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
|
lcnhappe/happe-master
|
arrayfilter.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/arrayfilter.m
| 488 |
utf_8
|
a2649b876169e3d850372917e57a8b68
|
% Filter elements of array that meet a condition.
% Copyright 2010 Levente Hunyadi
function array = arrayfilter(fun, array)
validateattributes(fun, {'function_handle'}, {'scalar'});
if isobject(array)
filter = false(size(array));
for k = 1 : numel(filter)
filter(k) = fun(array(k));
end
else
filter = arrayfun(fun, array); % logical indicator array of elements that satisfy condition
end
array = array(filter); % array of elements that meet condition
|
github
|
lcnhappe/happe-master
|
example_propertygrid.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/example_propertygrid.m
| 4,929 |
utf_8
|
f1e5d6dc7fc518cdb070956ff714353c
|
% Demonstrates how to use the property pane.
%
% See also: PropertyGrid
% Copyright 2010 Levente Hunyadi
function example_propertygrid
properties = [ ...
PropertyGridField('double', pi, ...
'Category', 'Primitive types', ...
'DisplayName', 'real double', ...
'Description', 'Standard MatLab type.') ...
PropertyGridField('single', pi, ...
'Category', 'Primitive types', ...
'DisplayName', 'real single', ...
'Description', 'Single-precision floating point number.') ...
PropertyGridField('integer', int32(23), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value.') ...
PropertyGridField('interval', int32(2), ...
'Type', PropertyType('int32', 'scalar', [0 6]), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value with an interval domain.') ...
PropertyGridField('enumerated', int32(-1), ...
'Type', PropertyType('int32', 'scalar', {int32(-1), int32(0), int32(1)}), ...
'Category', 'Primitive types', ...
'DisplayName', 'int32', ...
'Description', 'A 32-bit integer value with an enumerated domain.') ...
PropertyGridField('logical', true, ...
'Category', 'Primitive types', ...
'DisplayName', 'logical', ...
'Description', 'A Boolean value that takes either true or false.') ...
PropertyGridField('doublematrix', [], ...
'Type', PropertyType('denserealdouble', 'matrix'), ...
'Category', 'Compound types', ...
'DisplayName', 'real double matrix', ...
'Description', 'Matrix of standard MatLab type with empty initial value.') ...
PropertyGridField('string', 'a sample string', ...
'Category', 'Compound types', ...
'DisplayName', 'string', ...
'Description', 'A row vector of characters.') ...
PropertyGridField('rowcellstr', {'a sample string','spanning multiple','lines'}, ...
'Category', 'Compound types', ...
'DisplayName', 'cell row of strings', ...
'Description', 'A row cell array whose every element is a string (char array).') ...
PropertyGridField('colcellstr', {'a sample string';'spanning multiple';'lines'}, ...
'Category', 'Compound types', ...
'DisplayName', 'cell column of strings', ...
'Description', 'A column cell array whose every element is a string (char array).') ...
PropertyGridField('season', 'spring', ...
'Type', PropertyType('char', 'row', {'spring','summer','fall','winter'}), ...
'Category', 'Compound types', ...
'DisplayName', 'string', ...
'Description', 'A row vector of characters that can take any of the predefined set of values.') ...
PropertyGridField('set', [true false true], ...
'Type', PropertyType('logical', 'row', {'A','B','C'}), ...
'Category', 'Compound types', ...
'DisplayName', 'set', ...
'Description', 'A logical vector that serves an indicator of which elements from a universe are included in the set.') ...
PropertyGridField('root', [], ... % [] (and no type explicitly set) indicates that value is not editable
'Category', 'Compound types', ...
'DisplayName', 'root node') ...
PropertyGridField('root.parent', int32(23), ...
'Category', 'Compound types', ...
'DisplayName', 'parent node') ...
PropertyGridField('root.parent.child', int32(2007), ...
'Category', 'Compound types', ...
'DisplayName', 'child node') ...
];
% arrange flat list into a hierarchy based on qualified names
properties = properties.GetHierarchy();
% create figure
f = figure( ...
'MenuBar', 'none', ...
'Name', 'Property grid demo - Copyright 2010 Levente Hunyadi', ...
'NumberTitle', 'off', ...
'Toolbar', 'none');
% procedural usage
g = PropertyGrid(f, ... % add property pane to figure
'Properties', properties, ... % set properties explicitly
'Position', [0 0 0.5 1]);
h = PropertyGrid(f, ...
'Position', [0.5 0 0.5 1]);
% declarative usage, bind object to grid
obj = SampleObject; % a value object
h.Item = obj; % bind object, discards any previously set properties
% update the type of a property assigned with type autodiscovery
userproperties = PropertyGridField.GenerateFrom(obj);
userproperties.FindByName('IntegerMatrix').Type = PropertyType('denserealdouble', 'matrix');
disp(userproperties.FindByName('IntegerMatrix').Type);
h.Bind(obj, userproperties);
% wait for figure to close
uiwait(f);
% display all properties and their values on screen
disp('Left-hand property grid');
disp(g.GetPropertyValues());
disp('Right-hand property grid');
disp(h.GetPropertyValues());
disp('SampleObject (modified)');
disp(h.Item);
disp('SampleNestedObject (modified)');
disp(h.Item.NestedObject);
|
github
|
lcnhappe/happe-master
|
constructor.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/constructor.m
| 2,078 |
utf_8
|
c67e647ec8055710896666c9e83b45e0
|
% Sets public properties of a MatLab object using a name-value list.
% Properties are traversed in the order they occur in the class definition.
% Copyright 2008-2009 Levente Hunyadi
function obj = constructor(obj, varargin)
assert(isobject(obj), ...
'Function operates on MatLab new-style objects only.');
if nargin <= 1
return;
end
if isa(obj, 'hgsetget')
set(obj, varargin{:});
return;
end
assert(is_name_value_list(varargin), ...
'constructor:ArgumentTypeMismatch', ...
'A list of property name--value pairs is expected.');
% instantiate input parser object
parser = inputParser;
% query class properties using meta-class facility
metaobj = metaclass(obj);
properties = metaobj.Properties;
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property)
parser.addParamValue(property.Name, obj.(property.Name));
end
end
% set property values according to name-value list
parser.parse(varargin{:});
for i = 1 : numel(properties)
property = properties{i};
if is_public_property(property) && ~is_string_in_vector(property.Name, parser.UsingDefaults) % do not set defaults
obj.(property.Name) = parser.Results.(property.Name);
end
end
function tf = is_name_value_list(list)
% True if the specified list is a name-value list.
%
% Input arguments:
% list:
% a name-value list as a cell array.
validateattributes(list, {'cell'}, {'vector'});
n = numel(list);
if mod(n, 2) ~= 0
% a name-value list has an even number of elements
tf = false;
else
for i = 1 : 2 : n
if ~ischar(list{i})
% each odd element in a name-value list must be a char array
tf = false;
return;
end
end
tf = true;
end
function tf = is_string_in_vector(str, vector)
tf = any(strcmp(str, vector));
function tf = is_public_property(property)
% True if the property designates a public, accessible property.
tf = ~property.Abstract && ~property.Hidden && strcmp(property.GetAccess, 'public') && strcmp(property.SetAccess, 'public');
|
github
|
lcnhappe/happe-master
|
nestedassign.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/nestedassign.m
| 1,457 |
utf_8
|
12d661bb4df3c64a0707a06f7e3e6afc
|
% Assigns the given value to the named property of an object or structure.
% This function can deal with nested properties.
%
% Input arguments:
% obj:
% the structure, handle or value object the value should be assigned to
% name:
% a property name with dot (.) separating property names at
% different hierarchy levels
% value:
% the value to assign to the property at the deepest hierarchy
% level
%
% Output arguments:
% obj:
% the updated object or structure, optional for handle objects
%
% Example:
% obj = struct('surface', struct('nested', 10));
% obj = nestedassign(obj, 'surface.nested', 23);
% disp(obj.surface.nested); % prints 23
%
% See also: nestedfetch
% Copyright 2010 Levente Hunyadi
function obj = nestedassign(obj, name, value)
if ~iscell(name)
nameparts = strsplit(name, '.');
else
nameparts = name;
end
obj = nestedassign_recurse(obj, nameparts, value);
end
function obj = nestedassign_recurse(obj, name, value)
% Assigns the given value to the named property of an object.
%
% Input arguments:
% obj:
% the handle or value object the value should be assigned to
% name:
% a cell array of the composite property name
% value:
% the value to assign to the property at the deepest hierarchy
% level
if numel(name) > 1
obj.(name{1}) = nestedassign_recurse(obj.(name{1}), name(2:end), value);
else
obj.(name{1}) = value;
end
end
|
github
|
lcnhappe/happe-master
|
javaArrayList.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/dependencies/PropertyGrid-2010-09-16-mod/javaArrayList.m
| 740 |
utf_8
|
cb4ad03c4e0fc536bc1ae024bfb8920a
|
% Converts a MatLab array into a java.util.ArrayList.
%
% Input arguments:
% array:
% a MatLab row or column vector (with elements of any type)
%
% Output arguments:
% list:
% a java.util.ArrayList instance
%
% See also: javaArray
% Copyright 2010 Levente Hunyadi
function list = javaArrayList(array)
list = java.util.ArrayList;
if ~isempty(array)
assert(isvector(array), 'javaArrayList:DimensionMismatch', ...
'Row or column vector expected.');
if iscell(array) % convert cell array into ArrayList
for k = 1 : numel(array)
list.add(array{k});
end
else % convert (numeric) array into ArrayList
for k = 1 : numel(array)
list.add(array(k));
end
end
end
|
github
|
lcnhappe/happe-master
|
hlp_scope.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_scope.m
| 3,366 |
utf_8
|
4544c2a11f66464cc00f860f36646304
|
function varargout = hlp_scope(assignments, f, varargin)
% Execute a function within a dynamic scope of values assigned to symbols.
% Results... = hlp_scope(Assignments, Function, Arguments...)
%
% This is the only completely reliable way in MATLAB to ensure that symbols that should be assigned
% while a function is running get cleared after the function returns orderly, crashes, segfaults,
% the user slams Ctrl+C, and so on. Symbols can be looked up via hlp_resolve().
%
% In:
% Assignments : Cell array of name-value pairs or a struct. Values are associated with symbols of
% the given names. The names should be valid MATLAB identifiers. These assigments
% form a dynamic scope for the execution of the function; scopes can also be
% nested, and assignments in inner scopes override those of outer scopes.
%
% Function : a function handle to invoke
%
% Arguments... : arguments to pass to the function
%
% Out:
% Results... : return value(s) of the function
%
% See also:
% hlp_resolve
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-05-03
% add a new stack frame with the evaluated assignments & get its unique id
id = make_stackframe(assignments);
% also take care that it gets reclaimed after we're done
reclaimer = onCleanup(@()return_stackframe(id));
% make a function that is tagged by id
func = make_func(id);
% evaluate the function with the id introduced into MATLAB's own stack
[varargout{1:nargout}] = func(f,varargin);
function func = make_func(id)
persistent funccache; % (cached, since the eval() below is a bit slow)
try
func = funccache.(id);
catch
func = eval(['@(f,a,frame__' id ')feval(f,a{:})']);
funccache.(id) = func;
end
function id = make_stackframe(assignments)
% put the assignments into a struct
if iscell(assignments)
assignments = cell2struct(assignments(2:2:end),assignments(1:2:end),2); end
% get a fresh frame id
global tracking;
try
id = tracking.stack.frameids.removeLast();
catch
if ~isfield(tracking,'stack') || ~isfield(tracking.stack,'frameids')
% need to create the id repository first
tracking.stack.frameids = java.util.concurrent.LinkedBlockingDeque();
for k=50000:-1:1
tracking.stack.frameids.addLast(sprintf('f%d',k)); end
else
if tracking.stack.frameids.size() == 0
% if this happens then either you have 10.000s of parallel executions of hlp_scope(),
% or you have a very deep recursion level (the MATLAB default is 500), or your function
% has crashed 10.000s of times in a way that keeps onCleanup from doing its job, or you have
% substituted onCleanup by a dummy class or function that doesn't actually work (e.g. on
% pre-2008a systems).
error('We ran out of stack frame ids. This should not happen under normal conditions. Please make sure that your onCleanup implementation is not consistently failing to execute.');
end
end
id = tracking.stack.frameids.removeLast();
end
% and store the assignments under it
tracking.stack.frames.(id) = assignments;
function return_stackframe(id)
% finally return the frame id again...
global tracking;
tracking.stack.frameids.addLast(id);
|
github
|
lcnhappe/happe-master
|
hlp_fingerprint.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_fingerprint.m
| 7,085 |
utf_8
|
ebeb87c5f5aa958473e853a153d261f9
|
function fp = hlp_fingerprint(data)
% Make a fingerprint (hash) of the given data structure.
% Fingerprint = hlp_fingerprint(Data)
%
% This includes all contents; however, large arrays (such as EEG.data) are only spot-checked. For
% thorough checking, use hlp_cryptohash.
%
% In:
% Data : some data structure
%
% Out:
% Fingerprint : an integer that identifies the data
%
% Notes:
% The fingerprint is not unique and identifies the data set only with a certain (albeit high)
% probability.
%
% On MATLAB versions prior to 2008b, hlp_fingerprint cannot be used concurrently from timers,
% and also may alter the random generator's state if cancelled via Ctrl+C.
%
% Examples:
% % calculate the hash of a large data structure
% hash = hlp_fingerprint(data);
%
% See also:
% hlp_cryptohash
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-02
warning off MATLAB:structOnObject
if hlp_matlab_version >= 707
fp = fingerprint(data,RandStream('swb2712','Seed',5183));
else
try
% save & override random state
randstate = rand('state'); %#ok<*RAND>
rand('state',5183);
% make the fingerprint
fp = fingerprint(data,0);
% restore random state
rand('state',randstate);
catch e
% restore random state in case of an error...
rand('state',randstate);
rethrow(e);
end
end
% make a fingerprint of the given data structure
function fp = fingerprint(data,rs)
% convert data into a string representation
data = summarize(data,rs);
% make sure that it does not contain 0's
data(data==0) = 'x';
% obtain a hash code via Java (MATLAB does not support proper integer arithmetic...)
str = java.lang.String(data);
fp = str.hashCode()+2^31;
% get a recursive string summary of arbitrary data
function x = summarize(x,rs)
if isnumeric(x)
% numeric array
if ~isreal(x)
x = [real(x) imag(x)]; end
if issparse(x)
x = [find(x) nonzeros(x)]; end
if numel(x) <= 4096
% small matrices are hashed completely
try
x = ['n' typecast([size(x) x(:)'],'uint8')];
catch
if hlp_matlab_version <= 702
x = ['n' typecast([size(x) double(x(:))'],'uint8')]; end
end
else
% large matrices are spot-checked
ne = numel(x);
count = floor(256 + (ne-256)/1000);
if hlp_matlab_version < 707
indices = 1+floor((ne-1)*rand(1,count));
else
indices = 1+floor((ne-1)*rand(rs,1,count));
end
if size(x,2) == 1
% x is a column vector: reindexed expression needs to be transposed
x = ['n' typecast([size(x) x(indices)'],'uint8')];
else
% x is a matrix or row vector: shape follows that of indices
x = ['n' typecast([size(x) x(indices)],'uint8')];
end
end
elseif iscell(x)
% cell array
sizeprod = cellfun('prodofsize',x(:));
if all(sizeprod <= 1) && any(sizeprod)
% all scalar elements (some empty, but not all)
if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single'))
% standard floating-point scalars
if cellfun('isreal',x)
% all real
x = ['cdr' typecast([size(x) x{:}],'uint8')];
else
% some complex
x = ['cdc' typecast([size(x) real([x{:}]) imag([x{:}])],'uint8')];
end
elseif cellfun('isclass',x(:),'logical')
% all logical
x = ['cl' typecast(uint32(size(x)),'uint8') uint8([x{:}])];
elseif cellfun('isclass',x(:),'char')
% all single chars
x = ['ccs' typecast(uint32(size(x)),'uint8') x{:}];
else
% generic types (structs, cells, integers, handles, ...)
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
elseif isempty(x)
% empty cell array
x = ['ce' typecast(uint32(size(x)),'uint8')];
else
% some non-scalar elements
dims = cellfun('ndims',x(:));
size1 = cellfun('size',x(:),1);
size2 = cellfun('size',x(:),2);
if all((size1+size2 == 0) & (dims == 2))
% all empty and nondegenerate elements
if all(cellfun('isclass',x(:),'double'))
% []'s
x = ['ced' typecast(uint32(size(x)),'uint8')];
elseif all(cellfun('isclass',x(:),'cell'))
% {}'s
x = ['cec' typecast(uint32(size(x)),'uint8')];
elseif all(cellfun('isclass',x(:),'struct'))
% struct()'s
x = ['ces' typecast(uint32(size(x)),'uint8')];
elseif length(unique(cellfun(@class,x(:),'UniformOutput',false))) == 1
% same class
x = ['cex' class(x{1}) typecast(uint32(size(x)),'uint8')];
else
% arbitrary class...
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
elseif all((cellfun('isclass',x(:),'char') & size1 <= 1) | (sizeprod==0 & cellfun('isclass',x(:),'double')))
% all horizontal strings or proper empty strings, possibly some []'s
x = ['cch' [x{:}] typecast(uint32(size2'),'uint8')];
else
% arbitrary sizes...
if all(cellfun('isclass',x(:),'double')) || all(cellfun('isclass',x(:),'single'))
% all standard floating-point types...
tmp = cellfun(@vectorize,x,'UniformOutput',false);
% treat as a big vector...
x = ['cn' typecast(uint32(size(x)),'uint8') summarize([tmp{:}],rs)];
else
tmp = cellfun(@summarize,x,repmat({rs},size(x)),'UniformOutput',false);
x = ['cg' typecast(uint32(size(x)),'uint8') tmp{:}];
end
end
end
elseif ischar(x)
% char array
x = ['c' x(:)'];
elseif isstruct(x)
% struct
fn = fieldnames(x)';
if numel(x) > length(fn)
% summarize over struct fields to expose homogeneity
x = cellfun(@(f)summarize({x.(f)},rs),fn,'UniformOutput',false);
x = ['s' [fn{:}] ':' [x{:}]];
else
% summarize over struct elements
x = ['s' [fn{:}] ':' summarize(struct2cell(x),rs)];
end
elseif islogical(x)
% logical array
x = ['l' typecast(uint32(size(x)),'uint8') uint8(x(:)')];
elseif isa(x,'function_handle')
x = ['f ' char(x)];
elseif isobject(x)
x = ['o' class(x) ':' summarize(struct(x),rs)];
else
try
x = ['u' class(x) ':' summarize(struct(x),rs)];
catch
warning('BCILAB:hlp_fingerprint:unsupported_type','Unsupported type: %s',class(x));
error; %#ok<LTARG>
end
end
function x = vectorize(x)
x = x(:)';
|
github
|
lcnhappe/happe-master
|
hlp_flattensearch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_flattensearch.m
| 4,217 |
utf_8
|
9f21976c4c355a8c0ac9432e74a4d31d
|
function x = hlp_flattensearch(x,form)
% Flatten search() clauses in a nested data structure into a flat search() clause.
% Result = hlp_flattensearch(Expression, Output-Form)
%
% Internal tool used by utl_gridsearch to enable the specification of search parameters using
% search() clauses.
%
% In:
% Expression : some data structure, usually an argument to utl_gridsearch, may or may not contain
% nested search clauses.
%
% Output-Form : form of the output (default: 'search')
% * 'search': the output shall be a flattened search clause (or a plain value if no
% search)
% * 'cell': the output shall be a cell array of elements to search over
%
% Out:
% Result : a flattened search clause (or plain value), or a cell array of search possibilities.
%
% See also:
% search, utl_gridsearch
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-06-29
x = flatten(x);
if ~exist('form','var') || isempty(form) || strcmp(form,'search')
% turn from cell format into search format
if isscalar(x)
% just one option: return the plain value
x = x{1};
else
% multiple options: return a search expression
x = struct('head',{@search},'parts',{x});
end
elseif ~strcmp(form,'cell')
error(['Unsupported output form: ' form]);
end
% recursively factor search expressions out of a data structure, to give an overall search
% expression (output format is cell array of search options)
function parts = flatten(x)
if isstruct(x)
if isfield(x,{'data','srate','chanlocs','event','epoch'})
% data set? do not descend further
parts = {x};
elseif all(isfield(x,{'head','parts'})) && numel(x)==1 && strcmp(char(x.head),'search')
% search expression: flatten any nested searches...
parts = cellfun(@flatten,x.parts,'UniformOutput',false);
% ... and splice their parts in
parts = [parts{:}];
else
% generic structure: create a cartesian product over field-wise searches
if isscalar(x)
parts = {x};
% flatten per-field contents
fields = cellfun(@flatten,struct2cell(x),'UniformOutput',false);
lengths = cellfun('length',fields);
% was any one a search?
if any(lengths>1)
fnames = fieldnames(x);
% for each field that is a search...
for k=find(lengths>1)'
% replicate all parts once for each search item in the current field
partnum = length(parts);
parts = repmat(parts,1,lengths(k));
% and fill each item into the appropriate place
for j=1:length(parts)
parts{j}.(fnames{k}) = fields{k}{ceil(j/partnum)}; end
end
end
elseif ~isempty(x)
% struct array (either with nested searches or a concatenation of search() expressions):
% handle as a cell array of structs
parts = flatten(arrayfun(@(s){s},x));
% got a search?
if ~isscalar(parts)
% re-concatenate the cell contents of each part of the search expression into
% struct arrays
for i=1:length(parts)
parts{i} = reshape([parts{i}{:}],size(parts{i})); end
else
parts = {x};
end
else
parts = {x};
end
end
elseif iscell(x)
% cell array: create a cartesian product over cell-wise searches
parts = {x};
x = cellfun(@flatten,x,'UniformOutput',false);
% for each cell that is a search...
for c=find(cellfun('length',x(:)')>1)
% replicate all parts once for each search item in the current cell
partnum = length(parts);
parts = repmat(parts,1,length(x{c}));
% and fill in the new item in the appropriate place
for j=1:length(parts)
parts{j}{c} = x{c}{ceil(j/partnum)}; end
end
else
% anything else: wrap
parts = {x};
end
|
github
|
lcnhappe/happe-master
|
hlp_tostring.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_tostring.m
| 6,536 |
utf_8
|
7c374a9f8a1954f5289b4e446ea1a30d
|
function str = hlp_tostring(v)
% Get an human-readable string representation of a data structure.
% String = hlp_tostring(Data)
%
% The resulting string representations are usually executable, but there are corner cases (e.g.,
% certain anonymous function handles and large data sets), which are not supported. For
% general-purpose serialization, see hlp_serialize/hlp_deserialize.
%
% In:
% Data : a data structure
%
% Out:
% String : string form of the data structure
%
% Notes:
% hlp_tostring has builtin support for displaying expression data structures.
%
% Examples:
% % get a string representation of a data structure
% hlp_tostring({'test',[1 2 3], struct('field','value')})
%
% See also:
% hlp_serialize
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-15
%
% adapted from serialize.m
% (C) 2006 Joger Hansegord ([email protected])
n = 15;
str = serializevalue(v,n);
%
% Main hub for serializing values
%
function val = serializevalue(v, n)
if isnumeric(v) || islogical(v)
val = serializematrix(v, n);
elseif ischar(v)
val = serializestring(v, n);
elseif isa(v,'function_handle')
val = serializefunction(v, n);
elseif is_impure_expression(v)
val = serializevalue(v.tracking.expression, n);
elseif has_canonical_representation(v)
val = serializeexpression(v, n);
elseif is_dataset(v)
val = serializedataset(v, n);
elseif isstruct(v)
val = serializestruct(v, n);
elseif iscell(v)
val = serializecell(v, n);
elseif isobject(v)
val = serializeobject(v, n);
else
try
val = serializeobject(v, n);
catch
error('Unhandled type %s', class(v));
end
end
%
% Serialize a string
%
function val = serializestring(v,n)
if any(v == '''')
val = ['''' strrep(v,'''','''''') ''''];
try
if ~isequal(eval(val),v)
val = ['char(' serializevalue(uint8(v), n) ')']; end
catch
val = ['char(' serializevalue(uint8(v), n) ')'];
end
else
val = ['''' v ''''];
end
%
% Serialize a matrix and apply correct class and reshape if required
%
function val = serializematrix(v, n)
if ndims(v) < 3
if isa(v, 'double')
if size(v,1) == 1 && length(v) > 3 && isequal(v,v(1):v(2)-v(1):v(end))
% special case: colon sequence
if v(2)-v(1) == 1
val = ['[' num2str(v(1)) ':' num2str(v(end)) ']'];
else
val = ['[' num2str(v(1)) ':' num2str(v(2)-v(1)) ':' num2str(v(end)) ']'];
end
elseif size(v,2) == 1 && length(v) > 3 && isequal(v',v(1):v(2)-v(1):v(end))
% special case: colon sequence
if v(2)-v(1) == 1
val = ['[' num2str(v(1)) ':' num2str(v(end)) ']'''];
else
val = ['[' num2str(v(1)) ':' num2str(v(2)-v(1)) ':' num2str(v(end)) ']'''];
end
else
val = mat2str(v, n);
end
else
val = mat2str(v, n, 'class');
end
else
if isa(v, 'double')
val = mat2str(v(:), n);
else
val = mat2str(v(:), n, 'class');
end
val = sprintf('reshape(%s, %s)', val, mat2str(size(v)));
end
%
% Serialize a cell
%
function val = serializecell(v, n)
if isempty(v)
val = '{}';
return
end
cellSep = ', ';
if isvector(v) && size(v,1) > 1
cellSep = '; ';
end
% Serialize each value in the cell array, and pad the string with a cell
% separator.
vstr = cellfun(@(val) [serializevalue(val, n) cellSep], v, 'UniformOutput', false);
vstr{end} = vstr{end}(1:end-2);
% Concatenate the elements and add a reshape if requied
val = [ '{' vstr{:} '}'];
if ~isvector(v)
val = ['reshape(' val sprintf(', %s)', mat2str(size(v)))];
end
%
% Serialize an expression
%
function val = serializeexpression(v, n)
if numel(v) > 1
val = ['['];
for k = 1:numel(v)
val = [val serializevalue(v(k), n), ', ']; end
val = [val(1:end-2) ']'];
else
if numel(v.parts) > 0
val = [char(v.head) '('];
for fieldNo = 1:numel(v.parts)
val = [val serializevalue(v.parts{fieldNo}, n), ', ']; end
val = [val(1:end-2) ')'];
else
val = char(v.head);
end
end
%
% Serialize a data set
%
function val = serializedataset(v, n) %#ok<INUSD>
val = '<EEGLAB data set>';
%
% Serialize a struct by converting the field values using struct2cell
%
function val = serializestruct(v, n)
fieldNames = fieldnames(v);
fieldValues = struct2cell(v);
if ndims(fieldValues) > 6
error('Structures with more than six dimensions are not supported');
end
val = 'struct(';
for fieldNo = 1:numel(fieldNames)
val = [val serializevalue( fieldNames{fieldNo}, n) ', '];
val = [val serializevalue( permute(fieldValues(fieldNo, :,:,:,:,:,:), [2:ndims(fieldValues) 1]) , n) ];
val = [val ', '];
end
if numel(fieldNames)==0
val = [val ')'];
else
val = [val(1:end-2) ')'];
end
if ~isvector(v)
val = sprintf('reshape(%s, %s)', val, mat2str(size(v)));
end
%
% Serialize an object by converting to struct and add a call to the copy
% contstructor
%
function val = serializeobject(v, n)
val = sprintf('%s(%s)', class(v), serializevalue(struct(v), n));
function val = serializefunction(v, n) %#ok<INUSD>
try
val = ['@' char(get_function_symbol(v))];
catch
val = char(v);
end
function result___ = get_function_symbol(expression___)
% internal: some function_handle expressions have a function symbol (an @name expression), and this function obtains it
% note: we are using funny names here to bypass potential name conflicts within the eval() clause further below
if ~isa(expression___,'function_handle')
error('the expression has no associated function symbol.'); end
string___ = char(expression___);
if string___(1) == '@'
% we are dealing with a lambda function
if is_symbolic_lambda(expression___)
result___ = eval(string___(27:end-21));
else
error('cannot derive a function symbol from a non-symbolic lambda function.');
end
else
% we are dealing with a regular function handle
result___ = expression___;
end
function res = is_symbolic_lambda(x)
% internal: a symbolic lambda function is one which generates expressions when invoked with arguments (this is what exp_symbol generates)
res = isa(x,'function_handle') && ~isempty(regexp(char(x),'@\(varargin\)struct\(''head'',\{.*\},''parts'',\{varargin\}\)','once'));
|
github
|
lcnhappe/happe-master
|
hlp_config.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_config.m
| 12,881 |
utf_8
|
7b49f69371781d0161c3a842064a43d0
|
function result = hlp_config(configname, operation, varargin)
% helper function to process human-readable config scripts.
% Result = hlp_config(FileName,Operation,VariableName,Value,NVPs...)
%
% Config scripts consist of assignments of the form name = value; to set configuration options. In
% addition, there may be any type of comments, conditional control flow, etc - e.g., setting certain
% values on some platforms and others on others. This function allows to get or set the value
% assigned to a variable in the place of the script where it is actually assigned on the current
% platform. Note that the respective variable has to be already in the config file for this function
% to work.
%
% In:
% FileName : name of the configuration file to process
%
% Operation : operation to perform on the config file
% 'get' : get the currently defined value of a given variable
% 'set' : replace the current defintion of a given variable
%
% VariableName : name of the variable to be affected (must be a MATLAB identifier)
%
% Value : the new value to be assigned, if the operation is 'set', as a string
% note that most data structures can be converted into a string via hlp_tostring
%
% NVPs... : list of further name-value pairs, where each name denotes a config variables and the subsequent
% value is the string expression that should be written into the config file. It is
% generally a good idea to use hlp_tostring() to turn a data structure into such a string
% representation.
%
% Out:
% Result : the current value of the variable of interest, when using the 'get'
% operation
%
% Notes:
% There can be multiple successive variable name / value pairs for the set mode.
% If an error occurs during a set operation, any changes will be rolled back.
%
% Examples:
% % read out the value of the 'data' config variable from a config file
% data = hlp_config('/home/christian/myconfig.m','get','data')
%
% % override the values of the 'files' and 'capacity' config variables in the given config script
% hlp_config('/home/christian/myconfig.m', 'set', 'files',myfiles, 'capacity',1000)
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-11-19
if ~exist(configname,'file')
error('hlp_config:file_not_found','The specified config file was not found.'); end
switch operation
case 'get'
varname = varargin{1};
if ~isvarname(varname)
error('hlp_config:bad_varname','The variable name must be a valid MATLAB identifier.'); end
% get the currently defined value of a variable...
result = get_value(configname,varname);
case 'set'
backupfile = [];
try
% apply first assignment
backupfile = set_value(configname,varargin{1},varargin{2},true);
for k = 4:2:length(varargin)
% apply all other assignments
set_value(configname,varargin{k-1},varargin{k},false); end
catch e
% got an error; roll back changes if necessary
if ~isempty(backupfile)
try
movefile(backupfile,configname);
catch
disp(['Could not roll back changes. You can manually revert changes by replacing ' configname ' by ' backupfile '.']);
end
end
rethrow(e);
end
otherwise
error('hlp_config:unsupported_option','Unsupported config operation.');
end
% run the given config script and obtain the current value of the given variable...
function res = get_value(filename__,varname__)
try
run_script(filename__);
catch e
error('hlp_config:erroneous_file',['The config file is erroneous; Error message: ' e.message]);
end
if ~exist(varname__,'var')
error('hlp_config:var_not_found','The variable is not being defined in the config file.'); end
res = eval(varname__);
function backup_name = set_value(filename,varname,newvalue,makebackup)
backup_name = [];
if ~exist(filename,'file')
error('hlp_config:file_not_found','The config file was not found.'); end
if ~isvarname(varname)
error('hlp_config:incorrect_value','The variable name must be a valid MATLAB identifier.'); end
if ~ischar(newvalue)
error('hlp_config:incorrect_value','The value to be assigned must be given as a string.'); end
try
% read the config file contents
contents = {};
f = fopen(filename,'r');
while 1
l = fgetl(f);
if ~ischar(l)
break; end
contents{end+1} = [l 10];
end
fclose(f);
% turn it into one str
contents = [contents{:}];
catch e
try fclose(f); catch,end
error('hlp_config:cannot_read_config',['Cannot read the config file; Error message: ' e.message]);
end
% now check if the file is actually writable
try
f = fopen(filename,'r+');
if f ~= -1
fclose(f);
else
error('hlp_config:permissions_error','Could not update the config file %s. Please check file permissions and try again.',filename);
end
catch
error('hlp_config:permissions_error','Could not update the config file %s. Please check file permissions and try again.',filename);
end
% temporarily replace stray semicolons by a special character and contract ellipses,
% so that the subsequent assignment regex matching will not get derailed)
evalstr = contents;
comment_flag = false;
string_flag = false;
bracket_level = 0;
ellipsis_flag = false;
substitute = false(1,length(evalstr)); % this mask indicates where we have to subsitute reversibly by special characters
spaceout = false(1,length(evalstr)); % this mask indicates where we can substitute irreversibly by whitespace characters...
for k=1:length(evalstr)
if ellipsis_flag
% everything that follows an ellipsis will be spaced out (including the subsequent newline that resets it)
spaceout(k) = true; end
switch evalstr(k)
case ';' % semicolon
% in strs, brackets or comments: indicate need for substitution
if string_flag || bracket_level>0 || comment_flag
substitute(k) = true; end
case '''' % quotes
% flip str flag, unless in comment
if ~comment_flag
string_flag = ~string_flag; end
case 10 % newline
% reset bracket level, unless in ellipsis
if ~ellipsis_flag
bracket_level = 0; end
% reset comment flag, str flag and ellipsis flag
comment_flag = false;
string_flag = false;
ellipsis_flag = false;
case {'[','{'} % opening array bracket
% if not in str nor comment, increase bracket level
if ~string_flag && ~comment_flag
bracket_level = bracket_level+1; end
case {']','}'} % closing array bracket
% if not in str nor comment, decrease bracket level
if ~string_flag && ~comment_flag
bracket_level = bracket_level-1; end
case '%' % comment character
% if not in str, switch on comment flag
if ~string_flag
comment_flag = true; end
case '.' % potential ellipsis character
% if not in comment nor in str, turn on ellipsis and comment
if ~string_flag && ~comment_flag && k>2 && strcmp(evalstr(k-2:k),'...')
ellipsis_flag = true;
comment_flag = true;
% we want to replace the ellipsis and everything that follows up to and including the next newline
spaceout(k-2:k) = true;
end
end
end
% replace the characters that need to be substituted (by the bell character)
evalstr(substitute) = 7;
evalstr(spaceout) = ' ';
% replace all assignments of the form "varname = *;" by "varname{end+1} = num;"
[starts,ends] = regexp(evalstr,[varname '\s*=[^;\n]*;']);
for k=length(starts):-1:1
evalstr = [evalstr(1:starts(k)-1) varname '{end+1} = struct(''assignment'',' num2str(k) ');' evalstr(ends(k)+1:end)]; end
% add initial assignment
evalstr = [sprintf('%s = {};\n',varname) evalstr];
% back-substitute the special character by semicolons
evalstr(evalstr==7) = ';';
% evaluate contents and get the matching assignment id's
ids = run_protected(evalstr,varname);
% check validity of the updated value, and of the updated config file
try
% check if the value str can in fact be evaluated
newvalue_eval = eval(newvalue);
catch
error('hlp_config:incorrect_value','The value "%s" (to be assigned to variable "%s") cannot be evaluated properly. Note that, for example, string values need to be quoted.',newvalue,varname);
end
% evaluate the original config script and record the full variable assignment
[dummy,wspace_old] = run_protected(contents); %#ok<ASGLU>
% splice the new value into the config file contents, for the last assignment in ids
id = ids{end}.assignment;
contents = [contents(1:starts(id)-1) varname ' = ' newvalue ';' contents(ends(id)+1:end)];
% evaluate the new config script and record the full variable assignment
[dummy,wspace_new] = run_protected(contents); %#ok<ASGLU>
% make sure that the only thing that has changed is the assignment to the variable of interest
wspace_old.(varname) = newvalue_eval;
if ~isequalwithequalnans(wspace_old,wspace_new)
error('hlp_config:update_failed','The config file can not be properly updated.'); end
% apparently, everything went well, except for the following possibilities
% * the newly assigned value makes no sense (--> usage error)
% * the settings were changed for unanticipated platforms (--> this needs to be documented properly)
if makebackup
try
% make a backup of the original config file using a fresh name (.bak00X)
[p,n,x] = fileparts(filename);
files = dir([p filesep n '*.bak*']);
backup_numbers = cellfun(@(n)str2num(n(end-2:end)),{files.name},'UniformOutput',false);
backup_numbers = [backup_numbers{:}];
if ~isempty(backup_numbers)
new_number = 1 + max(backup_numbers);
else
new_number = 1;
end
backup_name = [p filesep n '.bak' sprintf('%03i',new_number)];
copyfile(filename,backup_name);
% set read permissions
warning off MATLAB:FILEATTRIB:SyntaxWarning
fileattrib(backup_name,'+w','a');
catch
error('hlp_config:permissions_error','Could not create a backup of the original config file %s. Please check file permissions and try again.',filename);
end
end
% split the contents into lines again
contents = strsplit(contents,10);
try
% re-create the file, line by line
f = fopen(filename,'w+');
for k=1:length(contents)
fwrite(f,contents{k});
fprintf(f,'\n');
end
fclose(f);
% set file attributes
warning off MATLAB:FILEATTRIB:SyntaxWarning
fileattrib(filename,'+w','a');
catch
try fclose(f); catch,end
error('hlp_config:permissions_error','Could not override the config file %s. Please check file permissions and try again.',filename);
end
% run the given config script and obtain the current value of the given variable...
function [res,wspace] = run_protected(code__,varname__)
try
eval(code__);
% collect all variables into a workspace struct
infos = whos();
for n = {infos.name}
if ~any(strcmp(n{1},{'code__','varname__'}))
wspace.(n{1}) = eval(n{1}); end
end
if exist('varname__','var')
% if a specific variable was to be inspected...
res = eval(varname__);
if ~iscell(res) || length(res) < 1 || ~all(cellfun('isclass',res,'struct')) || ~all(cellfun(@(x)isfield(x,'assignment'),res))
error('Not all assignments to the variable were correctly identified.'); end
else
res = [];
end
catch e
error('hlp_config:update_error',['The config file could not be parsed (probably it is ill-formed); Debug message: ' e.message]);
end
% split a string without fusing delimiters (unlike hlp_split)
function strs = strsplit(str, delim)
idx = strfind(str, delim);
strs = cell(numel(idx)+1, 1);
idx = [0 idx numel(str)+1];
for k = 2:numel(idx)
strs{k-1} = str(idx(k-1)+1:idx(k)-1); end
% for old MATLABs that can't properly move files...
function movefile(src,dst)
try
builtin('movefile',src,dst);
catch e
if any([src dst]=='$') && hlp_matlab_version <= 705
if ispc
[errcode,text] = system(sprintf('move ''%s'' ''%s''',src,dst)); %#ok<NASGU>
else
[errcode,text] = system(sprintf('mv ''%s'' ''%s''',src,dst)); %#ok<NASGU>
end
if errcode
error('Failed to move %s to %s.',src,dst); end
else
rethrow(e);
end
end
|
github
|
lcnhappe/happe-master
|
hlp_deserialize.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_deserialize.m
| 12,045 |
utf_8
|
5973cf16c3a0b718e9f334724d312870
|
function v = hlp_deserialize(m)
% Convert a serialized byte vector back into the corresponding MATLAB data structure.
% Data = hlp_deserialize(Bytes)
%
% In:
% Bytes : a representation of the original data as a byte stream
%
% Out:
% Data : some MATLAB data structure
%
%
% See also:
% hlp_serialize
%
% Examples:
% bytes = hlp_serialize(mydata);
% ... e.g. transfer the 'bytes' array over the network ...
% mydata = hlp_deserialize(bytes);
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-02
%
% adapted from deserialize.m
% (C) 2010 Tim Hutt
% wrap dispatcher
v = deserialize_value(uint8(m(:)),1);
end
% dispatch
function [v,pos] = deserialize_value(m,pos)
switch m(pos)
case {0,200}
[v,pos] = deserialize_string(m,pos);
case 128
[v,pos] = deserialize_struct(m,pos);
case {33,34,35,36,37,38,39}
[v,pos] = deserialize_cell(m,pos);
case {1,2,3,4,5,6,7,8,9,10}
[v,pos] = deserialize_scalar(m,pos);
case 133
[v,pos] = deserialize_logical(m,pos);
case {151,152,153}
[v,pos] = deserialize_handle(m,pos);
case {17,18,19,20,21,22,23,24,25,26}
[v,pos] = deserialize_numeric_simple(m,pos);
case 130
[v,pos] = deserialize_sparse(m,pos);
case 131
[v,pos] = deserialize_complex(m,pos);
case 132
[v,pos] = deserialize_char(m,pos);
case 134
[v,pos] = deserialize_object(m,pos);
otherwise
error('Unknown class');
end
end
% individual scalar
function [v,pos] = deserialize_scalar(m,pos)
classes = {'double','single','int8','uint8','int16','uint16','int32','uint32','int64','uint64'};
sizes = [8,4,1,1,2,2,4,4,8,8];
sz = sizes(m(pos));
% Data.
v = typecast(m(pos+1:pos+sz),classes{m(pos)});
pos = pos + 1 + sz;
end
% standard string
function [v,pos] = deserialize_string(m,pos)
if m(pos) == 0
% horizontal string: tag
pos = pos + 1;
% length (uint32)
nbytes = double(typecast(m(pos:pos+3),'uint32'));
pos = pos + 4;
% data (chars)
v = char(m(pos:pos+nbytes-1))';
pos = pos + nbytes;
else
% proper empty string: tag
[v,pos] = deal('',pos+1);
end
end
% general char array
function [v,pos] = deserialize_char(m,pos)
pos = pos + 1;
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')');
pos = pos + ndms*4;
nbytes = prod(dms);
% Data.
v = char(m(pos:pos+nbytes-1));
pos = pos + nbytes;
v = reshape(v,[dms 1 1]);
end
% general logical array
function [v,pos] = deserialize_logical(m,pos)
pos = pos + 1;
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')');
pos = pos + ndms*4;
nbytes = prod(dms);
% Data.
v = logical(m(pos:pos+nbytes-1));
pos = pos + nbytes;
v = reshape(v,[dms 1 1]);
end
% simple numerical matrix
function [v,pos] = deserialize_numeric_simple(m,pos)
classes = {'double','single','int8','uint8','int16','uint16','int32','uint32','int64','uint64'};
sizes = [8,4,1,1,2,2,4,4,8,8];
cls = classes{m(pos)-16};
sz = sizes(m(pos)-16);
pos = pos + 1;
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')');
pos = pos + ndms*4;
nbytes = prod(dms) * sz;
% Data.
v = typecast(m(pos:pos+nbytes-1),cls);
pos = pos + nbytes;
v = reshape(v,[dms 1 1]);
end
% complex matrix
function [v,pos] = deserialize_complex(m,pos)
pos = pos + 1;
[re,pos] = deserialize_numeric_simple(m,pos);
[im,pos] = deserialize_numeric_simple(m,pos);
v = complex(re,im);
end
% sparse matrix
function [v,pos] = deserialize_sparse(m,pos)
pos = pos + 1;
% matrix dims
u = double(typecast(m(pos:pos+7),'uint64'));
pos = pos + 8;
v = double(typecast(m(pos:pos+7),'uint64'));
pos = pos + 8;
% index vectors
[i,pos] = deserialize_numeric_simple(m,pos);
[j,pos] = deserialize_numeric_simple(m,pos);
if m(pos)
% real
pos = pos+1;
[s,pos] = deserialize_numeric_simple(m,pos);
else
% complex
pos = pos+1;
[re,pos] = deserialize_numeric_simple(m,pos);
[im,pos] = deserialize_numeric_simple(m,pos);
s = complex(re,im);
end
v = sparse(i,j,s,u,v);
end
% struct array
function [v,pos] = deserialize_struct(m,pos)
pos = pos + 1;
% Number of field names.
nfields = double(typecast(m(pos:pos+3),'uint32'));
pos = pos + 4;
% Field name lengths
fnLengths = double(typecast(m(pos:pos+nfields*4-1),'uint32'));
pos = pos + nfields*4;
% Field name char data
fnChars = char(m(pos:pos+sum(fnLengths)-1)).';
pos = pos + length(fnChars);
% Number of dims
ndms = double(typecast(m(pos:pos+3),'uint32'));
pos = pos + 4;
% Dimensions
dms = typecast(m(pos:pos+ndms*4-1),'uint32')';
pos = pos + ndms*4;
% Field names.
fieldNames = cell(length(fnLengths),1);
splits = [0; cumsum(double(fnLengths))];
for k=1:length(splits)-1
fieldNames{k} = fnChars(splits(k)+1:splits(k+1)); end
% Content.
v = reshape(struct(),[dms 1 1]);
if m(pos)
% using struct2cell
pos = pos + 1;
[contents,pos] = deserialize_cell(m,pos);
v = cell2struct(contents,fieldNames,1);
else
% using per-field cell arrays
pos = pos + 1;
for ff = 1:nfields
[contents,pos] = deserialize_cell(m,pos);
[v.(fieldNames{ff})] = deal(contents{:});
end
end
end
% cell array
function [v,pos] = deserialize_cell(m,pos)
kind = m(pos);
pos = pos + 1;
switch kind
case 33 % arbitrary/heterogenous cell array
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = double(typecast(m(pos:pos+ndms*4-1),'uint32')');
pos = pos + ndms*4;
% Contents
v = cell([dms,1,1]);
for ii = 1:numel(v)
[v{ii},pos] = deserialize_value(m,pos); end
case 34 % cell scalars
[content,pos] = deserialize_value(m,pos);
v = cell(size(content));
for k=1:numel(v)
v{k} = content(k); end
case 35 % mixed-real cell scalars
[content,pos] = deserialize_value(m,pos);
v = cell(size(content));
for k=1:numel(v)
v{k} = content(k); end
[reality,pos] = deserialize_value(m,pos);
v(reality) = real(v(reality));
case 36 % cell array with horizontal or empty strings
[chars,pos] = deserialize_string(m,pos);
[lengths,pos] = deserialize_numeric_simple(m,pos);
[empty,pos] = deserialize_logical(m,pos);
v = cell(size(lengths));
splits = [0 cumsum(double(lengths(:)))'];
for k=1:length(lengths)
v{k} = chars(splits(k)+1:splits(k+1)); end
[v{empty}] = deal('');
case 37 % empty,known type
tag = m(pos);
pos = pos + 1;
switch tag
case 1 % double - []
prot = [];
case 33 % cell - {}
prot = {};
case 128 % struct - struct()
prot = struct();
otherwise
error('Unsupported type tag.');
end
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = typecast(m(pos:pos+ndms*4-1),'uint32')';
pos = pos + ndms*4;
% Create content
v = repmat({prot},dms);
case 38 % empty, prototype available
% Prototype.
[prot,pos] = deserialize_value(m,pos);
% Number of dims
ndms = double(m(pos));
pos = pos + 1;
% Dimensions
dms = typecast(m(pos:pos+ndms*4-1),'uint32')';
pos = pos + ndms*4;
% Create content
v = repmat({prot},dms);
case 39 % boolean flags
[content,pos] = deserialize_logical(m,pos);
v = cell(size(content));
for k=1:numel(v)
v{k} = content(k); end
otherwise
error('Unsupported cell array type.');
end
end
% object
function [v,pos] = deserialize_object(m,pos)
pos = pos + 1;
% Get class name.
[cls,pos] = deserialize_string(m,pos);
% Get contents
[conts,pos] = deserialize_value(m,pos);
% construct object
try
% try to use the loadobj function
v = eval([cls '.loadobj(conts)']);
catch
try
% pass the struct directly to the constructor
v = eval([cls '(conts)']);
catch
try
% try to set the fields manually
v = feval(cls);
for fn=fieldnames(conts)'
try
set(v,fn{1},conts.(fn{1}));
catch
% Note: if this happens, your deserialized object might not be fully identical
% to the original (if you are lucky, it didn't matter, through). Consider
% relaxing the access rights to this property or add support for loadobj from
% a struct.
warn_once('hlp_deserialize:restricted_access','No permission to set property %s in object of type %s.',fn{1},cls);
end
end
catch
v = conts;
v.hlp_deserialize_failed = ['could not construct class: ' cls];
end
end
end
end
% function handle
function [v,pos] = deserialize_handle(m,pos)
% Tag
kind = m(pos);
pos = pos + 1;
switch kind
case 151 % simple function
persistent db_simple; %#ok<TLEV> % database of simple functions (indexed by name)
% Name
[name,pos] = deserialize_string(m,pos);
try
% look up from table
v = db_simple.(name);
catch
% otherwise generate & fill table
v = str2func(name);
db_simple.(name) = v;
end
case 152 % anonymous function
% Function code
[code,pos] = deserialize_string(m,pos);
% Workspace
[wspace,pos] = deserialize_struct(m,pos);
% Construct
v = restore_function(code,wspace);
case 153 % scoped or nested function
persistent db_nested; %#ok<TLEV> % database of nested functions (indexed by name)
% Parents
[parentage,pos] = deserialize_cell(m,pos);
try
key = sprintf('%s_',parentage{:});
% look up from table
v = db_nested.(key);
catch
% recursively look up from parents, assuming that these support the arg system
v = parentage{end};
for k=length(parentage)-1:-1:1
% Note: if you get an error here, you are trying to deserialize a function handle
% to a nested function. This is not natively supported by MATLAB and can only be made
% to work if your function's parent implements some mechanism to return such a handle.
% The below call assumes that your function uses the BCILAB arg system to do this.
v = arg_report('handle',v,parentage{k});
end
db_nested.(key) = v;
end
end
end
% helper for deserialize_handle
function f = restore_function(decl__,workspace__)
% create workspace
for fn__=fieldnames(workspace__)'
% we use underscore names here to not run into conflicts with names defined in the workspace
eval([fn__{1} ' = workspace__.(fn__{1}) ;']);
end
clear workspace__ fn__;
% evaluate declaration
f = eval(decl__);
end
% emit a specific warning only once (per MATLAB session)
function warn_once(varargin)
persistent displayed_warnings;
% determine the message content
if length(varargin) > 1 && any(varargin{1}==':') && ~any(varargin{1}==' ') && ischar(varargin{2})
message_content = [varargin{1} sprintf(varargin{2:end})];
else
message_content = sprintf(varargin{1:end});
end
% generate a hash of of the message content
str = java.lang.String(message_content);
message_id = sprintf('x%.0f',str.hashCode()+2^31);
% and check if it had been displayed before
if ~isfield(displayed_warnings,message_id)
% emit the warning
warning(varargin{:});
% remember to not display the warning again
displayed_warnings.(message_id) = true;
end
end
|
github
|
lcnhappe/happe-master
|
hlp_aggregatestructs.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_aggregatestructs.m
| 7,805 |
utf_8
|
bab3d7ea8549fc71419a8fa5cb42447f
|
function res = hlp_aggregatestructs(structs,defaultop,varargin)
% Aggregate structs (recursively), using the given combiner operations.
% Result = hlp_aggregatestructs(Structs,Default-Op,Field-Ops...)
%
% This results in a single 1x1 struct which has aggregated values in its fields (e.g., arrays,
% averages, etc.). For a different use case, see hlp_superimposedata.
%
% In:
% Structs : cell array of structs to be aggregated (recursively) into a single struct
%
% Default-Op : optional default combiner operation to execute for every field that is not itself a
% struct; see notes for the format.
%
% Field-Ops : name-value pairs of field-specific ops; names can have dots to denote operations
% that apply to subfields. field-specific ops that apply to fields that are
% themselves structures become the default op for that sub-structure
%
% Out:
% recursively merged structure.
%
% Notes:
% If an operation cannot be applied, a sequence of fall-backs is silently applied. First,
% concatenation is tried, then, replacement is tried (which never fails). Therefore,
% function_handles are being concatenated up to 2008a, and replaced starting with 2008b.
% Operations are specified in one of the following formats:
% * 'cat': concatenate values horizontally using []
% * 'replace': replace values by those of later structs (noncommutative)
% * 'sum': sum up values
% * 'mean': compute the mean value
% * 'std': compute the standard deviation
% * 'median': compute the median value
% * 'random': pick a random value
% * 'fillblanks': replace [] by values of later structs
% * binary function: apply the function to aggregate pairs of values; applied in this order
% f(f(f(first,second),third),fourth)...
% * cell array of binary and unary function: apply the binary function to aggregate pairs of
% values, then apply the unary function to finalize the result: functions {b,u} are applied in
% the following order: u(b(b(b(first,second),third),fourth))
%
% Examples:
% % calc the average of the respective field values, across structs
% hlp_aggregatestructs({result1,result2,result3},'mean')
%
% % calc the std deviation of the respective field values, across structs
% hlp_aggregatestructs({result1,result2,result3},'std')
%
% % concatenate the field values across structs
% hlp_aggregatestructs({result1,result2,result3},'cat')
%
% % as before, but use different operations for a few fields
% hlp_aggregatestructs({result1,result2,result3},'cat','myfield1','mean','myfield2.subfield','median')
%
% % use a custom combiner operation (here: product)
% hlp_aggregatestructs({result1,result2,result3},@times)
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-05-04
warning off MATLAB:warn_r14_function_handle_transition
if ~exist('defaultop','var')
defaultop = 'cat'; end
if ~iscell(structs)
structs = {structs}; end
fieldops = hlp_varargin2struct(varargin);
% translate all ops (if they are specified as strings)
defaultop = translateop(defaultop);
fieldops = translateop(fieldops);
% aggregate, then finalize
res = finalize(aggregate(structs,defaultop,fieldops),defaultop,fieldops);
function res = aggregate(structs,defaultop,fieldops)
% we skip empty records
structs = structs(~cellfun('isempty',structs));
% for any struct array in the input, we first merge it recursively as if it were a cell array
for k=find(cellfun('length',structs)>1)
structs{k} = hlp_aggregatestructs(structarray2cellarray(structs{k}),defaultop,fieldops); end
% at this point, we should have a cell array of structs
if ~isempty(structs)
% we begin with the first struct
res = structs{1};
% and aggregate the remaining ones onto it
for i=2:length(structs)
si = structs{i};
% proceeding field by field...
for fn=fieldnames(si)'
f = fn{1};
% figure out which operation applies
if isfield(fieldops,f)
% a field-specific op applies
if isstruct(fieldops.(f))
% ... which is itself a struct
fop = fieldops.(f);
else
op = fieldops.(f);
end
else
% the default op applies
op = defaultop;
fop = fieldops;
end
% now process the field
if ~isfield(res,f)
% field is not yet in the aggregate: just assign
res.(f) = si.(f);
else
% need to aggregate it
if isstruct(res.(f)) && isstruct(si.(f))
% both are a struct: recursively aggregate
res.(f) = aggregate({res.(f),si.(f)},op,fop);
else
% they are not both structus
try
% try to apply the combiner op
res.(f) = op{1}(res.(f),si.(f));
catch
% didn't work: try to concatenate as fallback
try
res.(f) = [res.(f),si.(f)];
catch
% didn't work: try to assign as fallback (dropping previous field)
res.(f) = si.(f);
end
end
end
end
end
end
else
% nothing to aggregate
res = [];
end
function x = finalize(x,defaultop,fieldops)
% proceed field by field...
for fn=fieldnames(x)'
f = fn{1};
% figure out which operation applies
if ~isempty(fieldops) && isfield(fieldops,f)
% a field-specific op applies
if isstruct(fieldops.(f))
% ... which is itself a struct
fop = fieldops.(f);
else
op = fieldops.(f);
end
else
% the default op applies
op = defaultop;
fop = fieldops;
end
try
% now apply the finalizer
if isstruct(x.(f))
% we have a sub-struct: recurse
x.(f) = finalize(x.(f),op,fop);
else
% we have a regular element: apply finalizer
x.(f) = op{2}(x.(f));
end
catch
% for empty structs, x.(f) produces no output
end
end
% translate string ops into actual ops, add the default finalizer if missing
function op = translateop(op)
if isstruct(op)
% recurse
op = structfun(@translateop,op,'UniformOutput',false);
else
% remap strings
if ischar(op)
switch op
case 'cat'
op = @(a,b)[a b];
case 'replace'
op = @(a,b)b;
case 'sum'
op = @(a,b)a+b;
case 'mean'
op = {@(a,b)[a b], @(x)mean(x)};
case 'median'
op = {@(a,b)[a b], @(x)median(x)};
case 'std'
op = {@(a,b)[a b], @(x)std(x)};
case 'random'
op = {@(a,b)[a b], @(x) x(min(length(x),ceil(eps+rand(1)*length(x))))};
case 'fillblanks'
op = @(a,b)fastif(isempty(a),b,a);
otherwise
error('unsupported combiner op specified');
end
end
% add finalizer if missing
if ~iscell(op)
op = {op,@(x)x}; end
end
% inefficiently turn a struct array into a cell array of structs
function res = structarray2cellarray(arg)
res = {};
for k=1:numel(arg)
res = [res {arg(k)}]; end
% for the 'fillblanks' translate op
function val = fastif(cond,trueval,falseval)
if cond
val = trueval;
else
val = falseval;
end
|
github
|
lcnhappe/happe-master
|
hlp_matlab_version.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_matlab_version.m
| 642 |
utf_8
|
56356c36dd8e15038caa4dc7b15b62b5
|
function v = hlp_matlab_version()
% Get the MATLAB version in a numeric format that can be compared with <, >, etc.
persistent vers;
try
v = vers(1);
catch
v = strsplit(version,'.'); v = str2num(v{1})*100 + str2num(v{2});
vers = v;
end
% Split a string according to some delimiter(s). Not as fast as hlp_split (and doesn't fuse
% delimiters), but doesn't need bsxfun().
function strings = strsplit(string, splitter)
ix = strfind(string, splitter);
strings = cell(1,numel(ix)+1);
ix = [0 ix numel(string)+1];
for k = 2 : numel(ix)
strings{k-1} = string(ix(k-1)+1:ix(k)-1); end
strings = strings(~cellfun('isempty',strings));
|
github
|
lcnhappe/happe-master
|
hlp_trycompile.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_trycompile.m
| 50,690 |
utf_8
|
cef0c2f78d5b912954b1826f6352d9e1
|
function ok = hlp_trycompile(varargin)
% Try to auto-compile a set of binary files in a folder, and return the status.
% OK = hlp_trycompile(Options...)
%
% This function tries to ensure that a given set of functions or classes (specified by their
% MATLAB identifier), whose source files are assumed to be located in a given directory, are
% properly compiled.
%
% The Style parameter determines how the function proceeds: Either compilation is always done
% ('force'), or only if necessary ('eager', e.g. if invalid file or changed source code). The check
% for re-compilation may be done on every call ('eager'), or once per MATLAB session ('lazy').
%
% The most common use case is specifying a given directory (and omitting the identifiers). In this
% case, all source files that have a mexFunction declaration are compiled, and all other source
% files are also supplied to the compiler as additional files. In case of compilation errors,
% hlp_trycompile also tries to omit all additional files during compilation. Both the list of
% additional files (or their file name patterns) or the considered file types can be specified. The
% list of identifiers to consider can also be specified.
%
% Another possible use case is to omit both the identifiers and the directory. In this case,
% hlp_trycompile assumes that a mex file with the same identifier (and path) as the calling function
% shall be compiled. This is would be used in .m files which directly implement some fallback code
% in case that the compilation fails (or which are just stubs to trigger the on-demand compilation).
%
%
% Since there can be many different versions of a mex binary under Linux (even with the same name),
% .mex files are by default moved into a sub-directory (named according to the hostname) after
% compilation. This does not apply to .class files, which are not platform-specific.
%
% The function supports nearly all features of the underlying MEX compiler, and can thus be used
% to compile a large variety of mex packages found in the wild (in some cases with custom defines,
% libraries, or include directories).
%
% If you are debugging code with it, it is best to set Verbose to true, so that you get compilation
% output.
%
% Additional features of this function include:
% * Figures out whether the -largeArrayDims switch should be used.
% * Repeated calls of this function are very fast if used in 'lazy' mode (so that it can be used in
% an inner loop).
% * Automatically rebuilds if the mex source has changed (does not apply to misc dependency files),
% if used in 'eager' mode.
% * By default uses the Mathworks versions of BLAS and LAPACK (if these libraries are pulled in).
% * Supports both '/' and '\' in directory names.
% * Behaves reasonably in deployed mode (i.e. gives warnings if files are missing).
% * Also compiles .java files where appropriate.
% * Supports test code.
%
% If this function produces errors for some mex package, the most common causes are:
% * If the platform has never been used to compile code, an appropriate compiler may have to be
% selected using "mex -setup". If no supported compiler is installed (e.g. on Win64), it must
% first be doenloaded and installed (there is a free standard compiler for every platform).
% * Some unused source files are in the directory which produce errors when they are automatically
% pulled in.
% --> turn on verbose output and identify & remove these (or check the supplied make file for
% what files are actually needed)
% * The functions require a custom define switch to work.
% --> Check the make file, and add the switch(es) using the 'Defines' parameter.
% * The functions use non-standard C code (e.g. // comments).
% --> Tentatively rename the offending .c files into .cpp.
% * The functions require a specific library to work.
% --> Check the make file, and add the libraries using the 'Libaries' parameter.
% * The functions require specific include directories to work.
% --> Check the make file, and add the directories using the 'IncludeDirectories' parameter.
% * The functions require additional files that are in a different directory.
% --> Check the make file, and add these files using the 'SupportFiles' parameter. Wildcards are
% allowed (in particular the special '*' string, which translates into all source files in
% the Directory).
% * The package assumes that mex is used with the -output option to use a custom identifier name
% --> This type of make acrobatic is not supported by hlp_trycompile; instead, rename the source
% file which has the mexFunction definition such that it matches the target identifier.
% * The functions require specific library directories to work.
% --> Check the make file, and add the directories using the 'LibraryDirectories' parameter.
%
%
% In:
% Style : execution style, can be one of the following (default: 'lazy')
% 'force' : force compilation (regardless of whether the binaries are already there)
% 'eager' : compile only if necessary, check every time that this function is called
% 'lazy' : compile only if necessary, and don't check again during this MATLAB session
%
% --- target files ---
%
% Directory : directory in which the source files are located
% (default: directory of the calling function)
%
% Identifiers : identifier of the target function/class, or cell array of identifiers that should
% be compiled (default: Calling function, if no directory given, or names of all
% compilable source files in the directory, if a directory is given.)
%
% FileTypes : file type patterns to consider as sources files for the Identifiers
% (default: {'*.f','*.c','*.cpp','*.java'})
%
%
% --- testing conditions ---
%
% TestCode : MATLAB code (string) which evaluates to true if the compiled code is behaving
% correctly (and false otherwise), or alternatively a function handle which does the
% same
%
%
% --- additional compiler inputs ---
%
% SupportFiles : cell array of additional / supporting source filenames to include in the compilation of all
% Identifiers (default: '*')
% Note: Any file listed here will not be considered part of the Identifiers, when
% all contents of a directory are to be compiled.
% Note: If there are support source files in sub-directories, include the full path
% to them.
% Note: If this is '*', all source files that are not mex files in the given
% directory are used as support files.
%
% Libraries : names of libraries to include in the compilation
% (default: {})
%
% IncludeDirectories : additional directories in which to search for included source files.
% (default: {})
%
% LibraryDirectories : additional directories in which to search for referenced library files.
% (default: {})
%
% Defines : list of defined symbols (either 'name' or 'name=value' strings)
% (default: {})
%
% Renaming : cell array of {sourcefile,identifier,sourcefile,identifier, ...} indicating that
% the MEX functions generated from the respective source files should be renamed to
% the given identifiers. Corresponds to MEX's -output option; does not apply to Java files.
% (default: {})
%
% Arguments : miscellaneous compiler arguments (default: {})
% For possible arguments, type "help mex" in the command line
%
% DebugBuild : whether to build binaries in debug mode (default: false)
%
%
% --- user messages ---
%
% ErrorMessage : the detail error message to display which describes what type of functionality
% will not be available (if any).
% Note: If you have a MATLAB fallback, mention this in the error message.
%
% PreparationMessage : the message that will be displayed before compilation begins.
% (default: {})
%
% Verbose : whether to display verbose compiler outputs (default: false)
%
%
% --- misc options ---
%
% MathworksLibs : whether to use the Mathworks versions of std. libraries instead of OS-supplied
% ones, if present (applies to blas and lapack) (default: true)
%
% DebugCompile : debug the compilation process; halts in the directory prior to invoking mex
% (default: false)
%
%
% Examples:
% % try to compile all mex / Java files in a given directory:
% hlp_trycompile('Directory','/Extern/MySources');
%
% % as before, but restrict the set of identifiers to compile to a given set
% hlp_trycompile('Directory','/Extern/MySources','Identifiers',{'svmtrain','svmpredict'});
%
% % try to compile mex / Java files in a given directory, and include 2 libraries in the compilation
% hlp_trycompile('Directory','/Extern/MySources','Libraries',{'blas','lapack'});
%
% % like before, but this time include additional source files from two other directories
% % (the single '*' means: include non-mex sources in the specified directory)
% hlp_trycompile('Directory','/Extern/MySources','SupportFiles',{'*','../blas/*.c','../*.cpp'});
%
% % like before, but this time add an include directory, a library directory, and some library
% hlp_trycompile('Directory','/Extern/MySources', 'IncludeDirectories','/boost/include','LibraryDirectories','/boost/lib','Libraries','boost_date_time-1.44');
%
% % like before, this time specifying some custom #define's
% hlp_trycompile('Directory','/Extern/MySources','Defines',{'DEBUG','MAX=((a)>(b)?(a):(b))'});
%
%
% Use cases:
% 1) In addition to a source file mysvd.c (compiling into mysvd.mex*), a stub .m file of the same
% name can be placed in the same directory, which contains code to compile the binary when needed.
%
% function [U,S,V] = mysvd(X)
% if hlp_trycompile
% [U,S,V] = mysvd(X);
% else
% % either display an error message or implement some fallback code.
% end
%
% 2) In a MATLAB function which makes use of a few mex files, ensure compilation of these files.
% function myprocessing(X,y)
% if ~hlp_trycompile('Identifiers',{'svmtrain.c','svmpredict.c'})
% error('Your binary files could not be compiled.');
% else
% m = svmtrain(X,y);
% l = svmpredict(X,m);
% ...
% end
%
% 3) In a startup script.
% hlp_trycompile('Directory','/Extern/MySources');
%
% See also:
% mex
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-03-09
persistent results; % a map of result-tag to OK value
persistent compiler_selected; % whether a compiler has been selected (true/false, or [] if uncertain)
% read options
o = hlp_varargin2struct(varargin, ...
... % overall behavior
{'style','Style'}, 'lazy', ...
... % target files
{'dir','Directory'}, [], ...
{'idents','Identifiers'}, [], ...
{'types','FileTypes'}, {'*.c','*.C','*.cpp','*.CPP','*.f','*.F','*.java','*.Java'}, ...
... % test condition
{'test','TestCode'},'', ...
... % additional compiler inputs
{'support','SupportFiles'}, {'*'}, ...
{'libs','Libraries'}, {}, ...
{'includedirs','IncludeDirectories'}, {}, ...
{'libdirs','LibraryDirectories'}, {}, ...
{'defines','Defines'}, {}, ...
{'args','Arguments'}, '', ...
{'renaming','Renaming'}, {}, ...
{'debug','DebugBuild'}, false, ...
... % messages
{'errmsg','ErrorMessage'}, {'Some BCILAB functionality will likely not be available.'}, ...
{'prepmsg','PreparationMessage'}, {}, ...
{'verbose','Verbose'}, false, ...
... % misc
{'mwlibs','MathworksLibs'}, true, ...
{'debugcompile','DebugCompile'}, false ...
);
% support for parameterless calls
if isempty(o.dir)
% if no dir given, use the calling function's directory
[name,file] = hlp_getcaller();
o.dir = fileparts(file);
if isempty(file)
error('If hlp_trycompile is called without a directory, it must be called from within a file.'); end
% if neither idents nor dir given, use the calling function's identifier
if isempty(o.idents)
o.idents = name; end
end
% uniformize ident format
if isa(o.idents,'function_handle')
o.idents = char(o.idents); end
if ischar(o.idents)
o.idents = {o.idents}; end
if isempty(o.idents)
o.idents = {}; end
% decide whether a re-check can be skipped based on identifiers and directory
if strcmp(o.style,'lazy') || isdeployed
str = java.lang.String(sprintf('%s:',o.dir,o.idents{:}));
tag = sprintf('x%.0f',str.hashCode()+3^31);
if isfield(results,tag)
ok = results.(tag);
return;
end
end
% uniformize directory format
o.dir = path_normalize(o.dir);
% verify style
if ~any(strcmp(o.style,{'force','eager','lazy'}))
error('Unsupported style: %s',o.style); end
% uniformize test condition
if isa(o.test,'function_handle')
o.test = char(o.test); end
% uniformize user messages
if ischar(o.errmsg)
o.errmsg = {o.errmsg}; end
if ischar(o.prepmsg)
o.prepmsg = {o.prepmsg}; end
% uniformize types
if ischar(o.types)
o.types = {o.types}; end
for t=1:length(o.types)
if o.types{t}(1) ~= '*'
o.types{t} = ['*' o.types{t}]; end
end
% uniformize compiler inputs
if ischar(o.support)
o.support = {o.support}; end
if ischar(o.includedirs)
o.includedirs = {o.includedirs}; end
if ischar(o.libdirs)
o.libdirs = {o.libdirs}; end
if ischar(o.libs)
o.libs = {o.libs}; end
if ischar(o.defines)
o.defines = {o.defines}; end
if ischar(o.args)
o.args = {o.args}; end
for i=1:length(o.support)
o.support{i} = path_normalize(o.support{i}); end
for i=1:length(o.includedirs)
o.includedirs{i} = path_normalize(o.includedirs{i}); end
for i=1:length(o.libdirs)
o.libdirs{i} = path_normalize(o.libdirs{i}); end
% if a support is given as '*'
starred = strcmp('*',o.support);
if any(starred)
% list all in the given directory that are not mex files
infos = [];
for t = 1:length(o.types)
if ~isempty(infos)
infos = [infos; dir([o.dir filesep o.types{t}])];
else
infos = dir([o.dir filesep o.types{t}]);
end
end
fnames = {infos.name};
supportfiles = ~cellfun(@(n)is_primary([o.dir filesep n]),fnames);
o.support = [fnames(supportfiles) o.support(~starred)];
end
% infer directory, if not given (take it from the calling function)
if isempty(o.idents) && ~isempty(o.dir)
% get all the source files in the given direcctory
infos = [];
for t = 1:length(o.types)
if ~isempty(infos)
infos = [infos; dir([o.dir filesep o.types{t}])];
else
infos = dir([o.dir filesep o.types{t}]);
end
end
fnames = {infos.name};
% ... but exclude the support files
fnames = setdiff(fnames,o.support);
% and apply any renamings to get the corresponding identifiers
if ~isempty(o.renaming)
for n=1:length(fnames)
fnames{n} = hlp_rewrite(fnames{n},o.renaming{:}); end
end
% ... and strip off the extensions
for n=1:length(fnames)
fnames{n} = hlp_getresult(2,@fileparts,fnames{n}); end
o.idents = fnames;
end
ok = false;
missingid = []; % indices of missing identifiers (for dont-retry-next-time beacon files)
if isdeployed
% --- deployed mode ---
% Can not compile, but figure out whether everything needed is present. A special consideration
% is that both the mex files calling functions are in a mounted .ctf archive.
% check if all identifiers are present (either as mex or class)
for i=1:length(o.idents)
if ~any(exist(o.idents{i}) == [2 3 8])
missingid(end+1) = i; end
end
ok = isempty(missingid);
if ~isempty(missingid)
% not all identifiers are compiled for this platform
disp(['Note: The MEX functions/identifiers ' format_cellstr(o.idents(missingid)) ' are not included for your platform.']);
elseif strcmp(o.style,'force')
% in force mode, we remark that everything is already compiled
disp_once(['The functions ' format_cellstr(o.idents) ' are properly compiled.']);
end
else
% --- regular mode ---
% here, we *do* compile what needs to be compiled
% find out a key configuration settings
is64bit = ~isempty(strfind(computer,'64'));
has_largearrays = is64bit && hlp_matlab_version >= 703;
if ispc
warning off MATLAB:FILEATTRIB:SyntaxWarning; end
% add a few missing defines
if hlp_matlab_version < 703
o.defines = [o.defines {'mwIndex=int','mwSize=int','mwSignedIndex=int'}]; end
% rewrite blas & lapack libs....
if o.mwlibs
% for each type of library
for l={'blas','lapack'}
lib = l{1};
% note: this code is based on SeDuMi's compile script (by Michael C. Grant)
in_use = strcmp(o.libs,lib);
if any(in_use)
if ispc
if is64bit
osdir = 'win64';
else
osdir = 'win32';
end
libpath = [matlabroot '\extern\lib\' osdir '\microsoft\libmw' lib '.lib'];
if ~exist(libpath,'file')
libpath = [matlabroot '\extern\lib\' osdir '\microsoft\msvc60\libmw' lib '.lib']; end
if exist(libpath,'file')
o.libs{in_use} = libpath;
else
disp_once('Note: The Mathworks library %s was assumed to be in %s, but not found.',lib,libpath);
end
else
o.libs{in_use} = ['mw' lib];
end
end
end
end
try
% remember the current directory & enter the target directory
olddir = pwd;
if hlp_matlab_version >= 706
go_back = onCleanup(@()cd(olddir)); end
if ~exist(o.dir,'dir')
error(['The target directory ' o.dir ' does not exist.']); end
cd(o.dir);
% expand regex patterns in o.support
for i=length(o.support):-1:1
if any(o.support{i} == '*')
found = dir(o.support{i});
if ~isempty(found)
% ... and splice the results in
basepath = fileparts(o.support{i});
items = cellfun(@(x)[basepath filesep x],{found.name},'UniformOutput',false);
o.support = [o.support(1:i-1) items o.support(i+1:end)];
end
end
end
% find all source & target files for the respective identifiers...
% (note that there might be multiple source files for each one)
sources = cell(1,length(o.idents)); % list of all source file names for the corresponding identifiers (indexed like idents)
targets = cell(1,length(o.idents)); % list of all target file names for the corresponding identifiers (indexed like idents)
for i=1:length(o.idents)
if ~isempty(o.renaming)
% the renaming may yield additional source file names for the given identifiers
idx = strcmp(o.idents{i},o.renaming(2:2:end));
if any(idx)
% the identifier is a renaming target: add the corresponding source file name
filename = o.renaming{find(idx)*2-1};
% if a source file with this ident & type is present
if exist([o.dir filesep filename],'file')
% remember it & derive its respective target file name
sources{i}{end+1} = filename;
targets{i}{end+1} = [o.idents{i} '.' mexext];
end
end
end
for t=1:length(o.types)
filename = [o.idents{i} o.types{t}(2:end)];
% if a source file with this ident & type is present
if exist([o.dir filesep filename],'file')
% remember it
sources{i}{end+1} = filename;
% and also derive its respective target file name
if strcmp(o.types{t},'*.java')
targets{i}{end+1} = [o.idents{i} '.class'];
else
targets{i}{end+1} = [o.idents{i} '.' mexext];
end
end
end
% check whether we have all necessary source files
if isempty(sources{i})
error('Did not find source file for %s',o.idents{i}); end
if isempty(targets{i})
error('Could not determine target file for %s',o.idents{i}); end
end
% check for existence (either .mex* or class) of all identifiers
% and make a list of missing & present binary files; do this in a different directory,
% to not shadow the mex files of interest with whatever .m files live in this directory
cd ..
binaries = {}; % table of existing binary file paths (indexed like idents)
for i=1:length(o.idents)
% get current file reference to this identifier
binaries{i} = which(o.idents{i});
% if it doesn't point to a .mex or .class file, ignore it
if ~any(exist(o.idents{i}) == [3 8])
binaries{i} = []; end
if ~isempty(binaries{i})
% check whether it is correct file path
if ~any(binaries{i} == filesep)
error(['Could not determine the location of the mex file for: ' o.idents{i}]); end
% check whether the referenced file actually exists in the file system
if isempty(dir(binaries{i}))
binaries{i} = []; end
end
% if no binary found, record it as missing
if isempty(binaries{i})
missingid(end+1) = i; end
end
cd(o.dir);
% check which of the existing binaries need to be re-compiled (if out of date)
outdatedid = []; % indices of identifiers (in o.idents) that need to be recompiled
for i=1:length(binaries)
if ~isempty(binaries{i})
% get the date of the binary file
bininfo = dir(binaries{i});
% find all corresponding source files
srcinfo = [];
for s=1:length(sources{i})
srcinfo = [srcinfo; dir([o.dir filesep sources{i}{s}])]; end
if ~isfield(bininfo,'datenum')
[bininfo.datenum] = celldeal(cellfun(@datenum,{bininfo.date},'UniformOutput',false)); end
if ~isfield(srcinfo,'datenum')
[srcinfo.datenum] = celldeal(cellfun(@datenum,{srcinfo.date},'UniformOutput',false)); end
% if any of the source files has been changed
if bininfo.datenum < max([srcinfo.datenum])
% check if their md5 hash is still the same...
if exist([binaries{i} '.md5'],'file')
try
contents = load([binaries{i} '.md5'],'-mat','srchash');
% need to do that over all source files...
srchash = [];
sorted_sources = sort(sources{i});
for s=1:length(sorted_sources)
srchash = [srchash hlp_cryptohash([o.dir filesep sorted_sources{s}],true)]; end
if ~isequal(srchash,contents.srchash)
% hash is different: mark binary as outdated
outdatedid(end+1) = i;
end
catch
% there was a probblem: mark as outdated
outdatedid(end+1) = i;
end
else
% no md5 present: mark as outdated
outdatedid(end+1) = i;
end
end
end
end
% we try to recompile both what's missing and what's outdated
recompileid = [missingid outdatedid];
javainvolved = false; % for final error/help message generation
mexinvolved = false; % same
if ~isempty(recompileid)
% need to recompile something -- display a few preparatory messages...
for l=1:length(o.prepmsg)
disp(o.prepmsg{l}); end
failedid = []; % list of indices of identifier that failed the build
% for each identifier, try to compile it
% and record whether it failed
for i=recompileid
success = false;
fprintf(['Compiling the function/class ' o.idents{i} '...']);
% for each source file mapping to that identifier
for s=1:length(sources{i})
% check type of source
if ~isempty(strfind(sources{i}{s},'.java'))
% we have a Java source file: compile
[errcode,result] = system(['javac ' javac_options(o) sources{i}{s}]);
if errcode
javainvolved = true;
% problem: show display output
fprintf('\n');
disp(result);
else
success = true;
break;
end
else
% generate MEX options
opts = mex_options(o);
supp = sprintf(' %s',o.support{:});
if isempty(compiler_selected)
% not clear whether a compiler has been selected yet
if hlp_matlab_version >= 708
% we can find it out programmatically
try
cconf = mex.getCompilerConfigurations; %#ok<NASGU>
compiler_selected = true;
catch
% no compiler has been selected yet...
try
% display a few useful hints to the user
disp(' to compile this feature, you first need to select');
disp('which compiler should be used on your platform.');
if ispc
if is64bit
disp_once('As you are on 64-bit windows, you may find that no compiler is installed.');
else
disp_once('On 32-bit Windows, MATLAB supplies a built-in compiler (LLC), which should');
disp_once('faithfully compile most C code. For broader support across C dialects (as well as C++), ');
disp_once('you should make sure that a better compiler is installed on your system and selected in the following.');
end
disp_once('A good choice is the free Microsoft Visual Studio 2005/2008/2010 Express compiler suite');
disp_once('together with the Microsoft Platform SDK (6.1 for 2008, 7.1 for 2010) for your Windows Version.');
disp_once('See also: http://argus-home.coas.oregonstate.edu/forums/development/core-software-development/compiling-64-bit-mex-files');
disp_once(' http://www.mathworks.com/support/compilers/R2010b/win64.html');
disp_once('The installation is easier if a professional Intel or Microsoft compiler is used.');
elseif isunix
disp_once('On Linux/UNIX, the best choice is usually a supported version of the GCC compiler suite.');
else
disp_once('On Mac OS, you need to have a supported version of Xcode/GCC installed.');
end
% start the compiler selection tool
mex -setup
% verify that a compiler has been selected
cconf = mex.getCompilerConfigurations; %#ok<NASGU>
compiler_selected = true;
catch
compiler_selected = false;
end
end
else
disp(' you may be prompted to select a compiler in the following');
disp('(as BCILAB cannot auto-determine whether one is selected on your platform).');
end
end
if ~compiler_selected
fprintf('skipped (no compiler selected).\n');
else
if o.verbose || isempty(compiler_selected)
% this variant will also be brought up if not sure whether a compiler
% has already been selected...
doeval = @eval;
else
doeval = @evalc;
end
% try to build the file
try
mexinvolved = true;
% check if a renaming applies...
idx = strcmp(sources{i}{s},o.renaming);
if any(idx)
rename = [' -output ' o.renaming{find(idx,1)+1} ' '];
else
rename = '';
end
if o.debugcompile
% display a debug console to allow the user to debug how their file compiles
fprintf('\nExecution has been paused immediately before running mex.\n');
disp(['You are in the directory "' pwd '".']);
disp('The mex command that will be invoked in the following is:');
if has_largearrays
disp([' mex ' opts ' -largeArrayDims ' rename sources{i}{s} supp]);
else
disp([' mex ' opts rename sources{i}{s} supp]);
end
fprintf('\n\nTo proceed normally, type "dbcont".\n');
keyboard;
end
if has_largearrays
try
% -largeArrayDims enabled
try
doeval(['mex ' opts ' -largeArrayDims ' rename sources{i}{s} supp]); % with supporting libaries
catch
doeval(['mex ' opts ' -largeArrayDims ' rename sources{i}{s}]); % without supporting libraries
end
catch
% -largeArrayDims disabled
try
doeval(['mex ' opts rename sources{i}{s} supp]); % with supporting libaries
catch
doeval(['mex ' opts rename sources{i}{s}]); % without supporting libraries
end
end
else
% -largeArrayDims disabled
try
doeval(['mex ' opts rename sources{i}{s} supp]); % with supporting libaries
catch
doeval(['mex ' opts rename sources{i}{s}]); % without supporting libraries
end
end
% compilation succeeded...
if any(i==outdatedid)
% there is an outdated binary, which needs to be deleted
try
delete(binaries{i});
catch
disp(['Could not delete outdated binary ' binaries{i}]);
end
end
% check whether the file is being found now
if exist(o.idents{i}) == 3
success = true;
compiler_selected = true;
break;
end
catch
% build failed
end
end
end
end
% check if compilation of this identifier was successful
if success
% if so, we sign off the binary with an md5 hash of the sources...
newbinary = which(o.idents{i});
try
srchash = [];
sorted_sources = sort(sources{i});
for s=1:length(sorted_sources)
srchash = [srchash hlp_cryptohash([o.dir filesep sorted_sources{s}],true)]; end
save([newbinary '.md5'],'srchash','-mat');
fprintf('success.\n');
catch
disp('could not create md5 hash for the source files; other than that, successful.');
end
else
fprintf('failed.\n');
failedid(end+1) = i;
end
end
embed_test = false;
if isempty(failedid)
% all worked: now run the test code - if any - to verify the correctness of the build
if length(recompileid) > 1
if ~isempty(o.test)
fprintf('All files in %s compiled successfully; now testing the build outputs...',o.dir);
else
fprintf('All files in %s compiled successfully.\n',o.dir);
end
elseif ~isempty(o.test)
fprintf('Now testing the build outputs...');
end
% test the output
try
ans = true; %#ok<NOANS>
eval(o.test);
catch
ans = false; %#ok<NOANS>
end
if ans %#ok<NOANS>
% the test was successful; now copy the files into a platform-specific directory
if ~isempty(o.test)
% only if we have a succeeding non-empty test
embed_test = true;
fprintf('success.\n');
end
retainid = recompileid;
eraseid = [];
ok = true;
else
% the test was unsuccessful: remove all newly-compiled files...
if ~isempty(o.test)
fprintf('failed.\n'); end
disp('The code compiled correctly but failed the build tests. Reverting the build...');
disp('If this is unmodified BCILAB code, please consider reporting this issue.');
retainid = [];
eraseid = recompileid;
end
else
if length(recompileid) > 1
if isempty(setdiff(recompileid,failedid))
fprintf('All files in %s failed to build; this indicates a problem in your build environment/settings.\n',o.dir);
else
fprintf('Some files in %s failed to build. Please make sure that you have a supported compiler; otherwise, please report this issue.\n',o.dir);
end
else
disp('Please make sure that you have a supported compiler and that your build environment is set up correctly.');
disp('Also, please consider reporting this issue.');
end
% compilation failed; only a part of the binaries may be available...
retainid = setdiff(recompileid,failedid);
eraseid = [];
end
% move the mex files into their own directory
moveid = retainid(cellfun(@exist,o.idents(retainid)) == 3);
if ~isempty(moveid)
% some files to be moved
dest_path = [o.dir filesep 'build-' hlp_hostname filesep];
% create a new directory
if ~exist(dest_path,'dir')
if ~mkdir(o.dir,['build-' hlp_hostname])
error(['unable to create directory ' dest_path]); end
% set permissions
try
fileattrib(dest_path,'+w','a');
catch
disp(['Note: There are permission problems for the directory ' dest_path]);
end
end
% create a new env_add.m there
try
filename = [dest_path 'env_add.m'];
fid = fopen(filename,'w+');
if embed_test
% if we had a successful test, we use this to control inclusion of the mex files
fprintf(fid,o.test);
else
% otherwise we check whether any one of the identifiers is recognized by
% MATLAB as a mex function
fprintf(fid,'any(cellfun(@exist,%s)==3)',hlp_tostring(o.idents(moveid)));
end
fclose(fid);
fileattrib(filename,'+w','a');
catch
disp(['Note: There were write permission problems for the file ' filename]);
end
% move the targets over there...
movefiles = unique(o.idents(moveid));
for t = 1:length(movefiles)
[d,n,x] = fileparts(which(movefiles{t}));
movefile([d filesep n x],[dest_path n x]);
try
movefile([d filesep n x '.md5'],[dest_path n x '.md5']);
catch
end
end
% add the destination path
addpath(dest_path);
% and to be entirely sure, CD into that directory to verify that the files are being recognized...
% (and don't get shadowed by whatever is in the directory below)
cd(dest_path);
all_ok = all(strncmp(dest_path,cellfun(@which,o.idents(moveid),'UniformOutput',false),length(dest_path)));
cd(o.dir);
% make sure that they are still being found...
if ~all_ok
error('It could not be verified that the MEX file records in %s were successfully updated to their new sub-directories.',o.dir); end
end
% move the java class files into their own directory
infos = dir([o.dir filesep '*.class']);
movefiles = {infos.name};
moveid = retainid(cellfun(@exist,o.idents(retainid)) ~= 3);
if ~isempty(movefiles)
% some files to be moved
dest_path = [o.dir filesep 'build-javaclasses' filesep];
% create a new directory
if ~exist(dest_path,'dir')
if ~mkdir(o.dir,'build-javaclasses')
error(['unable to create directory ' dest_path]); end
% set permissions
try
fileattrib(dest_path,'+w','a');
catch
disp(['Note: There are permission problems for the directory ' dest_path]);
end
end
% create a new env_add.m there
try
filename = [dest_path 'env_add.m'];
fid = fopen(filename,'w+'); fclose(fid);
fileattrib(filename,'+w','a');
catch
disp(['Note: There were write permission problems for the file ' filename]);
end
% move the targets over there...
for t = 1:length(movefiles)
movefile([o.dir filesep movefiles{t}],[dest_path movefiles{t}]);
try
movefile([o.dir filesep movefiles{t} '.md5'],[dest_path movefiles{t} '.md5']);
catch
end
end
% add the destination path
if isdeployed
warning off MATLAB:javaclasspath:jarAlreadySpecified; end
javaaddpath(dest_path);
% check whether the class is found
if ~all(cellfun(@exist,o.idents(moveid)) == 8)
disp_once('Not all Java binaries in %s could be recognized by MATLAB.',dest_path); end
end
if ~isempty(eraseid)
% some files need to be erased...
for k=eraseid
for t=1:length(targets{k})
if exist([o.dir filesep targets{k}{t}])
try
delete(targets{k}{t});
catch
disp(['Could not delete broken binary ' binaries{i}{s}]);
end
end
end
end
end
else
% nothing to recompile
ok = true;
if strcmp(o.style,'eager') && ~isempty(o.idents) && o.verbose
disp_once(['The functions ' format_cellstr(o.idents) ' are already compiled.']); end
end
% go back to the old directory
if hlp_matlab_version < 706
cd(olddir); end
catch e
ok = false; %#ok<NASGU>
% go back to the old path in case of an error
if hlp_matlab_version < 706
cd(olddir); end
rethrow(e);
end
end
% store the OK flag in the results
if strcmp(o.style,'lazy') || isdeployed
results.(tag) = ok; end
if ~ok
if ~isdeployed
% regular error summary
if mexinvolved
disp_once('\nIn case you need to use a better / fully supported compiler, please have a look at:');
try
v=version;
releasename = v(find(v=='(')+1 : find(v==')')-1);
if length(releasename) > 3 && releasename(1) == 'R'
releasename = releasename(2:end); end
site = ['http://www.google.com/search?q=matlab+supported+compilers+' releasename];
catch
site = 'http://www.google.com/search?q=matlab+supported+compilers';
end
disp_once(' <a href="%s">%s</a>\n',site,site);
if ispc
if is64bit
disp_once('On 64-bit Windows, MATLAB comes with no built-in compiler, so you need to have one installed.');
else
disp_once('On 32-bit Windows, MATLAB supplies a built-in compiler (LLC), which is, however, not very good.');
end
disp_once('A good choice is the free Microsoft Visual Studio 2005/2008/2010 Express compiler suite');
disp_once('together with the Microsoft Platform SDK (6.1 for 2008, 7.1 for 2010) for your Windows Version.');
disp_once('See also: http://argus-home.coas.oregonstate.edu/forums/development/core-software-development/compiling-64-bit-mex-files');
disp_once(' http://www.mathworks.com/support/compilers/R2010b/win64.html');
disp_once('The installation is easier if a professional Intel or Microsoft compiler is used.');
elseif isunix
disp_once('On Linux/UNIX, the best choice is usually a supported version of the GCC compiler suite.');
else
disp_once('On Mac OS, you need to have a supported version of Xcode/GCC installed.');
end
end
if javainvolved
disp_once('Please make sure that your system''s java configuration matches the one used by MATLAB (see "ver" command).');
end
end
end
% create javac options string from options struct
function opts = javac_options(o)
verbosity = hlp_rewrite(o.verbose,true,'-verbose',false,'');
if ~isempty(o.libdirs)
cpath = ['-classpath ' sprintf('%s;',o.libdirs{:})];
cpath(end) = [];
else
cpath = '';
end
if ~isempty(o.includedirs)
ipath = ['-sourcepath ' sprintf('%s;',o.includedirs{:})];
ipath(end) = [];
else
ipath = '';
end
debugness = hlp_rewrite(o.debug,true,'-g',false,'-g:none');
targetsource = '-target 1.6 -source 1.6';
opts = [sprintf(' %s',verbosity,cpath,ipath,debugness,targetsource) ' '];
% create mex options string from options struct
function opts = mex_options(o)
if ~isempty(o.defines)
defs = sprintf(' -D%s',o.defines{:});
else
defs = '';
end
debugness = hlp_rewrite(o.debug,true,'-g',false,'');
if ~isempty(o.includedirs)
incdirs = sprintf(' -I"%s"',o.includedirs{:});
else
incdirs = '';
end
if ~isempty(o.libs)
if ispc
libs = sprintf(' -l"%s"',o.libs{:});
else
libs = sprintf(' -l%s',o.libs{:});
end
else
libs = '';
end
if ~isempty(o.libdirs)
libdirs = sprintf(' -L"%s"',o.libdirs{:});
else
libdirs = '';
end
verbosity = hlp_rewrite(o.verbose,true,'-v',false,'');
opts = [sprintf(' %s',defs,debugness,incdirs,libs,libdirs,verbosity) ' '];
% format a non-empty cell-string array into a string
function x = format_cellstr(x)
if isempty(x)
x = '';
else
x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}'];
end
% check whether a given identifier is frozen in a ctf archive
function tf = in_ctf(ident) %#ok<DEFNU>
tf = isdeployed && strncmp(ctfroot,which(ident),length(ctfroot));
% normalize a directory path
function dir = path_normalize(dir)
if filesep == '\';
dir(dir == '/') = filesep;
else
dir(dir == '\') = filesep;
end
if dir(end) == filesep
dir = dir(1:end-1); end
% determine if a given file is a mex source file or a java source file
% (and compiles into an identifier that is seen by MATLAB)
function tf = is_primary(filename)
if length(filename)>5 && strcmp(filename(end-4:end),'.java')
tf = true;
return;
else
tf = false;
end
fid = fopen(filename);
if fid ~= -1
try
contents = fread(fid);
tf = ~isempty(strfind(char(contents)','mexFunction')); %#ok<FREAD>
fclose(fid);
catch
fclose(fid);
end
end
% act like deal, but with a single cell array as input
function varargout = celldeal(argin)
varargout = argin;
% for old MATLABs that can't properly move files...
function movefile(src,dst)
try
builtin('movefile',src,dst);
catch e
if any([src dst]=='$') && hlp_matlab_version <= 705
if ispc
[errcode,text] = system(sprintf('move ''%s'' ''%s''',src,dst)); %#ok<NASGU>
else
[errcode,text] = system(sprintf('mv ''%s'' ''%s''',src,dst)); %#ok<NASGU>
end
if errcode
error('Failed to move %s to %s.',src,dst); end
else
rethrow(e);
end
end
% for old MATLABs that don't handle Java classes on the dynamic path...
function res = exist(obj,type)
if nargin > 1
res = builtin('exist',obj,type);
if ~res && (hlp_matlab_version <= 704) && strcmp(type,'class') && builtin('exist',[obj '.class'],'file')
res = 8; end
else
res = builtin('exist',obj);
if ~res && (hlp_matlab_version <= 704) && builtin('exist',[obj '.class'])
res = 8; end
end
% for old MATLABs that don't handle Java classes on the dynamic path...
function res = which(ident)
res = builtin('which',ident);
if ~any(res == filesep)
if hlp_matlab_version <= 704
if isempty(res) || ~isempty(strfind(res,'not found'))
res = builtin('which',[ident '.class']); end
else
if ~isempty(strfind(res,'Java'))
res = builtin('which',[ident '.class']); end
end
end
|
github
|
lcnhappe/happe-master
|
hlp_serialize.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_serialize.m
| 15,821 |
utf_8
|
90ee89875e34a4a84c3e58d9657c04f1
|
function m = hlp_serialize(v)
% Convert a MATLAB data structure into a compact byte vector.
% Bytes = hlp_serialize(Data)
%
% The original data structure can be recovered from the byte vector via hlp_deserialize.
%
% In:
% Data : some MATLAB data structure
%
% Out:
% Bytes : a representation of the original data as a byte stream
%
% Notes:
% The code is a rewrite of Tim Hutt's serialization code. Support has been added for correct
% recovery of sparse, complex, single, (u)intX, function handles, anonymous functions, objects,
% and structures with unlimited field count. Serialize/deserialize performance is ~10x higher.
%
% Limitations:
% * Java objects cannot be serialized
% * Arrays with more than 255 dimensions have their last dimensions clamped
% * Handles to nested/scoped functions can only be deserialized when their parent functions
% support the BCILAB argument reporting protocol (e.g., by using arg_define).
% * New MATLAB objects need to be reasonably friendly to serialization; either they support
% construction from a struct, or they support saveobj/loadobj(struct), or all their important
% properties can be set via set(obj,'name',value)
% * In anonymous functions, accessing unreferenced variables in the workspace of the original
% declaration via eval(in) works only if manually enabled via the global variable
% tracking.serialize_anonymous_fully (possibly at a significant performance hit).
% note: this feature is currently not rock solid and can be broken either by Ctrl+C'ing
% in the wrong moment or by concurrently serializing from MATLAB timers.
%
% See also:
% hlp_deserialize
%
% Examples:
% bytes = hlp_serialize(mydata);
% ... e.g. transfer the 'bytes' array over the network ...
% mydata = hlp_deserialize(bytes);
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-02
%
% adapted from serialize.m
% (C) 2010 Tim Hutt
% dispatch according to type
if isnumeric(v)
m = serialize_numeric(v);
elseif ischar(v)
m = serialize_string(v);
elseif iscell(v)
m = serialize_cell(v);
elseif isstruct(v)
m = serialize_struct(v);
elseif isa(v,'function_handle')
m = serialize_handle(v);
elseif islogical(v)
m = serialize_logical(v);
elseif isobject(v)
m = serialize_object(v);
elseif isjava(v)
warn_once('hlp_serialize:cannot_serialize_java','Cannot properly serialize Java class %s; using a placeholder instead.',class(v));
m = serialize_string(['<<hlp_serialize: ' class(v) ' unsupported>>']);
else
try
m = serialize_object(v);
catch
warn_once('hlp_serialize:unknown_type','Cannot properly serialize object of unknown type "%s"; using a placeholder instead.',class(v));
m = serialize_string(['<<hlp_serialize: ' class(v) ' unsupported>>']);
end
end
end
% single scalar
function m = serialize_scalar(v)
% Data type & data
m = [class2tag(class(v)); typecast(v,'uint8').'];
end
% char arrays
function m = serialize_string(v)
if size(v,1) == 1
% horizontal string: Type, Length, and Data
m = [uint8(0); typecast(uint32(length(v)),'uint8').'; uint8(v(:))];
elseif sum(size(v)) == 0
% '': special encoding
m = uint8(200);
else
% general char array: Tag & Number of dimensions, Dimensions, Data
m = [uint8(132); ndims(v); typecast(uint32(size(v)),'uint8').'; uint8(v(:))];
end
end
% logical arrays
function m = serialize_logical(v)
% Tag & Number of dimensions, Dimensions, Data
m = [uint8(133); ndims(v); typecast(uint32(size(v)),'uint8').'; uint8(v(:))];
end
% non-complex and non-sparse numerical matrix
function m = serialize_numeric_simple(v)
% Tag & Number of dimensions, Dimensions, Data
m = [16+class2tag(class(v)); ndims(v); typecast(uint32(size(v)),'uint8').'; typecast(v(:).','uint8').'];
end
% Numeric Matrix: can be real/complex, sparse/full, scalar
function m = serialize_numeric(v)
if issparse(v)
% Data Type & Dimensions
m = [uint8(130); typecast(uint64(size(v,1)), 'uint8').'; typecast(uint64(size(v,2)), 'uint8').']; % vectorize
% Index vectors
[i,j,s] = find(v);
% Real/Complex
if isreal(v)
m = [m; serialize_numeric_simple(i); serialize_numeric_simple(j); 1; serialize_numeric_simple(s)];
else
m = [m; serialize_numeric_simple(i); serialize_numeric_simple(j); 0; serialize_numeric_simple(real(s)); serialize_numeric_simple(imag(s))];
end
elseif ~isreal(v)
% Data type & contents
m = [uint8(131); serialize_numeric_simple(real(v)); serialize_numeric_simple(imag(v))];
elseif isscalar(v)
% Scalar
m = serialize_scalar(v);
else
% Simple matrix
m = serialize_numeric_simple(v);
end
end
% Struct array.
function m = serialize_struct(v)
% Tag, Field Count, Field name lengths, Field name char data, #dimensions, dimensions
fieldNames = fieldnames(v);
fnLengths = [length(fieldNames); cellfun('length',fieldNames)];
fnChars = [fieldNames{:}];
dims = [ndims(v) size(v)];
m = [uint8(128); typecast(uint32(fnLengths(:)).','uint8').'; uint8(fnChars(:)); typecast(uint32(dims), 'uint8').'];
% Content.
if numel(v) > length(fieldNames)
% more records than field names; serialize each field as a cell array to expose homogenous content
tmp = cellfun(@(f)serialize_cell({v.(f)}),fieldNames,'UniformOutput',false);
m = [m; 0; vertcat(tmp{:})];
else
% more field names than records; use struct2cell
m = [m; 1; serialize_cell(struct2cell(v))];
end
end
% Cell array of heterogenous contents
function m = serialize_cell_heterogenous(v)
contents = cellfun(@hlp_serialize,v,'UniformOutput',false);
m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').'; vertcat(contents{:})];
end
% Cell array of homogenously-typed contents
function m = serialize_cell_typed(v,serializer)
contents = cellfun(serializer,v,'UniformOutput',false);
m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').'; vertcat(contents{:})];
end
% Cell array
function m = serialize_cell(v)
sizeprod = cellfun('prodofsize',v);
if sizeprod == 1
% all scalar elements
if (all(cellfun('isclass',v(:),'double')) || all(cellfun('isclass',v(:),'single'))) && all(~cellfun(@issparse,v(:)))
% uniformly typed floating-point scalars (and non-sparse)
reality = cellfun('isreal',v);
if reality
% all real
m = [uint8(34); serialize_numeric_simple(reshape([v{:}],size(v)))];
elseif ~reality
% all complex
m = [uint8(34); serialize_numeric(reshape([v{:}],size(v)))];
else
% mixed reality
m = [uint8(35); serialize_numeric(reshape([v{:}],size(v))); serialize_logical(reality(:))];
end
else
% non-float types
if cellfun('isclass',v,'struct')
% structs
m = serialize_cell_typed(v,@serialize_struct);
elseif cellfun('isclass',v,'cell')
% cells
m = serialize_cell_typed(v,@serialize_cell);
elseif cellfun('isclass',v,'logical')
% bool flags
m = [uint8(39); serialize_logical(reshape([v{:}],size(v)))];
elseif cellfun('isclass',v,'function_handle')
% function handles
m = serialize_cell_typed(v,@serialize_handle);
else
% arbitrary / mixed types
m = serialize_cell_heterogenous(v);
end
end
elseif isempty(v)
% empty cell array
m = [uint8(33); ndims(v); typecast(uint32(size(v)),'uint8').'];
else
% some non-scalar elements
dims = cellfun('ndims',v);
size1 = cellfun('size',v,1);
size2 = cellfun('size',v,2);
if cellfun('isclass',v,'char') & size1 <= 1 %#ok<AND2>
% all horizontal strings or proper empty strings
m = [uint8(36); serialize_string([v{:}]); serialize_numeric_simple(uint32(size2)); serialize_logical(size1(:)==0)];
elseif (size1+size2 == 0) & (dims == 2) %#ok<AND2>
% all empty and non-degenerate elements
if all(cellfun('isclass',v(:),'double')) || all(cellfun('isclass',v(:),'cell')) || all(cellfun('isclass',v(:),'struct'))
% of standard data types: Tag, Type Tag, #Dims, Dims
m = [uint8(37); class2tag(class(v{1})); ndims(v); typecast(uint32(size(v)),'uint8').'];
elseif length(unique(cellfun(@class,v(:),'UniformOutput',false))) == 1
% of uniform class with prototype
m = [uint8(38); hlp_serialize(class(v{1})); ndims(v); typecast(uint32(size(v)),'uint8').'];
else
% of arbitrary classes
m = serialize_cell_heterogenous(v);
end
else
% arbitrary sizes (and types, etc.)
m = serialize_cell_heterogenous(v);
end
end
end
% Object / class
function m = serialize_object(v)
try
% try to use the saveobj method first to get the contents
conts = saveobj(v);
if isstruct(conts) || iscell(conts) || isnumeric(conts) || ischar(conts) || islogical(conts) || isa(conts,'function_handle')
% contents is something that we can readily serialize
conts = hlp_serialize(conts);
else
% contents is still an object: turn into a struct now
conts = serialize_struct(struct(conts));
end
catch
% saveobj failed for this object: turn into a struct
conts = serialize_struct(struct(v));
end
% Tag, Class name and Contents
m = [uint8(134); serialize_string(class(v)); conts];
end
% Function handle
function m = serialize_handle(v)
% get the representation
rep = functions(v);
switch rep.type
case 'simple'
% simple function: Tag & name
m = [uint8(151); serialize_string(rep.function)];
case 'anonymous'
global tracking; %#ok<TLEV>
if isfield(tracking,'serialize_anonymous_fully') && tracking.serialize_anonymous_fully
% serialize anonymous function with their entire variable environment (for complete
% eval and evalin support). Requires a stack of function id's, as function handles
% can reference themselves in their full workspace.
persistent handle_stack; %#ok<TLEV>
% Tag and Code
m = [uint8(152); serialize_string(char(v))];
% take care of self-references
str = java.lang.String(rep.function);
func_id = str.hashCode();
if ~any(handle_stack == func_id)
try
% push the function id
handle_stack(end+1) = func_id;
% now serialize workspace
m = [m; serialize_struct(rep.workspace{end})];
% pop the ID again
handle_stack(end) = [];
catch e
% note: Ctrl-C can mess up the handle stack
handle_stack(end) = []; %#ok<NASGU>
rethrow(e);
end
else
% serialize the empty workspace
m = [m; serialize_struct(struct())];
end
if length(m) > 2^18
% If you are getting this warning, it is likely that one of your anonymous functions
% was created in a scope that contained large variables; MATLAB will implicitly keep
% these variables around (referenced by the function) just in case you refer to them.
% To avoid this, you can create the anonymous function instead in a sub-function
% to which you only pass the variables that you actually need.
warn_once('hlp_serialize:large_handle','The function handle with code %s references variables of more than 256k bytes; this is likely very slow.',rep.function);
end
else
% anonymous function: Tag, Code, and reduced workspace
if ~isempty(rep.workspace)
m = [uint8(152); serialize_string(char(v)); serialize_struct(rep.workspace{1})];
else
m = [uint8(152); serialize_string(char(v)); serialize_struct(struct())];
end
end
case {'scopedfunction','nested'}
% scoped function: Tag and Parentage
m = [uint8(153); serialize_cell(rep.parentage)];
otherwise
warn_once('hlp_serialize:unknown_handle_type','A function handle with unsupported type "%s" was encountered; using a placeholder instead.',rep.type);
m = serialize_string(['<<hlp_serialize: function handle of type ' rep.type ' unsupported>>']);
end
end
% *container* class to byte
function b = class2tag(cls)
switch cls
case 'string'
b = uint8(0);
case 'double'
b = uint8(1);
case 'single'
b = uint8(2);
case 'int8'
b = uint8(3);
case 'uint8'
b = uint8(4);
case 'int16'
b = uint8(5);
case 'uint16'
b = uint8(6);
case 'int32'
b = uint8(7);
case 'uint32'
b = uint8(8);
case 'int64'
b = uint8(9);
case 'uint64'
b = uint8(10);
% other tags are as follows:
% % offset by +16: scalar variants of these...
% case 'cell'
% b = uint8(33);
% case 'cellscalars'
% b = uint8(34);
% case 'cellscalarsmixed'
% b = uint8(35);
% case 'cellstrings'
% b = uint8(36);
% case 'cellempty'
% b = uint8(37);
% case 'cellemptyprot'
% b = uint8(38);
% case 'cellbools'
% b = uint8(39);
% case 'struct'
% b = uint8(128);
% case 'sparse'
% b = uint8(130);
% case 'complex'
% b = uint8(131);
% case 'char'
% b = uint8(132);
% case 'logical'
% b = uint8(133);
% case 'object'
% b = uint8(134);
% case 'function_handle'
% b = uint8(150);
% case 'function_simple'
% b = uint8(151);
% case 'function_anon'
% b = uint8(152);
% case 'function_scoped'
% b = uint8(153);
% case 'emptystring'
% b = uint8(200);
otherwise
error('Unknown class');
end
end
% emit a specific warning only once (per MATLAB session)
function warn_once(varargin)
persistent displayed_warnings;
% determine the message content
if length(varargin) > 1 && any(varargin{1}==':') && ~any(varargin{1}==' ') && ischar(varargin{2})
message_content = [varargin{1} sprintf(varargin{2:end})];
else
message_content = sprintf(varargin{1:end});
end
% generate a hash of of the message content
str = java.lang.String(message_content);
message_id = sprintf('x%.0f',str.hashCode()+2^31);
% and check if it had been displayed before
if ~isfield(displayed_warnings,message_id)
% emit the warning
warning(varargin{:});
% remember to not display the warning again
displayed_warnings.(message_id) = true;
end
end
|
github
|
lcnhappe/happe-master
|
hlp_varargin2struct.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_varargin2struct.m
| 6,267 |
utf_8
|
a185d699c488adb84cda30f6db5facda
|
function res = hlp_varargin2struct(args, varargin)
% Convert a list of name-value pairs into a struct with values assigned to names.
% struct = hlp_varargin2struct(Varargin, Defaults)
%
% In:
% Varargin : cell array of name-value pairs and/or structs (with values assigned to names)
%
% Defaults : optional list of name-value pairs, encoding defaults; multiple alternative names may
% be specified in a cell array
%
% Example:
% function myfunc(x,y,z,varargin)
% % parse options, and give defaults for some of them:
% options = hlp_varargin2struct(varargin, 'somearg',10, 'anotherarg',{1 2 3});
%
% Notes:
% * mandatory args can be expressed by specifying them as ..., 'myparam',mandatory, ... in the defaults
% an error is raised when any of those is left unspecified
%
% * the following two parameter lists are equivalent (note that the struct is specified where a name would be expected,
% and that it replaces the entire name-value pair):
% ..., 'xyz',5, 'a',[], 'test','toast', 'xxx',{1}. ...
% ..., 'xyz',5, struct( 'a',{[]},'test',{'toast'} ), 'xxx',{1}, ...
%
% * names with dots are allowed, i.e.: ..., 'abc',5, 'xxx.a',10, 'xxx.yyy',20, ...
%
% * some parameters may have multiple alternative names, which shall be remapped to the
% standard name within opts; alternative names are given together with the defaults,
% by specifying a cell array of names instead of the name in the defaults, as in the following example:
% ... ,{'standard_name','alt_name_x','alt_name_y'}, 20, ...
%
% Out:
% Result : a struct with fields corresponding to the passed arguments (plus the defaults that were
% not overridden); if the caller function does not retrieve the struct, the variables are
% instead copied into the caller's workspace.
%
% Examples:
% % define a function which takes some of its arguments as name-value pairs
% function myfunction(myarg1,myarg2,varargin)
% opts = hlp_varargin2struct(varargin, 'myarg3',10, 'myarg4',1001, 'myarg5','test');
%
% % as before, but this time allow an alternative name for myarg3
% function myfunction(myarg1,myarg2,varargin)
% opts = hlp_varargin2struct(varargin, {'myarg3','legacyargXY'},10, 'myarg4',1001, 'myarg5','test');
%
% % as before, but this time do not return arguments in a struct, but assign them directly to the
% % function's workspace
% function myfunction(myarg1,myarg2,varargin)
% hlp_varargin2struct(varargin, {'myarg3','legacyargXY'},10, 'myarg4',1001, 'myarg5','test');
%
% See also:
% hlp_struct2varargin, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-05
% a struct was specified as first argument
if isstruct(args)
args = {args}; end
% --- handle defaults ---
if ~isempty(varargin)
% splice substructs into the name-value list
if any(cellfun('isclass',varargin(1:2:end),'struct'))
varargin = flatten_structs(varargin); end
defnames = varargin(1:2:end);
defvalues = varargin(2:2:end);
% make a remapping table for alternative default names...
for k=find(cellfun('isclass',defnames,'cell'))
for l=2:length(defnames{k})
name_for_alternative.(defnames{k}{l}) = defnames{k}{1}; end
defnames{k} = defnames{k}{1};
end
% create default struct
if [defnames{:}]~='.'
% use only the last assignment for each name
[s,indices] = sort(defnames(:));
indices( strcmp(s((1:end-1)'),s((2:end)'))) = [];
% and make the struct
res = cell2struct(defvalues(indices),defnames(indices),2);
else
% some dot-assignments are contained in the defaults
try
res = struct();
for k=1:length(defnames)
if any(defnames{k}=='.')
eval(['res.' defnames{k} ' = defvalues{k};']);
else
res.(defnames{k}) = defvalues{k};
end
end
catch
error(['invalid field name specified in defaults: ' defnames{k}]);
end
end
else
res = struct();
end
% --- handle overrides ---
if ~isempty(args)
% splice substructs into the name-value list
if any(cellfun('isclass',args(1:2:end),'struct'))
args = flatten_structs(args); end
% rewrite alternative names into their standard form...
if exist('name_for_alternative','var')
for k=1:2:length(args)
if isfield(name_for_alternative,args{k})
args{k} = name_for_alternative.(args{k}); end
end
end
% override defaults with arguments...
try
if [args{1:2:end}]~='.'
for k=1:2:length(args)
res.(args{k}) = args{k+1}; end
else
% some dot-assignments are contained in the overrides
for k=1:2:length(args)
if any(args{k}=='.')
eval(['res.' args{k} ' = args{k+1};']);
else
res.(args{k}) = args{k+1};
end
end
end
catch
if ischar(args{k})
error(['invalid field name specified in arguments: ' args{k}]);
else
error(['invalid field name specified for the argument at position ' num2str(k)]);
end
end
end
% check for missing but mandatory args
% note: the used string needs to match mandatory.m
missing_entries = strcmp('__arg_mandatory__',struct2cell(res));
if any(missing_entries)
fn = fieldnames(res)';
fn = fn(missing_entries);
error(['The parameters {' sprintf('%s, ',fn{1:end-1}) fn{end} '} were unspecified but are mandatory.']);
end
% copy to the caller's workspace if no output requested
if nargout == 0
for fn=fieldnames(res)'
assignin('caller',fn{1},res.(fn{1})); end
end
% substitute any structs in place of a name-value pair into the name-value list
function args = flatten_structs(args)
k = 1;
while k <= length(args)
if isstruct(args{k})
tmp = [fieldnames(args{k}) struct2cell(args{k})]';
args = [args(1:k-1) tmp(:)' args(k+1:end)];
k = k+numel(tmp);
else
k = k+2;
end
end
|
github
|
lcnhappe/happe-master
|
hlp_worker.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_worker.m
| 5,701 |
utf_8
|
912f4bd9ba397e3e40f05b77f7bf1fb5
|
function hlp_worker(varargin)
% Act as a lightweight worker process for use with hlp_schedule.
% hlp_worker(Options...)
%
% Receives commands (string expressions) from the network, evaluate them, and send off the result to
% some collector (again as a string). Processing is done in a single thread.
%
% In:
% Options... : optional name-value pairs, with possible names:
% 'port': port number on which to listen for requests (default: 23547)
% if the port is already in use, the next free one will be chosen,
% until port+portrange is exceeded; then, a free one will be chosen
% if specified as 0, a free one is chosen directly
%
% 'portrange': number of ports to try following the default/supplied port (default: 16)
%
% 'backlog': backlog of queued incoming connections (default: 0)
%
% 'timeout_accept': timeout for accepting connections, in seconds (default: 3)
%
% 'timeout_send': timeout for sending results, in seconds (default: 10)
%
% 'timeout_recv': timeout for receiving data, in seconds (default: 5)
%
% Notes:
% * use multiple workers to make use of multiple cores
% * use only ports that are not accessible from the internet
% * request format: <task_id><collectoraddress_length><collectoraddress><body_length><body>
% <task_id>: identifier of the task (needs to be forwarded, with the result,
% to a some data collector upon task completion) (int)
% <collectoraddress_length>: length, in bytes, of the data collector's address (int)
% <collectoraddress>: where to send the result for collection (string, formatted as host:port)
% <body_length>: length, in bytes, of the message body (int)
% <body>: a MATLAB command that yields, when evaluated, some result in ans (string, as MATLAB expression)
% if an exception occurs, the exception struct (as from lasterror) replaces ans
% * response format: <task_id><body_length><body>
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-08-26
import java.io.*
import java.net.*
% read options
opts = hlp_varargin2struct(varargin, 'port',23547, 'portrange',16, 'backlog',1, 'timeout_accept',3, ...
'timeout_send',10, 'timeout_recv',5, 'receive_buffer',64000);
% open a new server socket (first trying the specified portrange, then falling back to 0)
for port = [opts.port:opts.port+opts.portrange 0]
try
serv = ServerSocket(port, opts.backlog);
break;
catch,end
end
disp(['This is ' hlp_hostname ' (' hlp_hostip '). Listening on port ' num2str(serv.getLocalPort())]);
% set socket properties (e.g., making the function interruptible)
serv.setReceiveBufferSize(opts.receive_buffer);
serv.setSoTimeout(round(1000*opts.timeout_accept));
% make sure that the server socket will be closed when this function is terminated
cleaner = onCleanup(@()serv.close());
tasknum = 1;
disp('waiting for connections...');
while 1
try
% wait for an incoming request
conn = serv.accept();
conn.setSoTimeout(round(1000*opts.timeout_recv));
conn.setTcpNoDelay(1);
disp('connected.');
try
% parse request
in = DataInputStream(conn.getInputStream());
cr = ChunkReader(in);
taskid = in.readInt();
collector = char(cr.readFully(in.readInt())');
task = char(cr.readFully(in.readInt())');
disp('received data; replying.');
out = DataOutputStream(conn.getOutputStream());
out.writeInt(taskid+length(collector)+length(task));
out.flush();
conn.close();
% evaluate task & serialize result
disp(['running task ' num2str(taskid) ' (' num2str(tasknum) ') ...']); tasknum = tasknum+1;
result = hlp_serialize(evaluate(task));
disp('done with task; opening back link...');
try
% send off the result
idx = find(collector==':',1);
outconn = Socket(collector(1:idx-1), str2num(collector(idx+1:end)));
disp('connected; now sending...');
outconn.setTcpNoDelay(1);
outconn.setSoTimeout(round(1000*opts.timeout_recv));
out = DataOutputStream(outconn.getOutputStream());
out.writeInt(taskid);
out.writeInt(length(result));
out.writeBytes(result);
out.flush();
outconn.close();
disp('done.');
disp('waiting for connections...');
catch
e = lasterror; %#ok<LERR>
if isempty(strfind(e.message,'timed out'))
disp(['Exception during result forwarding: ' e.message]); end
end
catch
conn.close();
e = lasterror; %#ok<LERR>
if ~isempty(strfind(e.message,'EOFException'))
disp(['cancelled.']);
elseif isempty(strfind(e.message,'timed out'))
disp(['Exception during task receive: ' e.message]);
end
end
catch
e = lasterror; %#ok<LERR>
if isempty(strfind(e.message,'timed out'))
disp(['Exception during accept: ' e.message]); end
end
end
function result = evaluate(task)
% evaluate a task
try
ans = []; %#ok<NOANS>
eval([task ';']);
result = ans; %#ok<NOANS>
catch
result = lasterror; %#ok<LERR>
end
|
github
|
lcnhappe/happe-master
|
hlp_superimposedata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/helpers/hlp_superimposedata.m
| 5,438 |
utf_8
|
512675e236e6e374f99cf433a05bb974
|
function res = hlp_superimposedata(varargin)
% Merge multiple partially populated data structures into one fully populated one.
% Result = hlp_superimposedata(Data1, Data2, Data3, ...)
%
% The function is applicable when you have cell arrays or structs/struct arrays with non-overlapping
% patterns of non-empty entries, where all entries should be merged into a single data structure
% which retains their original positions. If entries exist in multiple data structures at the same
% location, entries of later items will be ignored (i.e. earlier data structures take precedence).
%
% In:
% DataK : a data structure that should be super-imposed with the others to form a single data
% structure
%
% Out:
% Result : the resulting data structure
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-08-19
% first, compactify the data by removing the empty items
compact = varargin(~cellfun('isempty',varargin));
% start with the last data structure, then merge the remaining data structures into it (in reverse
% order as this avoids having to grow arrays incrementally in typical cases)
res = compact{end};
for k=length(compact)-1:-1:1
res = merge(res,compact{k}); end
% merge data structures A and B
function A = merge(A,B)
if iscell(A) && iscell(B)
% make sure that both have the same number of dimensions
if ndims(A) > ndims(B)
B = grow_cell(B,size(A));
elseif ndims(A) < ndims(B)
A = grow_cell(A,size(B));
end
% make sure that both have the same size
if all(size(B)==size(A))
% we're fine
elseif all(size(B)>=size(A))
% A is a minor of B: grow A
A = grow_cell(A,size(B));
elseif all(size(A)>=size(B))
% B is a minor of A: grow B
B = grow_cell(B,size(A));
else
% A and B have mixed sizes... grow both as necessary
M = max(size(A),size(B));
A = grow_cell(A,M);
B = grow_cell(B,M);
end
% find all non-empty elements in B
idx = find(~cellfun(@(x)isequal(x,[]),B));
if ~isempty(idx)
% check if any of these is occupied in A
clean = cellfun('isempty',A(idx));
if ~all(clean)
% merge all conflicting items recursively
conflicts = idx(~clean);
for k=conflicts(:)'
A{k} = merge(A{k},B{k}); end
% and transfer the rest
if any(clean)
A(idx(clean)) = B(idx(clean)); end
else
% transfer all to A
A(idx) = B(idx);
end
end
elseif isstruct(A) && isstruct(B)
% first make sure that both have the same fields
fnA = fieldnames(A);
fnB = fieldnames(B);
if isequal(fnA,fnB)
% we're fine
elseif isequal(sort(fnA),sort(fnB))
% order doesn't match -- impose A's order on B
B = orderfields(B,fnA);
elseif isempty(setdiff(fnA,fnB))
% B has a superset of A's fields: add the remaining fields to A, and order them according to B
remaining = setdiff(fnB,fnA);
for fn = remaining'
A(1).(fn{1}) = []; end
A = orderfields(A,fnB);
elseif isempty(setdiff(fnB,fnA))
% A has a superset of B's fields: add the remaining fields to B, and order them according to A
remaining = setdiff(fnA,fnB);
for fn = remaining'
B(1).(fn{1}) = []; end
B = orderfields(B,fnA);
else
% A and B have incommensurable fields; add B's fields to A's fields, add A's fields to B's
% and order according to A's fields
remainingB = setdiff(fnB,fnA);
for fn = remainingB'
A(1).(fn{1}) = []; end
remainingA = setdiff(fnA,fnB);
for fn = remainingA'
B(1).(fn{1}) = []; end
B = orderfields(B,A);
end
% that being established, convert them to cell arrays, merge their cell arrays, and convert back to structs
merged = merge(struct2cell(A),struct2cell(B));
A = cell2struct(merged,fieldnames(A),1);
elseif isstruct(A) && ~isstruct(B)
if ~isempty(B)
error('One of the sub-items is a struct, and the other one is of a non-struct type.');
else
% we retain A
end
elseif isstruct(B) && ~isstruct(A)
if ~isempty(A)
error('One of the sub-items is a struct, and the other one is of a non-struct type.');
else
% we retain B
A = B;
end
elseif iscell(A) && ~iscell(B)
if ~isempty(B)
error('One of the sub-items is a cell array, and the other one is of a non-cell type.');
else
% we retain A
end
elseif iscell(B) && ~iscell(A)
if ~isempty(A)
error('One of the sub-items is a cell array, and the other one is of a non-cell type.');
else
% we retain B
A = B;
end
elseif isempty(A) && ~isempty(B)
% we retain B
A = B;
elseif isempty(B) && ~isempty(A)
% we retain A
elseif ~isequal_weak(A,B)
% we retain A and warn about dropping B
warn_once('Two non-empty (and non-identical) sub-elements occupied the same index; one was dropped. This warning will only be displayed once.');
end
% grow a cell array to accomodate a particular index
% (assuming that this index is not contained in the cell array yet)
function C = grow_cell(C,idx)
tmp = sprintf('%i,',idx);
eval(['C{' tmp(1:end-1) '} = [];']);
|
github
|
lcnhappe/happe-master
|
arg_guidialog.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog.m
| 10,844 |
utf_8
|
9a3feeb49fd1fa36ac5971ebb38d1ab9
|
function varargout = arg_guidialog(func,varargin)
% Create an input dialog that displays input fields for a Function and Parameters.
% Parameters = arg_guidialog(Function, Options...)
%
% The Parameters that are passed to the function can be used to override some of its defaults. The
% function must declare its arguments via arg_define. In addition, only a Subset of the function's
% specified arguments can be displayed.
%
% In:
% Function : the function for which to display arguments
%
% Options... : optional name-value pairs; possible names are:
% 'Parameters' : cell array of parameters to the Function to override some of its
% defaults.
%
% 'Subset' : Cell array of argument names to which the dialog shall be restricted;
% these arguments may contain . notation to index into arg_sub and the
% selected branch(es) of arg_subswitch/arg_subtoggle specifiers. Empty
% cells show up in the dialog as empty rows.
%
% 'Title' : title of the dialog (by default: functionname())
%
% 'Invoke' : whether to invoke the function directly; in this case, the output
% arguments are those of the function (default: true, unless called in
% the form g = arg_guidialog; e.g., from within some function)
%
% Out:
% Parameters : a struct that is a valid input to the Function.
%
% Examples:
% % bring up a configuration dialog for the given function
% settings = arg_guidialog(@myfunction)
%
% % bring up a config dialog with some pre-specified defaults
% settings = arg_guidialog(@myfunction,'Parameters',{4,20,'test'})
%
% % bring up a config dialog which displays only a subset of the function's arguments (in a particular order)
% settings = arg_guidialog(@myfunction,'Subset',{'blah','xyz',[],'flag'})
%
% % bring up a dialog, and invoke the function with the selected settings after the user clicks OK
% settings = arg_guidialog(@myfunction,'Invoke',true)
%
% See also:
% arg_guidialog_ex, arg_guipanel, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-24
if ~exist('func','var')
% called with no arguments, from inside a function: open function dialog
func = hlp_getcaller;
varargin = {'Parameters',evalin('caller','varargin'),'Invoke',nargout==0};
end
% parse arguments...
hlp_varargin2struct(varargin,{'params','Parameters','parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[],{'invoke','Invoke'},true);
oldparams = params;
% obtain the argument specification for the function
rawspec = arg_report('rich', func, params); %#ok<*NODEF>
% extract a list of sub arguments...
if ~isempty(subset) && subset{1}==-1
% user specified a set of items to *exclude*
% convert subset to setdiff(all-arguments,subset)
allnames = fieldnames(arg_tovals(rawspec));
subset(1) = [];
subset = allnames(~ismember(allnames,[subset 'arg_direct']));
end
[spec,subset] = obtain_items(rawspec,subset);
% create an inputgui() dialog...
geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2);
geomvert = ones(1,length(spec)+length(buttons)/2);
% turn the spec into a UI list...
uilist = {};
for k = 1:length(spec)
s = spec{k};
if isempty(s)
uilist(end+1:end+2) = {{} {}};
else
if isempty(s.help)
error(['Cannot display the argument ' subset{k} ' because it contains no description.']);
else
tag = subset{k};
uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'};
% depending on the type, we introduce different types of input widgets here...
if iscell(s.range) && strcmp(s.type,'char')
% string popup menu
uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag};
elseif strcmp(s.type,'logical')
if length(s.range)>1
% multiselect
uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000};
geomvert(k) = min(3.5,length(s.range));
else
% checkbox
uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag};
end
elseif strcmp(s.type,'char')
% string edit
uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag};
else
% expression edit
if isinteger(s.value)
s.value = double(s.value); end
uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag};
end
% append the tooltip string
if length(s.help) > 1
uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end
end
end
if ~isempty(buttons) && k==buttons{1}
% render a command button
uilist(end+1:end+2) = {{} buttons{2}};
buttons(1:2) = [];
end
end
% invoke the GUI, obtaining a list of output values...
helptopic = char(func);
try
if helptopic(1) == '@'
fn = functions(func);
tmp = struct2cell(fn.workspace{1});
helptopic = class(tmp{1});
end
catch
disp('Cannot deduce help topic.');
end
[outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom',['env_doc ' helptopic], 'title',dialogtitle,'geomvert',geomvert); %#ok<ASGLU>
if ~isempty(okpressed)
% remove blanks from the spec
spec = spec(~cellfun('isempty',spec));
subset = subset(~cellfun('isempty',subset));
% turn the raw specification into a parameter struct (a non-direct one, since we will mess with
% it)
params = arg_tovals(rawspec,false);
% for each parameter produced by the GUI...
for k = 1:length(outs)
s = spec{k}; % current specifier
v = outs{k}; % current raw value
% do type conversion according to spec
if iscell(s.range) && strcmp(s.type,'char')
v = s.range{v};
elseif strcmp(s.type,'expression')
v = eval(v);
elseif strcmp(s.type,'logical')
if length(s.range)>1
v = s.range(v);
else
v = logical(v);
end
elseif strcmp(s.type,'char')
% noting to do
else
if ~isempty(v)
v = eval(v); % convert back to numeric (or object, or cell) value
end
end
% assign the converted value to params struct...
params = assign(params,subset{k},v);
end
% now send the result through the function to check for errors and obtain a values structure...
params = arg_report('rich',func,{params});
params = arg_tovals(params,false);
% invoke the function, if so desired
if ischar(func)
func = str2func(func); end
if invoke
[varargout{1:nargout(func)}] = func(oldparams{:},params);
else
varargout = {params};
end
else
varargout = {[]};
end
% obtain a cell array of spec entries by name from the given specification
function [items,ids] = obtain_items(rawspec,requested,prefix)
if ~exist('prefix','var')
prefix = ''; end
items = {};
ids = {};
% determine what subset of (possibly nested) items is requested
if isempty(requested)
% look for a special argument/property arg_dialogsel, which defines the standard dialog
% representation for the given specification
dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names}));
if ~isempty(dialog_sel)
requested = rawspec(dialog_sel).value; end
end
if isempty(requested)
% empty means that all items are requested
for k=1:length(rawspec)
items{k} = rawspec(k);
ids{k} = [prefix rawspec(k).names{1}];
end
else
% otherwise we need to obtain those items
for k=1:length(requested)
if ~isempty(requested{k})
try
[items{k},subid] = obtain(rawspec,requested{k});
catch
error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']);
end
ids{k} = [prefix subid];
end
end
end
% splice items that have children (recursively) into this list
for k = length(items):-1:1
% special case: switch arguments are not spliced, but instead the argument that defines the
% option popupmenu will be retained
if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested))
[subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']);
if ~isempty(subitems)
% and introduce blank rows around them
items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)];
ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)];
end
end
end
% remove items that cannot be displayed
retain = cellfun(@(x)isempty(x)||x.displayable,items);
items = items(retain);
ids = ids(retain);
% remove double blank rows
empties = cellfun('isempty',ids);
items(empties(1:end-1) & empties(2:end)) = [];
ids(empties(1:end-1) & empties(2:end)) = [];
% obtain a spec entry by name from the given specification
function [item,id] = obtain(rawspec,identifier,prefix)
if ~exist('prefix','var')
prefix = ''; end
% parse the . notation
dot = find(identifier=='.',1);
if ~isempty(dot)
[head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end));
else
head = identifier;
rest = [];
end
% search for the identifier at this level
names = {rawspec.names};
for k=1:length(names)
if any(strcmp(names{k},head))
% found a match!
if isempty(rest)
% return it
item = rawspec(k);
id = [prefix names{k}{1}];
else
% obtain the rest of the identifier
[item,id] = obtain(rawspec(k).children,rest,[prefix names{k}{1} '.']);
end
return;
end
end
error(['The given identifier (' head ') was not found among the function''s declared arguments.']);
% assign a field with dot notation in a struct
function s = assign(s,id,v)
% parse the . notation
dot = find(id=='.',1);
if ~isempty(dot)
[head,rest] = deal(id(1:dot-1), id(dot+1:end));
if ~isfield(s,head)
s.(head) = struct(); end
s.(head) = assign(s.(head),rest,v);
else
s.(id) = v;
end
|
github
|
lcnhappe/happe-master
|
arg_define.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_define.m
| 28,888 |
utf_8
|
79e413010787b04cc5fec2c1d1aa0d04
|
function res = arg_define(vals,varargin)
% Declare function arguments with optional defaults and built-in GUI support.
% Struct = arg_define(Values, Specification...)
% Struct = arg_define(Format, Values, Specification...)
%
% This is essentially an improved replacement for the parameter declaration line of a function.
% Assigns Values (a cell array of values, typically the "varargin" of the calling function,
% henceforth named the "Function") to fields in the output Struct, with parsing implemented
% according to a Specification of argument names and their order (optionally with a custom argument
% Format description).
%
% By default, values can be a list of a fixed number of positional arguments (i.e., the typical
% MATLAB calling format), optionally followed by a list of name-value pairs (NVPs, e.g., as the
% format accepted by figure()), in which, as well, instead of any given NVP, a struct may be
% passed (thus, one may pass a mix of 'name',value,struct,'name',value,'name',value, ...
% parameters). Alternatively, by default the entire list of positional arguments can instead be be
% specified as a list of NVPs/structs. Only names that are allowed by the Specification may be used,
% if positional syntax is allowed by the Format (which is the default).
%
% The special feature over hlp_varargin2struct()-like functionality is that arguments defined via
% arg_define can be reported to outside functions (if triggered by arg_report()). The resulting
% specification can be rendered in a GUI or be processed otherwise.
%
% In:
% Format : Optional format description (default: [0 Inf]):
% * If this is a number (say, k), it indicates that the first k arguments are specified
% in a positional manner, and the following arguments are specified as list of
% name-value pairs and/or structs.
% * If this is a vector of two numbers [0 k], it indicates that the first k arguments MAY
% be specified in a positional manner (the following arguments must be be specified as
% NVPs/structs) OR alternatively, all arguments can be specified as NVPs / structs.
% Only names that are listed in the specification may be used as names (in NVPs and
% structs) in this case.
% * If this is a function handle, the function is used to transform the Values prior to
% any other processing into a new Values cell array. The function may specify a new
% (numeric) Format as its second output argument (if not specified, this is 0).
%
% Values : A cell array of values passed to the function (usually the calling function's
% "varargin"). Interpreted according to the Format and the Specification.
%
% Specification... : The specification of the calling function's arguments; this is a sequence of
% arg(), arg_norep(), arg_nogui(), arg_sub(), arg_subswitch(), arg_subtoggle()
% specifiers. The special keywords mandatory and unassigned can be used in the
% declaration of default values, where "mandatory" declares that this argument
% must be assigned some value via Values (otherwise, an error is raised before
% the arg is passed to the Function) and "unassigned" declares that the
% variable will not be assigned unless passed as an argument (akin to the
% default behavior of regular MATLAB function arguments).
%
% Out:
% Struct : A struct with values assigned to fields, according to the Specification and Format.
%
% If this is not captured by the Function in a variable, the contents of Struct are
% instead assigned to the Function's workspace (default practice) -- but note that this
% only works for variable names are *not& also names of functions in the path (due to a
% flaw in MATLAB's treatment of identifiers). Thus, it is good advice to use long/expressive
% variable names to avoid this situation, or possibly CamelCase names.
%
% See also:
% arg, arg_nogui, arg_norep, arg_sub, arg_subswitch, arg_subtoggle
%
% Notes:
% 1) If the Struct output argument is omitted by the user, the arguments are not returned as a
% struct but instead directly copied into the Function's workspace.
%
% 2) Someone may call the user's Function with the request to deliver the parameter specification,
% instead of following the normal execution flow. arg_define() automatically handles this task
% by throwing an exception of the type 'BCILAB:arg:report_args' using arg_issuereport(), which
% is to be caught by the requesting function.
%
% Performance Tips:
% 1) If a struct with a field named 'arg_direct' is passed (and is set to true), or a name-value
% pair 'arg_direct',true is passed, then all type checking, specification parsing, fallback to
% default values and reporting functionality are skipped. This is a fast path to call a function,
% and it usually requires that all of its arguments are passed. The function arg_report allows
% to get a struct of all function arguments that can be used subsequently as part of a direct
% call.
%
% Please make sure not to pass multiple occurrences of 'arg_direct' with conflicting values to
% arg_define, as the behavior will then be undefined.
%
% 2) The function is about 2x as fast (in direct mode) if arguments are returned as a struct instead
% of being written into the caller's workspace.
%
% Examples:
% function myfunction(varargin)
%
% % begin a default argument declaration and declare a few arguments; The arguments can be passed either:
% % - by position: myfunction(4,20); including the option to leave some values at their defaults, e.g. myfunction(4) or myfunction()
% % - by name: myfunction('test',4,'blah',20); myfunction('blah',21,'test',4); myfunction('blah',22);
% % - as a struct: myfunction(struct('test',4,'blah',20))
% % - as a sequence of either name-value pairs or structs: myfunction('test',4,struct('blah',20)) (note that this is not ambiguous, as the struct would come in a place where only a name could show up otherwise
% arg_define(varargin, ...
% arg('test',3,[],'A test.'), ...
% arg('blah',25,[],'Blah.'));
%
% % a special syntax that is allowed is passing a particular parameter multiple times - in which case only the last specification is effective
% % myfunction('test',11, 'blah',21, 'test',3, struct('blah',15,'test',5), 'test',10) --> test will be 10, blah will be 15
%
% % begin an argument declaration which allows 0 positional arguments (i.e. everything must be passed by name
% arg_define(0,varargin, ...
%
% % begin an argument declaration which allows exactly 1 positional arguments, i.e. the first one must be passed by position and the other one by name (or struct)
% % valid calls would be: myfunction(3,'blah',25); myfunction(3); myfunction(); (the last one assumes the default for both)
% arg_define(1,varargin, ...
% arg('test',3,[],'A test.'), ...
% arg('blah',25,[],'Blah.'));
%
% % begin an argument decalration which allows either 2 positional arguments or 0 positional arguments (i.e. either the first two are passed by position, or all are passed by name)
% % some valid calls are: myfunction(4,20,'flag',true); myfunction(4,20); myfunction(4,20,'xyz','test','flag',true); myfunction(4); myfunction('flag',true,'test',4,'blah',21); myfunction('flag',true)
% arg_define([0 2],varargin, ...
% arg('test',3,[],'A test.'), ...
% arg('blah',25,[],'Blah.'), ...
% arg('xyz','defaultstr',[],'XYZ.'), ...
% arg('flag',false,[],'Some flag.'));
%
% % begin an argument declaration in which the formatting of arguments is completely arbitrary, and a custom function takes care of bringing them into a form understood by
% % the arg_define implementation. This function takes a cell array of arguments (in any formatting), and returns a cell array of a standard formatting (e.g. name-value pairs, or structs)
% arg_define(@myparser,varargin, ...
% arg('test',3,[],'A test.'), ...
% arg('blah',25,[],'Blah.'));
%
% % return the arguments as fields in a struct (here: opts), instead of directly in the workspace
% opts = arg_define(varargin, ...
% arg('test',3,[],'A test.'), ...
% arg('blah',25,[],'Blah.'));
%
% % note: in the current implementation, the only combinations of allowed argument numbers are: arg_define(...); arg_define(0, ...); arg_define(X, ...); arg_define([0 X], ...); arg_define(@somefunc, ...);
% % the implicit default is arg_define([0 Inf], ...)
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-24
% --- get Format, Values and Specification ---
if iscell(vals)
% no Format specifier was given: use default
fmt = [0 Inf];
spec = varargin;
try
% quick checks for direct (fast) mode
if isfield(vals{end},'arg_direct')
direct_mode = vals{end}.arg_direct;
elseif strcmp(vals{1},'arg_direct')
direct_mode = vals{2};
else
% figure it out later
direct_mode = false;
end
structs = cellfun('isclass',vals,'struct');
catch
% vals was empty: default behavior
direct_mode = false;
end
else
% a Format specifier was given as the first argument (instead of vals as the first argument) ...
if isempty(vals)
% ... but it was empty: use default behavior
fmt = [0 Inf];
else
% ... and was nonempty: use it
fmt = vals;
end
% shift the remaining two args
vals = varargin{1};
spec = varargin(2:end);
if isa(fmt,'function_handle')
% Format was a function: run it
if nargout(fmt) == 1
vals = fmt(vals);
fmt = 0;
else
[vals,fmt] = feval(fmt,vals);
end
end
direct_mode = false;
end
% --- if not yet known, determine conclusively if we are in direct mode (specificationless and therefore fast) ---
% this mode is only applicable when all arguments can be passed as NVPs/structs
if ~direct_mode && any(fmt == 0)
% search for an arg_direct argument
structs = cellfun('isclass',vals,'struct');
indices = find(structs | strcmp(vals,'arg_direct'));
for k = indices(end:-1:1)
if ischar(vals{k}) && k<length(vals)
% found it in the NVPs
direct_mode = vals{k+1};
break;
elseif isfield(vals{k},'arg_direct')
% found it in a struct
direct_mode = vals{k}.arg_direct;
break;
end
end
end
if direct_mode
% --- direct mode: quickly collect NVPs from the arguments and produce a result ---
% obtain flat NVP list
if any(structs(1:2:end))
vals = flatten_structs(vals); end
if nargout
% get names & values
names = vals(1:2:end);
values = vals(2:2:end);
% use only the last assignment for each name
[s,indices] = sort(names);
indices(strcmp(s(1:end-1),s(2:end))) = [];
% build & return a struct
res = cell2struct(values(indices),names(indices),2);
else
% place the arguments in the caller's workspace
for k=1:2:length(vals)
assignin('caller',vals{k},vals{k+1}); end
end
try
% also return the arguments in NVP form
assignin('caller','arg_nvps',vals);
catch
% this operation might be disallowed under some circumstances
end
else
% --- full parsing mode: determine the reporting type ---
% usually, the reporting type is 'none', except if called (possibly indirectly) by
% arg_report('type', ...): in this case, the reporting type is 'type' reporting is a special way to
% call arg_define, which requests the argument specification, so that it can be displayed by GUIs,
% etc.
%
% * 'none' normal execution: arg_define returns a Struct of Values to the Function or assigns the
% Struct's fields to the Function's workspace
% * 'rich' arg_define yields a rich specifier list to arg_report(), basically an array of specifier
% structs (see arg_specifier for the field names)
% * 'lean' arg_define yields a lean specifier list to arg_report(), basically an array of specifier
% structs but without alternatives for multi-option specifiers
% * 'vals' arg_define yields a struct of values to arg_report(), wich can subsequently be used as
% the full specification of arguments to pass to the Function
try
throw; %#ok<LTARG> % faster than error()
catch context
names = {context.stack(3:min(6,end)).name}; % function names at the considered levels of indirection...
matches = find(strncmp(names,'arg_report_',11)); % ... which start with 'arg_report_'
if isempty(matches)
reporting_type = 'none'; % no report requested (default case)
else
% the reporting type is the suffix of the deepest arg_report_* function in the call stack
reporting_type = names{matches(end)}(11+1:end);
end
end
% --- deal with 'handle' and 'properties' reports ---
if strcmp(reporting_type,'handle')
% very special report type: 'handle'--> this asks for function handles to nested / scoped
% functions. unfortunately, these cannot be obtained using standard MATLAB functionality.
if ~iscellstr(vals)
error('The arguments passed for handle report must denote function names.'); end
unresolved = {};
for f=1:length(vals)
% resolve each function name in the caller scope
funcs{f} = evalin('caller',['@' vals{f}]);
% check if the function could be retrieved
tmp = functions(funcs{f});
if isempty(tmp.file)
unresolved{f} = vals{f}; end
end
if ~isempty(unresolved)
% search the remaining ones in the specification
for f=find(~cellfun('isempty',unresolved))
funcs{f} = hlp_microcache('findfunction',@find_function_cached,spec,vals{f}); end
end
% report it
if length(funcs) == 1
funcs = funcs{1}; end
arg_issuereport(funcs);
elseif strcmp(reporting_type,'properties')
% 'properties' report, but no properties were declared
arg_issuereport(struct());
end
% --- one-time evaluation of the Specification list into a struct array ---
% evaluate the specification or retrieve it from cache
[spec,all_names,joint_names,remap] = hlp_microcache('spec',@evaluate_spec,spec,reporting_type,nargout==0);
% --- transform vals to a pure list of name-value pairs (NVPs) ---
if length(fmt) == 2
if fmt(1) ~= 0 || fmt(2) <= 0
% This error is thrown when the first parameter to arg_define() was not a cell array (i.e., not varargin),
% so that it is taken to denote the optional Format parameter.
% Format is usually a numeric array that specifies the number of positional arguments that are
% accepted by the function, and if numeric, it can only be either a number or a two-element array
% that contains 0 and a non-zero number.
error('For two-element formats, the first entry must be 0 and the second entry must be > 0.');
end
% there are two possible options: either 0 arguments are positional, or k arguments are
% positional; assuming at first that 0 arguments are positional, splice substructs into one
% uniform NVP list (this is because structs are allowed instead of individual NVPs)
if any(cellfun('isclass',vals(1:2:end),'struct'))
nvps = flatten_structs(vals);
else
nvps = vals;
end
% check if all the resulting names are in the set of allowed names (a disambiguation
% condition in this case)
if iscellstr(nvps(1:2:end))
try
disallowed_nvp = fast_setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]);
catch
disallowed_nvp = setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]);
end
else
disallowed_nvp = {'or the sequence of names and values was confused'};
end
if isempty(disallowed_nvp)
% the assumption was correct: 0 arguments are positional
fmt = 0;
else
% the assumption was violated: k arguments are positional, and we enfore strict naming
% for the remaining ones (i.e. names must be in the Specification).
strict_names = true;
fmt = fmt(2);
end
elseif fmt == 0
% 0 arguments are positional
nvps = flatten_structs(vals);
elseif fmt > 0
% k arguments are positional, the rest are NVPs (no need to enforce strict naming here)
strict_names = false;
else
% This error refers to the optional Format argument.
error('Negative or NaN formats are not allowed.');
end
% (from now on fmt holds the determined # of positional arguments)
if fmt > 0
% the first k arguments are positional
% Find out if we are being called by another arg_define; in this case, this definition
% appears inside an arg_sub/arg_*, and the values passed to the arg_define are part of the
% defaults declaration of one of these. If these defaults are specified positionally, the
% first k arg_norep() arguments in Specification are implicitly skipped.
if ~strcmp(reporting_type,'none') && any(strcmp('arg_define',{context.stack(2:end).name}));
% we implicitly skip the leading non-reportable arguments in the case of positional
% assignment (assuming that these are supplied by the outer function), by shifting the
% name/value assignment by the appropriate number of places
shift_positionals = min(fmt,find([spec.reportable],1)-1);
else
shift_positionals = 0;
end
% get the effective number of positional arguments
fmt = min(fmt,length(vals)+shift_positionals);
% the NVPs begin only after the k'th argument (defined by the Format)
nvps = vals(fmt+1-shift_positionals:end);
% splice in any structs
if any(cellfun('isclass',nvps(1:2:end),'struct'))
nvps = flatten_structs(nvps); end
% do minimal error checking...
if ~iscellstr(nvps(1:2:end))
% If you are getting this error, the order of names and values passed as name-value pairs
% to the function in question was likely mixed up. The error mentions structs because it
% is also allowed to pass in a struct in place of any 'name',value pair.
error('Some of the specified arguments that should be names or structs, are not.');
end
if strict_names
% enforce strict names
try
disallowed_pos = fast_setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]);
catch
disallowed_pos = setdiff(nvps(1:2:end),[joint_names {'arg_selection','arg_direct'}]);
end
if ~isempty(disallowed_pos)
% If you are getting this error, it is most likely due to a mis-typed argument name
% in the list of name-value pairs passed to the function in question.
%
% Because some functions may support also positional arguments, it is also possible
% that something that was supposed to be the value for one of the positional
% arguments was interpreted as part of the name-value pairs lit that may follow the
% positional arguments of the function. This error is likely because the wrong number
% of positional arguments was passed (a safer alternative is to instead pass everything
% by name).
error(['Some of the specified arguments do not appear in the argument specification; ' format_cellstr(disallowed_pos) '.']);
end
end
try
% remap the positionals (everything up to the k'th argument) into an NVP list, using the
% code names
poss = [cellfun(@(x)x{1},all_names(shift_positionals+1:fmt),'UniformOutput',false); vals(1:fmt-shift_positionals)];
catch
if strict_names
% maybe the user intended to pass 0 positionals, but used some disallowed names
error(['Apparently, some of the used argument names are not known to the function: ' format_cellstr(disallowed_nvp) '.']);
else
error(['The first ' fmt ' arguments must be passed by position, and the remaining ones must be passed by name (either in name-value pairs or structs).']);
end
end
% ... and concatenate them with the remaining NVPs into one big NVP list
nvps = [poss(:)' nvps];
end
% --- assign values to names using the assigner functions of the spec ---
for k=1:2:length(nvps)
if isfield(remap,nvps{k})
idx = remap.(nvps{k});
spec(idx) = spec(idx).assigner(spec(idx),nvps{k+1});
else
% append it to the spec (note: this might need some optimization... it would be better
% if the spec automatically contained the arg_selection field)
tmp = arg_nogui(nvps{k},nvps{k+1});
spec(end+1) = tmp{1}([],tmp{2}{:});
end
end
% --- if requested, yield a 'vals', 'lean' or 'rich' report ---
if ~strcmp(reporting_type,'none')
% but deliver only the reportable arguments, and only if the values are not unassigned
tmp = spec([spec.reportable] & ~strcmp(unassigned,{spec.value}));
if strcmp(reporting_type,'vals')
tmp = arg_tovals(tmp); end
arg_issuereport(tmp);
end
% --- otherwise post-process the outputs and create a result struct to pass to the Function ---
% generate errors for mandatory arguments that were not assigned
missing_entries = strcmp(mandatory,{spec.value});
if any(missing_entries)
missing_names = cellfun(@(x)x{1},{spec(missing_entries).names},'UniformOutput',false);
error(['The arguments ' format_cellstr(missing_names) ' were unspecified but are mandatory.']);
end
% strip non-returned arguments, and convert it all to a struct of values
res = arg_tovals(spec);
% also emit a final NVPs list
tmp = [fieldnames(res) struct2cell(res)]';
try
assignin('caller','arg_nvps',tmp(:)');
catch
% this operation might be disallowed under some circumstances
end
% if requested, place the arguments in the caller's workspace
if nargout==0
for fn=fieldnames(res)'
assignin('caller',fn{1},res.(fn{1})); end
end
end
% substitute any structs in place of a name-value pair into the name-value list
function args = flatten_structs(args)
k = 1;
while k <= length(args)
if isstruct(args{k})
tmp = [fieldnames(args{k}) struct2cell(args{k})]';
args = [args(1:k-1) tmp(:)' args(k+1:end)];
k = k+numel(tmp);
else
k = k+2;
end
end
% evaluate a specification into a struct array
function [spec,all_names,joint_names,remap] = evaluate_spec(spec,reporting_type,require_namecheck)
if strcmp(reporting_type,'rich')
subreport_type = 'rich';
else
subreport_type = 'lean';
end
% evaluate the functions to get (possibly arrays of) specifier structs
for k=1:length(spec)
spec{k} = spec{k}{1}(subreport_type,spec{k}{2}{:}); end
% concatenate the structs to one big struct array
spec = [spec{:}];
% make sure that spec has the correct fields, even if empty
if isempty(spec)
spec = arg_specifier;
spec = spec([]);
end
% obtain the argument names and the joined names
all_names = {spec.names};
joint_names = [all_names{:}];
% create a name/index remapping table
remap = struct();
for n=1:length(all_names)
for k=1:length(all_names{n})
remap.(all_names{n}{k}) = n; end
end
% check for duplicate argument names in the Specification
sorted_names = sort(joint_names);
duplicates = joint_names(strcmp(sorted_names(1:end-1),sorted_names(2:end)));
if ~isempty(duplicates)
error(['The names ' format_cellstr(duplicates) ' refer to multiple arguments.']); end
% if required, check for name clashes with functions on the path
% (this is due to a glitch in MATLAB's handling of variables that were assigned to a function's scope
% from the outside, which are prone to clashes with functions on the path...)
if require_namecheck && strcmp(reporting_type,'none')
try
check_names(cellfun(@(x)x{1},all_names,'UniformOutput',false));
catch e
disp_once('The function check_names failed; reason: %s',e.message);
end
end
% check for name clashes (once)
function check_names(code_names)
persistent name_table;
if ~isstruct(name_table)
name_table = struct(); end
for name_cell = fast_setdiff(code_names,fieldnames(name_table))
current_name = name_cell{1};
existing_func = which(current_name);
if ~isempty(existing_func)
if ~exist('function_caller','var')
function_caller = hlp_getcaller(4);
if function_caller(1) == '@'
function_caller = hlp_getcaller(14); end
end
if isempty(strfind(existing_func,'Java method'))
[path_part,file_part,ext_part] = fileparts(existing_func);
if ~any(strncmp('@',hlp_split(path_part,filesep),1))
% If this happens, it means that there is a function in one of the directories in
% MATLAB's path which has the same name as an argument of the specification. If this
% argument variable is copied into the function's workspace by arg_define, most MATLAB
% versions will (incorrectly) try to call that function instead of accessing the
% variable. I hope that they handle this issue at some point. One workaround is to use
% a longer argument name (that is less likely to clash) and, if it should still be
% usable for parameter passing, to retain the old name as a secondary or ternary
% argument name (using a cell array of names in arg()). The only really good
% solution at this point is to generally assign the output of arg_define to a
% struct.
disp([function_caller ': The argument name "' current_name '" clashes with the function "' [file_part ext_part] '" in directory "' path_part '"; it is strongly recommended that you either rename the function or remove it from the path.']);
end
else
% these Java methods are probably spurious "false positives" of the which() function
disp([function_caller ': There is a Java method named "' current_name '" on your path; if you experience any name clash with it, please report this issue.']);
end
end
name_table.(current_name) = existing_func;
end
% recursively find a function handle by name in a specification
% the first occurrence of a handle to a function with the given name is returned
function r = find_function(spec,name)
r = [];
for k=1:length(spec)
if isa(spec(k).value,'function_handle') && strcmp(char(spec(k).value),name)
r = spec(k).value;
return;
elseif ~isempty(spec(k).alternatives)
for n = 1:length(spec(k).alternatives)
r = find_function(spec(k).alternatives{n},name);
if ~isempty(r)
return; end
end
elseif ~isempty(spec(k).children)
r = find_function(spec(k).children,name);
if ~isempty(r)
return; end
end
end
% find a function handle by name in a specification
function f = find_function_cached(spec,name)
% evaluate the functions to get (possibly arrays of) specifier structs
for k=1:length(spec)
spec{k} = spec{k}{1}('rich',spec{k}{2}{:}); end
% concatenate the structs to one big struct array
spec = [spec{:}];
% now search the function in it
f = find_function(spec,name);
% format a non-empty cell-string array into a string
function x = format_cellstr(x)
x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}'];
|
github
|
lcnhappe/happe-master
|
arg_guidialog_old.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog_old.m
| 8,955 |
utf_8
|
4da1a90f92312aea4043460655d5f6aa
|
function params = arg_guidialog(func,varargin)
% Create an input dialog that displays input fields for a Function and Parameters.
% Parameters = arg_guidialog(Function, Options...)
%
% The Parameters that are passed to the function can be used to override some of its defaults.
% The function must declare its arguments via arg_define. In addition, only a Subset of the function's specified arguments can be displayed.
%
% In:
% Function : the function for which to display arguments
%
% Options... : optional name-value pairs; possible names are:
% 'Parameters' : cell array of parameters to the Function to override some of its defaults.
%
% 'Subset' : Cell array of argument names to which the dialog shall be restricted; these arguments may contain . notation to index
% into arg_sub and the selected branch(es) of arg_subswitch/arg_subtoggle specifiers.
% Empty cells show up in the dialog as empty rows.
%
% 'Title' : title of the dialog (by default: functionname())
%
% Out:
% Parameters : a struct that is a valid input to the Function.
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-24
% parse arguments...
hlp_varargin2struct(varargin,{'params','Parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[]);
% obtain the argument specification for the function
rawspec = arg_report('rich', func, params); %#ok<*NODEF>
% extract a list of sub arguments...
if ~isempty(subset) && subset{1}==-1
% user specified a set of items to *exclude*
% convert subset to setdiff(all-arguments,subset)
allnames = fieldnames(arg_tovals(rawspec));
subset(1) = [];
subset = allnames(~ismember(allnames,[subset 'arg_direct']));
end
[spec,subset] = obtain_items(rawspec,subset);
% create an inputgui() dialog...
geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2);
geomvert = ones(1,length(spec)+length(buttons)/2);
% turn the spec into a UI list...
uilist = {};
for k = 1:length(spec)
s = spec{k};
if isempty(s)
uilist(end+1:end+2) = {{} {}};
else
if isempty(s.help)
error(['Cannot display the argument ' subset{k} ' because it contains no description.']);
else
tag = subset{k};
uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'};
% depending on the type, we introduce different types of input widgets here...
if iscell(s.range) && strcmp(s.type,'char')
% string popup menu
uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag};
elseif strcmp(s.type,'logical')
if length(s.range)>1
% multiselect
uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(ismember(s.range,s.value)),'tag',tag,'min',1,'max',100000};
geomvert(k) = min(3.5,length(s.range));
else
% checkbox
uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag};
end
elseif strcmp(s.type,'char')
% string edit
uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag};
else
% expression edit
if isinteger(s.value)
s.value = double(s.value); end
uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag};
end
% append the tooltip string
if length(s.help) > 1
uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end
end
end
if ~isempty(buttons) && k==buttons{1}
% render a command button
uilist(end+1:end+2) = {{} buttons{2}};
buttons(1:2) = [];
end
end
% invoke the GUI, obtaining a list of output values...
[outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom','disp(''coming soon...'')', 'title',dialogtitle,'geomvert',geomvert);
if ~isempty(okpressed)
% remove blanks from the spec
spec = spec(~cellfun('isempty',spec));
subset = subset(~cellfun('isempty',subset));
% turn the raw specification into a parameter struct (a non-direct one, since we will mess with it)
params = arg_tovals(rawspec,false);
% for each parameter produced by the GUI...
for k = 1:length(outs)
s = spec{k}; % current specifier
v = outs{k}; % current raw value
% do type conversion according to spec
if iscell(s.range) && strcmp(s.type,'char')
v = s.range{v};
elseif strcmp(s.type,'expression')
v = eval(v);
elseif strcmp(s.type,'logical')
if length(s.range)>1
v = s.range(v);
else
v = logical(v);
end
elseif strcmp(s.type,'char')
% noting to do
else
if ~isempty(v)
v = eval(v); % convert back to numeric (or object, or cell) value
end
end
% assign the converted value to params struct...
params = assign(params,subset{k},v);
end
% now send the result through the function to check for errors and obtain a values structure...
params = arg_report('rich',func,{params});
params = arg_tovals(params,false);
else
params = [];
end
% obtain a cell array of spec entries by name from the given specification
function [items,ids] = obtain_items(rawspec,requested,prefix)
if ~exist('prefix','var')
prefix = ''; end
items = {};
ids = {};
% determine what subset of (possibly nested) items is requested
if isempty(requested)
% look for a special argument/property arg_dialogsel, which defines the standard dialog representation for the given specification
dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names}));
if ~isempty(dialog_sel)
requested = rawspec(dialog_sel).value; end
end
if isempty(requested)
% empty means that all items are requested
for k=1:length(rawspec)
items{k} = rawspec(k);
ids{k} = [prefix rawspec(k).names{1}];
end
else
% otherwise we need to obtain those items
for k=1:length(requested)
if ~isempty(requested{k})
try
items{k} = obtain(rawspec,requested{k});
catch
error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']);
end
ids{k} = [prefix requested{k}];
end
end
end
% splice items that have children (recursively) into this list
for k = length(items):-1:1
% special case: switch arguments are not spliced, but instead the argument that defines the option popupmenu will be retained
if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested))
[subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']);
if ~isempty(subitems)
% and introduce blank rows around them
items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)];
ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)];
end
end
end
% remove items that cannot be displayed
retain = cellfun(@(x)isempty(x)||x.displayable,items);
items = items(retain);
ids = ids(retain);
% remove double blank rows
empties = cellfun('isempty',ids);
items(empties(1:end-1) & empties(2:end)) = [];
ids(empties(1:end-1) & empties(2:end)) = [];
% obtain a spec entry by name from the given specification
function item = obtain(rawspec,identifier)
% parse the . notation
dot = find(identifier=='.',1);
if ~isempty(dot)
[head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end));
else
head = identifier;
rest = [];
end
% search for the identifier at this level
names = {rawspec.names};
for k=1:length(names)
if any(strcmp(names{k},head))
% found a match!
if isempty(rest)
% return it
item = rawspec(k);
else
% obtain the rest of the identifier
item = obtain(rawspec(k).children,rest);
end
return;
end
end
error(['The given identifier (' head ') was not found among the function''s declared arguments.']);
% assign a field with dot notation in a struct
function s = assign(s,id,v)
% parse the . notation
dot = find(id=='.',1);
if ~isempty(dot)
[head,rest] = deal(id(1:dot-1), id(dot+1:end));
if ~isfield(s,head)
s.(head) = struct(); end
s.(head) = assign(s.(head),rest,v);
else
s.(id) = v;
end
|
github
|
lcnhappe/happe-master
|
arg_guidialog_ex.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_guidialog_ex.m
| 8,675 |
utf_8
|
82a7c00e1dfc74a921a596040b742fd9
|
function params = arg_guidialog(func,varargin)
% Create an input dialog that displays input fields for a Function and Parameters.
% Parameters = arg_guidialog(Function, Options...)
%
% The Parameters that are passed to the function can be used to override some of its defaults.
% The function must declare its arguments via arg_define. In addition, only a Subset of the function's specified arguments can be displayed.
%
% In:
% Function : the function for which to display arguments
%
% Options... : optional name-value pairs; possible names are:
% 'Parameters' : cell array of parameters to the Function to override some of its defaults.
%
% 'Subset' : Cell array of argument names to which the dialog shall be restricted; these arguments may contain . notation to index
% into arg_sub and the selected branch(es) of arg_subswitch/arg_subtoggle specifiers.
% Empty cells show up in the dialog as empty rows.
%
% 'Title' : title of the dialog (by default: functionname())
%
% Out:
% Parameters : a struct that is a valid input to the Function.
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-24
% parse arguments...
hlp_varargin2struct(varargin,{'params','Parameters'},{}, {'subset','Subset'},{}, {'dialogtitle','title','Title'}, [char(func) '()'], {'buttons','Buttons'},[]);
% obtain the argument specification for the function
rawspec = arg_report('rich', func, params); %#ok<*NODEF>
% extract a list of sub arguments...
[spec,subset] = obtain_items(rawspec,subset);
% create an inputgui() dialog...
geometry = repmat({[0.6 0.35]},1,length(spec)+length(buttons)/2);
geomvert = ones(1,length(spec)+length(buttons)/2);
% turn the spec into a UI list...
uilist = {};
for k = 1:length(spec)
s = spec{k};
if isempty(s)
uilist(end+1:end+2) = {{} {}};
else
if isempty(s.help)
error(['Cannot display the argument ' subset{k} ' because it contains no description.']);
else
tag = subset{k};
uilist{end+1} = {'Style','text', 'string',s.help{1}, 'fontweight','bold'};
% depending on the type, we introduce different types of input widgets here...
if iscell(s.range) && strcmp(s.type,'char')
% string popup menu
uilist{end+1} = {'Style','popupmenu', 'string',s.range,'value',find(strcmp(s.value,s.range)),'tag',tag};
elseif strcmp(s.type,'logical')
if length(s.range)>1
% multiselect
uilist{end+1} = {'Style','listbox', 'string',s.range, 'value',find(strcmp(s.value,s.range)),'tag',tag,'min',1,'max',100000};
geomvert(k) = min(3.5,length(s.range));
else
% checkbox
uilist{end+1} = {'Style','checkbox', 'string','(set)', 'value',double(s.value),'tag',tag};
end
elseif strcmp(s.type,'char')
% string edit
uilist{end+1} = {'Style','edit', 'string', s.value,'tag',tag};
else
% expression edit
if isinteger(s.value)
s.value = double(s.value); end
uilist{end+1} = {'Style','edit', 'string', hlp_tostring(s.value),'tag',tag};
end
% append the tooltip string
if length(s.help) > 1
uilist{end} = [uilist{end} 'tooltipstring', regexprep(s.help{2},'\.\s+(?=[A-Z])','.\n')]; end
end
end
if ~isempty(buttons) && k==buttons{1}
% render a command button
uilist(end+1:end+2) = {{} buttons{2}};
buttons(1:2) = [];
end
end
% invoke the GUI, obtaining a list of output values...
[outs,dummy,okpressed] = inputgui('geometry',geometry, 'uilist',uilist,'helpcom','disp(''coming soon...'')', 'title',dialogtitle,'geomvert',geomvert);
if ~isempty(okpressed)
% remove blanks from the spec
spec = spec(~cellfun('isempty',spec));
subset = subset(~cellfun('isempty',subset));
% turn the raw specification into a parameter struct (a non-direct one, since we will mess with it)
params = arg_tovals(rawspec,false);
% for each parameter produced by the GUI...
for k = 1:length(outs)
s = spec{k}; % current specifier
v = outs{k}; % current raw value
% do type conversion according to spec
if iscell(s.range) && strcmp(s.type,'char')
v = s.range{v};
elseif strcmp(s.type,'expression')
v = eval(v);
elseif strcmp(s.type,'logical')
if length(s.range)>1
v = s.range(v);
else
v = logical(v);
end
elseif strcmp(s.type,'char')
% noting to do
else
if ~isempty(v)
v = eval(v); % convert back to numeric (or object, or cell) value
end
end
% assign the converted value to params struct...
params = assign(params,subset{k},v);
end
% now send the result through the function to check for errors and obtain a values structure...
params = arg_report('rich',func,{params});
params = arg_tovals(params,false);
else
params = [];
end
% obtain a cell array of spec entries by name from the given specification
function [items,ids] = obtain_items(rawspec,requested,prefix)
if ~exist('prefix','var')
prefix = ''; end
items = {};
ids = {};
% determine what subset of (possibly nested) items is requested
if isempty(requested)
% look for a special argument/property arg_dialogsel, which defines the standard dialog representation for the given specification
dialog_sel = find(cellfun(@(x)any(strcmp(x,'arg_dialogsel')),{rawspec.names}));
if ~isempty(dialog_sel)
requested = rawspec(dialog_sel).value; end
end
if isempty(requested)
% empty means that all items are requested
for k=1:length(rawspec)
items{k} = rawspec(k);
ids{k} = [prefix rawspec(k).names{1}];
end
else
% otherwise we need to obtain those items
for k=1:length(requested)
if ~isempty(requested{k})
try
items{k} = obtain(rawspec,requested{k});
catch
error(['The specified identifier (' prefix requested{k} ') could not be found in the function''s declared arguments.']);
end
ids{k} = [prefix requested{k}];
end
end
end
% splice items that have children (recursively) into this list
for k = length(items):-1:1
% special case: switch arguments are not spliced, but instead the argument that defines the option popupmenu will be retained
if ~isempty(items{k}) && ~isempty(items{k}.children) && (~iscellstr(items{k}.range) || isempty(requested))
[subitems, subids] = obtain_items(items{k}.children,{},[ids{k} '.']);
if ~isempty(subitems)
% and introduce blank rows around them
items = [items(1:k-1) {{}} subitems {{}} items(k+1:end)];
ids = [ids(1:k-1) {{}} subids {{}} ids(k+1:end)];
end
end
end
% remove items that cannot be displayed
retain = cellfun(@(x)isempty(x)||x.displayable,items);
items = items(retain);
ids = ids(retain);
% remove double blank rows
empties = cellfun('isempty',ids);
items(empties(1:end-1) & empties(2:end)) = [];
ids(empties(1:end-1) & empties(2:end)) = [];
% obtain a spec entry by name from the given specification
function item = obtain(rawspec,identifier)
% parse the . notation
dot = find(identifier=='.',1);
if ~isempty(dot)
[head,rest] = deal(identifier(1:dot-1), identifier(dot+1:end));
else
head = identifier;
rest = [];
end
% search for the identifier at this level
names = {rawspec.names};
for k=1:length(names)
if any(strcmp(names{k},head))
% found a match!
if isempty(rest)
% return it
item = rawspec(k);
else
% obtain the rest of the identifier
item = obtain(rawspec(k).children,rest);
end
return;
end
end
error(['The given identifier (' head ') was not found among the function''s declared arguments.']);
% assign a field with dot notation in a struct
function s = assign(s,id,v)
% parse the . notation
dot = find(id=='.',1);
if ~isempty(dot)
[head,rest] = deal(id(1:dot-1), id(dot+1:end));
if ~isfield(s,head)
s.(head) = struct(); end
s.(head) = assign(s.(head),rest,v);
else
s.(id) = v;
end
|
github
|
lcnhappe/happe-master
|
invoke_arg_internal.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/invoke_arg_internal.m
| 4,456 |
utf_8
|
cde8b4f57b2bc16a8b03c45c255fe35d
|
function spec = invoke_arg_internal(reptype,varargin) %#ok<INUSL>
% same type of invoke function as in arg_sub, arg_subswitch, etc. - but shared between
% arg, arg_norep, and arg_nogui
spec = hlp_microcache('arg',@invoke_arg,varargin{:});
% the function that does the actual work of building the argument specifier
function spec = invoke_arg(names,default,range,help,varargin)
% start with a base specification
spec = arg_specifier('head',@arg);
% override properties
if exist('names','var')
spec.names = names; end
if exist('default','var')
spec.value = default; end
if exist('range','var')
spec.range = range; end
if exist('help','var')
spec.help = help; end
for k=1:2:length(varargin)
if isfield(spec,varargin{k})
spec.(varargin{k}) = varargin{k+1};
else
error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.');
end
end
% do fixups & checking
if ~iscell(spec.names)
spec.names = {spec.names}; end
if isempty(spec.names) || ~iscellstr(spec.names)
error('The argument must have a name or cell array of names.'); end
% parse the help
if ~isempty(spec.help)
try
spec.help = parse_help(spec.help);
catch e
disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]);
spec.help = {};
end
elseif spec.reportable && spec.displayable
disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']);
end
% do type inference
[spec.type,spec.shape,spec.range,spec.value] = infer_type(spec.type,spec.shape,spec.range,spec.value);
% infer the type & range of the argument, based on provided info (note: somewhat messy)
function [type,shape,range,value] = infer_type(type,shape,range,value)
try
if isempty(type)
% try to auto-discover the type (or leave empty, if impossible)
if ~isempty(value)
type = PropertyType.AutoDiscoverType(value);
elseif ~isempty(range)
if isnumeric(range)
type = PropertyType.AutoDiscoverType(range);
elseif iscell(range)
types = cellfun(@PropertyType.AutoDiscoverType,range,'UniformOutput',false);
if length(unique(types)) == 1
type = types{1}; end
end
end
end
if isempty(shape)
% try to auto-discover the shape
if ~isempty(value)
shape = PropertyType.AutoDiscoverShape(value);
elseif ~isempty(range)
if isnumeric(range)
shape = 'scalar';
elseif iscell(range)
shapes = cellfun(@PropertyType.AutoDiscoverShape,range,'UniformOutput',false);
if length(unique(shapes)) == 1
shape = shapes{1}; end
end
end
end
catch
end
% rule: if in doubt, fall back to denserealdouble and/or matrix
if isempty(type)
type = 'denserealdouble'; end
if isempty(shape)
shape = 'matrix'; end
% rule: if both the value and the range are cell-string arrays, the type is 'logical';
% this means that the value is a subset of the range
if iscellstr(value) && iscellstr(range)
type = 'logical'; end
% rule: if the value is empty, but the range is a cell-string array and the type is not 'logical',
% the value is the first range element; here, the value is exactly one out of the possible
% strings in range (and cannot be empty)
if isempty(value) && iscellstr(range) && ~strcmp(type,'logical')
value = range{1}; end
% rule: if the value is an empty char array, the shape is by default 'row'
if isequal(value,'') && ischar(value)
shape = 'row'; end
% rule: if the value is []; convert to the appropriate MATLAB type (e.g., int, etc.)
if isequal(value,[])
if strcmp(type,'cellstr')
value = {};
else
try
pt = PropertyType(type,shape,range);
value = pt.ConvertFromMatLab(value);
catch
end
end
end
% rule: if the value is a logical scalar and the type is logical, and the range is a cell-string
% array (i.e. a set of strings), the value is mapped to either the entire set or the empty set
% (i.e. either all elements are in, or none)
if isscalar(value) && islogical(value) && strcmp(type,'logical') && iscell(range)
if value
value = range;
else
value = {};
end
end
|
github
|
lcnhappe/happe-master
|
arg_report.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_report.m
| 6,925 |
utf_8
|
eb8f94b9fd0693dbde5cbfa2824b7e8d
|
function res = arg_report(type,func,args)
% Report information of a certain Type from the given Function.
% Result = arg_report(Type,Function,Arguments)
%
% Functions that declare their arguments via arg_define() make their parameter specification
% accessible to outside functions. This can be used to display auto-generated settings dialogs, to
% record function calls, and so on.
%
% Varying amounts of meta-data can be obtained in addition to the raw parameter values, including
% just the bare-bones value struct ('vals'), the meta-data associated with the passed arguments,
% and the full set of meta-data for all possible options (for multi-option parameters), even if these
% options were not actually prompted by the Arguments.
%
% In:
% Type : Type of information to report, can be one of the following:
% 'rich' : Report a rich declaration of the function's arguments as a struct array, with
% fields as in arg_specifier.
% 'lean' : Report a lean declaration of the function's arguments as a struct array, with
% fields as in arg_specifier, like rich, but excluding the alternatives field.
% 'vals' : Report the values of the function's arguments as a struct, possibly with
% sub-structs.
%
% 'properties' : Report properties of the function, if any (these can be declared via
% declare_properties)
%
% 'handle': Report function handles to scoped functions within the Function (i.e.,
% subfunctions). The named of those functions are listed as a cell string array
% in place of Arguments, unless there is exactly one returned function. Then,
% this function is returned as-is. This functionality is a nice-to-have feature
% for some use cases but not essential to the operation of the argument system.
%
% Function : a function handle to a function which defines some arguments (via arg_define)
%
% Arguments : cell array of parameters to be passed to the function; depending on the function's
% implementation, this can affect the current value assignment (or structure) of the
% parameters being returned If this is not a cell, it is automatically wrapped inside
% one (note: to specify the first positional argument as [] to the function, always
% pass it as {[]}; this is only relevant if the first argument's default is non-[]).
%
% Out:
% Result : the reported data.
%
% Notes:
% In all cases except 'properties', the Function must use arg_define() to define its arguments.
%
% Examples:
% % for a function call with some arguments assigned, obtain a struct with all parameter
% % names and values, including defaults
% params = arg_report('vals',@myfunction,{4,10,true,'option1','xxx','option5',10})
%
% % obtain a specification of all function arguments, with defaults, help text, type, shape, and other
% % meta-data (with a subset of settings customized according to arguments)
% spec = arg_report('rich',@myfunction,myarguments)
%
% % obtain a report of properties of the function (declared via declared_properties() within the
% % function)
% props = arg_report('properties',@myfunction)
%
% See also:
% arg_define, declare_properties
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-24
% uniformize arguments
if ~exist('args','var')
args = {}; end
if isequal(args,[])
args = {}; end
if ~iscell(args)
args = {args}; end
if ischar(func)
func = str2func(func); end
% make sure that the direct mode is disabled for the function being called (because in direct mode
% it doesn't report)
indices = find(cellfun('isclass',args,'struct') | strcmp(args,'arg_direct'));
for k = indices(end:-1:1)
if ischar(args{k}) && k<length(args)
% found it in the NVPs
args{k+1} = false;
break;
elseif isfield(args{k},'arg_direct')
% found it in a struct
args{k}.arg_direct = false;
break;
end
end
if any(strcmpi(type,{'rich','lean','vals','handle'}))
% issue the report
res = do_report(type,func,args);
elseif strcmpi(type,'properties')
if isempty(args)
% without arguments we can do a quick hash map lookup
% (based on the MD5 hash of the file in question)
info = functions(func);
hash = ['h' utl_fileinfo(info.file,char(func))];
try
% try lookup
persistent cached_properties; %#ok<TLEV>
res = cached_properties.(hash);
catch
% fall back to actually reporting it
res = do_report('properties',func,args);
% and store it for the next time
cached_properties.(hash) = res;
end
else
% with arguments we don't try to cache (as the properties might be argument-dependent)
res = do_report('properties',func,args);
end
end
function res = do_report(type,func,args)
global tracking;
persistent have_expeval;
if isempty(have_expeval)
have_expeval = exist('exp_eval','file'); end
try
% the presence of one of the arg_report_*** functions in the stack communicates to the receiver
% that a report is requested and what type of report...
feval(['arg_report_' lower(type)],func,args,have_expeval);
catch report
if strcmp(report.identifier,'BCILAB:arg:report_args')
% get the ticket of the report
ticket = sscanf(report.message((find(report.message=='=',1,'last')+1):end),'%f');
% read out the payload
res = tracking.arg_sys.reports{ticket};
% and return the ticket
tracking.arg_sys.tickets.addLast(ticket);
else
% other error:
if strcmp(type,'properties')
% almost certainly no properties clause defined
res = {};
else
% genuine error: pass it on
rethrow(report);
end
end
end
% --- a bit of boilerplate below (as the caller's name is relevant here) ---
function arg_report_rich(func,args,have_expeval) %#ok<DEFNU>
if have_expeval && nargout(func) > 0
exp_eval(func(args{:}));
else
func(args{:});
end
function arg_report_lean(func,args,have_expeval) %#ok<DEFNU>
if have_expeval && nargout(func) > 0
exp_eval(func(args{:}));
else
func(args{:});
end
function arg_report_vals(func,args,have_expeval) %#ok<DEFNU>
if have_expeval && nargout(func) > 0
exp_eval(func(args{:}));
else
func(args{:});
end
function arg_report_handle(func,args,have_expeval) %#ok<DEFNU>
if have_expeval && nargout(func) > 0
exp_eval(func(args{:}));
else
func(args{:});
end
function arg_report_properties(func,args,have_expeval) %#ok<DEFNU>
if have_expeval && nargout(func) > 0
exp_eval(func(args{:}));
else
func(args{:});
end
|
github
|
lcnhappe/happe-master
|
arg_subswitch.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_subswitch.m
| 17,047 |
utf_8
|
f8e71db07aba22fedb0dce863f122c40
|
function res = arg_subswitch(varargin)
% Specify a function argument that can be one of several alternative structs.
% Spec = arg_subswitch(Names,Defaults,Alternatives,Help,Options...)
%
% The correct struct is chosen according to a selection rule (the mapper). Accessible to the
% function as a struct, and visible in the GUI as an expandable sub-list of arguments (with a
% drop-down list of alternative options). The chosen option (usually one out of a set of strings) is
% delivered to the Function as the special struct field 'arg_selection'.
%
% In:
% Names : The name(s) of the argument. At least one must be specified, and if multiple are
% specified, they must be passed in a cell array.
% * The first name specified is the argument's "code" name, as it should appear in the
% function's code (= the name under which arg_define() returns it to the function).
% * The second name, if specified, is the "Human-readable" name, which is exposed in the
% GUIs (if omitted, the code name is displayed).
% * Further specified names are alternative names for the argument (e.g., for backwards
% compatibility with older function syntaxes/parameter names).
%
% Defaults : A cell array of arguments to override defaults for the Source (sources declared as
% part of Alternatives); all syntax accepted by the (selected) Source is allowed here,
% whereas in the case of positional arguments, the leading arg_norep() arguments of the
% source are implicitly skipped. Note: Which one out of the several alternatives should
% be selected is determined via the 'mapper' (which can be overridden in form of an
% optional parameter). By default, the mapper maps the first argument to the Selector,
% and assigns the rest to the matching Source.
%
% Alternatives : Definition of the switchable option groups. This is a cell array of the form:
% {{'selector', Source}, {'selector', Source}, {'selector', Source}, ...} Each
% Source is either a function handle (referring to a function that exposes
% arguments via an arg_define() clause), or an in-line cell array of argument
% specifications, analogously to the more detailed explanation in arg_sub(). In the
% latter case (Source is a cell array), the option group may also be a 3-element
% cell array of the form {'selector',Source,Format} ... where Format is a format
% specifier as explained in arg_define().
%
% Help : The help text for this argument (displayed inside GUIs), optional. (default: []).
% (Developers: Please do *not* omit this, as it is the key bridge between ease of use and
% advanced functionality.)
%
% The first sentence should be the executive summary (max. 60 chars), any further sentences
% are a detailed explanation (examples, units, considerations). The end of the first
% sentence is indicated by a '. ' followed by a capital letter (beginning of the next
% sentence). If ambiguous, the help can also be specified as a cell array of 2 cells.
%
% Options... : Optional name-value pairs to denote additional properties:
% 'cat' : The human-readable category of this argument, helpful to present a list
% of many parameters in a categorized list, and to separate "Core
% Parameters" from "Miscellaneous" arguments. Developers: When choosing
% names, every bit of consistency with other function in the toolbox helps
% the uses find their way (default: []).
%
% 'mapper' : A function that maps the value (cell array of arguments like Defaults)
% to a value in the domain of selectors (first output), and a potentially
% updated argument list (second output). The mapper is applied to the
% argument list prior to any parsing (i.e. it faces the raw argument
% list) to determine the current selection, and its second output (the
% potentially updated argument list) is forwarded to the Source that was
% selected, for further parsing.
%
% The default mapper takes the first argument in the argument list as the
% Selector and passes the remaining list entries to the Source. If there
% is only a single argument that is a struct with a field
% 'arg_selection', this field's value is taken as the Selector, and the
% struct is passed as-is to the Source.
%
% 'merge': Whether a value (cell array of arguments) assigned to this argument
% should completely replace all arguments of the default, or whether it
% should instead the two cell arrays should be concatenated ('merged'), so
% that defaults are only selectively overridden. Note that for
% concatenation to make sense, the cell array of Defaults cannot be some
% subset of all allowed positional arguments, but must instead either be
% the full set of positional arguments (and possibly some NVPs) or be
% specified as NVPs in the first place.
%
% Out:
% Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of
% the argument, for use by arg_define. Technical note: Upon assignment with a value (via
% the assigner field), the 'children' field of the specifier struct is populated according
% to how the selected (by the mapper) Source (from Alternatives) parses the value into
% arguments. The additional struct field 'arg_selection 'is introduced at this point.
%
% Examples:
% % define a function with a multiple-choice argument, with different sub-arguments for each choice
% % (where the default is 'kmeans'; some valid calls are:
% % myfunction('method','em','flagXY',true)
% % myfunction('flagXY',true, 'method',{'em', 'myarg',1001})
% % myfunction({'vb', 'myarg1',1001, 'myarg2','test'},false)
% % myfunction({'kmeans', struct('arg2','test')})
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subswitch('method','kmeans',{ ...
% {'kmeans', {arg('arg1',10,[],'argument for kmeans.'), arg('arg2','test',[],'another argument for it.')}, ...
% {'em', {arg('myarg',1000,[],'argument for the EM method.')}, ...
% {'vb', {arg('myarg1',test',[],'argument for the VB method.'), arg('myarg2','xyz',[],'another argument for VB.')} ...
% }, 'Method to use. Three methods are supported: k-means, EM and VB, and each method has optional parameters that can be specified if chosen.'), ...
% arg('flagXY',false,[],'And some flag.'));
%
% % define a function with a multiple-choice argument, where the arguments for the choices come
% % from a different function each
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subswitch('method','kmeans',{{'kmeans', @kmeans},{'em', @expectation_maximization},{'vb',@variational_bayes}}, 'Method to use. Each has optional parameters that can be specified if chosen.'), ...
% arg('flagXY',false,[],'And some flag.'));
%
% % as before, but specify a different default and override some of the arguments for that default
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subswitch('method',{'vb','myarg1','toast'},{{'kmeans', @kmeans},{'em', @expectation_maximization},{'vb',@variational_bayes}}, 'Method to use. Each has optional parameters that can be specified if chosen.'), ...
% arg('flagXY',false,[],'And some flag.'));
%
% % specify a custom function to determine the format of the argument (and in particular the
% % mapping of assigned value to chosen selection
% arg_subswitch('method','kmeans',{{'kmeans', @kmeans},{'em',@expectation_maximization},{'vb',@variational_bayes}}, ...
% 'Method to use. Each has optional parameters that can be specified if chosen.', 'mapper',@mymapper), ...
%
% See also:
% arg, arg_nogui, arg_norep, arg_sub, arg_subtoggle, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-24
% we return a function that an be invoked to yield a specification (its output is cached for
% efficiency) packed in a cell array together with the remaining arguments
res = {@invoke_argsubswitch_cached,varargin};
function spec = invoke_argsubswitch_cached(varargin)
spec = hlp_microcache('arg',@invoke_argsubswitch,varargin{:});
% the function that does the actual work of building the argument specifier
function spec = invoke_argsubswitch(reptype,names,defaults,alternatives,help,varargin)
suppressNames = {};
% start with a base specification
spec = arg_specifier('head',@arg_subswitch, 'type','char', 'shape','row', 'mapper',@map_argsubswitch);
% override properties
if exist('names','var')
spec.names = names; end
if exist('help','var')
spec.help = help; end
for k=1:2:length(varargin)
if isfield(spec,varargin{k})
spec.(varargin{k}) = varargin{k+1};
elseif strcmpi(varargin{k},'suppress')
suppressNames = varargin{k+1};
else
error(['BCILAB:arg:no_new_fields','It is not allowed to introduce fields (here: ' varargin{k} ') into a specifier that are not declared in arg_specifier.']);
end
end
% do checking
if ~iscell(spec.names)
spec.names = {spec.names}; end
if isempty(spec.names) || ~iscellstr(spec.names)
error('The argument must have a name or cell array of names.'); end
if isempty(alternatives)
error('BCILAB:args:no_options','The Alternatives argument for arg_subswitch() may not be omitted.'); end %#ok<*NODEF>
if nargin(spec.mapper) == 1
spec.mapper = @(x,y,z) spec.mapper(x); end
% parse the help
if ~isempty(spec.help)
try
spec.help = parse_help(spec.help,100);
catch e
disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]);
spec.help = {};
end
elseif spec.reportable && spec.displayable
disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']);
end
% uniformize Alternatives syntax into {{'selector1',@function1, ...}, {'selector2',@function2, ...}, ...}
if iscellstr(alternatives(1:2:end)) && all(cellfun(@(x)iscell(x)||isa(x,'function_handle'),alternatives(2:2:end)))
alternatives = mat2cell(alternatives,1,repmat(2,length(alternatives)/2,1)); end
% derive range
spec.range = cellfun(@(c)c{1},alternatives,'UniformOutput',false);
% turn Alternatives into a cell array of Source functions
for k=1:length(alternatives)
sel = alternatives{k};
selector = sel{1};
source = sel{2};
if ~ischar(selector)
error('In arg_subswitch, each selector must be a string.'); end
if length(sel) > 2
fmt = sel{3};
else
fmt = [];
end
% uniformize Source syntax...
if iscell(source)
% args is a cell array instead of a function: we effectively turn this into a regular
% arg_define-using function (taking & parsing values)
source = @(varargin) arg_define(fmt,varargin,source{:});
else
% args is a function: was a custom format specified?
if isa(fmt,'function_handle')
source = @(varargin) source(fmt(varargin));
elseif ~isempty(fmt)
error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)'); end
end
alternatives{k} = source;
end
sources = alternatives;
% wrap the defaults into a cell if necessary (note: this is convenience syntax)
if ~iscell(defaults)
if ~(isstruct(defaults) || ischar(defaults))
error(['It is not allowed to use anything other than a cell, a struct, or a (selector) string as default for an arg_subswitch argument (here:' spec.names{1} ')']); end
defaults = {defaults};
end
% find out what index and value set the default configuration maps to; this is relevant for the
% merging option: in this case, we need to pull up the correct default and merge it with the passed
% value
[default_sel,default_val] = spec.mapper(defaults,spec.range,spec.names);
default_idx = find(strcmp(default_sel,spec.range));
% create the regular assigner...
spec.assigner = @(spec,value) assign_argsubswitch(spec,value,reptype,sources,default_idx,default_val,suppressNames);
% and assign the default itself
if strcmp(reptype,'rich')
spec = assign_argsubswitch(spec,defaults,'build',sources,0,{},suppressNames);
else
spec = assign_argsubswitch(spec,defaults,'lean',sources,0,{},suppressNames);
end
function spec = assign_argsubswitch(spec,value,reptype,sources,default_idx,default_val,suppressNames)
% for convenience (in scripts calling the function), also support values that are not cell arrays
if ~iscell(value)
if ~(isstruct(value) || ischar(value))
error(['It is not allowed to assign anything other than a cell, a struct, or a (selector) string to an arg_subswitch argument (here:' spec.names{1} ')']); end
value = {value};
end
% run the mapper to get the selection according to the value (selectors is here for error checking);
% also update the value
[selection,value] = spec.mapper(value,spec.range,spec.names);
% find the appropriate index in the selections...
idx = find(strcmp(selection,spec.range));
% if we should build the set of alternatives, do so now....
if strcmp(reptype,'build')
for n=setdiff(1:length(sources),idx)
arg_sel = arg_nogui('arg_selection',spec.range{n});
spec.alternatives{n} = [arg_report('rich',sources{n}) arg_sel{1}([],arg_sel{2}{:})];
end
reptype = 'rich';
end
% build children and override the appropriate item in the aternatives
arg_sel = arg_nogui('arg_selection',spec.range{idx});
if spec.merge && idx == default_idx
spec.children = [arg_report(reptype,sources{idx},[default_val value]) arg_sel{1}([],arg_sel{2}{:})];
else
spec.children = [arg_report(reptype,sources{idx},value) arg_sel{1}([],arg_sel{2}{:})];
end
% toggle the displayable option for children which should be suppressed
if ~isempty(suppressNames)
% identify which children we want to suppress display
hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false)));
% set display flag to false
for k=hidden(:)'
spec.children(k).displayable = false;
end
% identify which alternatives we want to suppress display
for alt_idx = 1:length(spec.alternatives)
if isempty(spec.alternatives{alt_idx})
continue; end
hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.alternatives{alt_idx}.names},'UniformOutput',false)));
% set display flag to false
for k=hidden(:)'
spec.alternatives{alt_idx}(k).displayable = false;
end
end
end
spec.alternatives{idx} = spec.children;
% and set the value of the selector field itself to the current selection
spec.value = selection;
function [selection,args] = map_argsubswitch(args,selectors,names)
if isempty(args)
selection = selectors{1};
elseif isfield(args{1},'arg_selection')
selection = args{1}.arg_selection;
elseif any(strcmp(args{1},selectors))
[selection,args] = deal(args{1},args(2:end));
else
% find the arg_selection in the cell array
pos = find(strcmp('arg_selection',args(1:end-1)),1,'last');
[selection,args] = deal(args{pos+1},args([1:pos-1 pos+2:end]));
end
% Note: If this error is triggered, an value was passed for an argument which has a flexible structure (chosen out of a set of possibilities), but the possibility
% which was chosen according to the passed value does not match any of the specified ones. For a value that is a cell array of arguments, the choice is
% made based on the first element in the cell. For a value that is a structure of arguments, the choice is made based on the 'arg_selection' field.
% The error is usually resolved by reviewing the argument specification of the offending function carefully, and comparing the passed value to the Alternatives
% declared in the arg_subswitch() clause in which the offending argument is declared.
if ~any(strcmpi(selection,selectors))
error(['The chosen selector argument (' selection ') does not match any of the possible options (' sprintf('%s, ',selectors{1:end-1}) selectors{end} ') in the function argument ' names{1} '.']); end
|
github
|
lcnhappe/happe-master
|
arg_sub.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_sub.m
| 12,136 |
utf_8
|
579d06548d7bb9eba5580ea1d6d33322
|
function res = arg_sub(varargin)
% Specify an argument of a function which is a structure of sub-arguments.
% Spec = arg_sub(Names,Defaults,Source,Help,Options...)
%
% Delivered to the function as a struct, and visible in the GUI as a an expandable sub-list of
% arguments. A function may have an argument which itself consists of several arguments. For
% example, a function may be passing the contents of this struct as arguments to another function,
% or may just collect several arguments into sub-fields of a single struct. Differs from the default
% arg() function by allowing, instead of the Range, either a Source function which exposes a list of
% arguments (itself using arg_define), or a cell array with argument specifications, identical in
% format to the Specification part of an arg_define() clause.
%
% In:
% Names : The name(s) of the argument. At least one must be specified, and if multiple are
% specified, they must be passed in a cell array.
% * The first name specified is the argument's "code" name, as it should appear in the
% function's code (= the name under which arg_define() returns it to the function).
% * The second name, if specified, is the "Human-readable" name, which is exposed in the
% GUIs (if omitted, the code name is displayed).
% * Further specified names are alternative names for the argument (e.g., for backwards
% compatibility with older function syntaxes/parameter names).
%
% Defaults : A cell array of arguments to override defaults for the Source; all syntax accepted by
% the Source is allowed here, whereas in the case of positional arguments, the leading
% arg_norep() arguments of the source are implicitly skipped. If empty, the defaults of
% the Source are unaffected.
%
% Source : A source of argument specifications, usually a function handle (referring to a function
% which defines arguments via arg_define()).
%
% For convenience, a cell array with a list of argument declarations, formatted like the
% Specification part of an arg_define() clause can be given, instead. In this case, the
% effect is the same as specifying @some_function, for a function implemented as:
%
% function some_function(varargin) arg_define(Format,varargin,Source{:});
%
% Help : The help text for this argument (displayed inside GUIs), optional. (default: []).
% (Developers: Please do *not* omit this, as it is the key bridge between ease of use and
% advanced functionality.)
%
% The first sentence should be the executive summary (max. 60 chars), any further sentences
% are a detailed explanation (examples, units, considerations). The end of the first
% sentence is indicated by a '. ' followed by a capital letter (beginning of the next
% sentence). If ambiguous, the help can also be specified as a cell array of 2 cells.
%
% Options... : Optional name-value pairs to denote additional properties:
% 'cat' : The human-readable category of this argument, helpful to present a list
% of many parameters in a categorized list, and to separate "Core
% Parameters" from "Miscellaneous" arguments. Developers: When choosing
% names, every bit of consistency with other function in the toolbox helps
% the uses find their way (default: []).
%
% 'fmt' : Optional format specification for the Source (if it is a cell array)
% (default: []). See arg_define() for a detailed explanation.
%
% 'merge': Whether a value (cell array of arguments) assigned to this argument
% should completely replace all arguments of the default, or whether
% instead the two cell arrays should be concatenated ('merged'), so that
% defaults are only selectively overridden. Note that for concatenation to
% make sense, the cell array of Defaults cannot be some subset of all
% allowed positional arguments, but must instead either be the full set of
% positional arguments (and possibly some NVPs) or be specified as NVPs in
% the first place. (default: true)
%
% Out:
% Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of
% the argument, for use by arg_define. Technical note: Upon assignment with a value (via
% the assigner field), the 'children' field of the specifier struct is populated according
% to how the Source parses the value into arguments.
%
% Notes:
% for MATLAB versions older than 2008a, type and shape checking is not necessarily enforced.
%
% Examples:
% % define 3 arguments for a function, including one which is a struct of two other arguments.
% % some valid calls to the function are:
% % myfunction('somearg',false, 'anotherarg',10, 'structarg',{'myarg1',5,'myarg2','xyz'})
% % myfunction(false, 10, {'myarg1',5,'myarg2','xyz'})
% % myfunction('structarg',{'myarg2','xyz'}, 'somearg',false)
% % myfunction('structarg',struct('myarg2','xyz','myarg1',10), 'somearg',false)
% function myfunction(varargin)
% arg_define(varargin, ...
% arg('somearg',true,[],'Some argument.'),...
% arg_sub('structarg',{},{ ...
% arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ...
% arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.')
% }, 'Struct argument. This argument has sub-structure. It can generally be assigned a cell array of name-value pairs, or a struct.'), ...
% arg('anotherarg',5,[],'Another argument. This is a regular numeric argument of myfunction again.));
%
% % define a struct argument with some overridden defaults
% arg_sub('structarg',{'myarg2','toast'},{ ...
% arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ...
% arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.')
% }, 'Struct argument. This argument has sub-structure. It can generally be assigned a cell array of name-value pairs, or a struct.'), ...
%
% % define an arguments including one whose sub-parameters match those that are declared in some
% % other function (@myotherfunction), which uses arg_define itself
% function myfunction(varargin)
% arg_define(varargin, ...
% arg('somearg',[],[],'Some help text.'), ...
% arg_sub('structarg',{},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction(), can be assigned as a cell array of name-value pairs or structs.'));
%
% % define an argument with sub-parameters sourced from some other function, but with partially overridden defaults
% arg_sub('structarg',{'myarg1',1001},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction(), can be assigned as a cell array of name-value pairs or structs.'));
%
% % define an argument with sub-parameters sourced from some other function, with a particular set of custom defaults
% % which are jointly replaced when a value is assigned to structarg (including an empty cell array)
% arg_sub('structarg',{'myarg1',1001},@myotherfunction, 'A struct argument. Arguments are as in myotherfunction().', 'merge',false));
%
% % define a struct argument with a custom formatting function (analogously to the optional Format function in arg_define)
% % myparser shall be a function that takes a string and returns a cell array of name-value pairs (names compatible to the sub-argument names)
% arg_sub('structarg',{},{ ...
% arg('myarg1',4,[],'Some sub-argument. This is a sub-argument of the argument named structarg in the function'), ...
% arg('myarg2','test',[],'Another sub-argument. This, too, is a sub-argument of structarg.')
% }, 'Struct argument. This argument has sub-structure. Assign it as a string of the form ''name=value; name=value;''.', 'fmt',@myparser), ...
%
% See also:
% arg, arg_nogui, arg_norep, arg_subswitch, arg_subtoggle, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-24
% we return a function that an be invoked to yield a specification (its output is cached for
% efficiency) packed in a cell array together with the remaining arguments
res = {@invoke_argsub_cached,varargin};
function spec = invoke_argsub_cached(varargin)
spec = hlp_microcache('arg',@invoke_argsub,varargin{:});
% the function that does the actual work of building the argument specifier
function spec = invoke_argsub(reptype,names,defaults,source,help,varargin)
% start with a base specification
spec = arg_specifier('head',@arg_sub,'fmt',[], 'value','', 'type','char', 'shape','row');
suppressNames = {};
% override properties
if exist('names','var')
spec.names = names; end
if exist('help','var')
spec.help = help; end
for k=1:2:length(varargin)
if isfield(spec,varargin{k})
spec.(varargin{k}) = varargin{k+1};
elseif strcmpi(varargin{k},'suppress')
suppressNames = varargin{k+1};
else
error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.');
end
end
% do checking
if ~iscell(spec.names)
spec.names = {spec.names}; end
if isempty(spec.names) || ~iscellstr(spec.names)
error('The argument must have a name or cell array of names.'); end
if ~exist('source','var') || isequal(source,[])
error('BCILAB:args:no_source','The Source argument for arg_sub() may not be omitted.'); end %#ok<*NODEF>
% parse the help
if ~isempty(spec.help)
try
spec.help = parse_help(spec.help,100);
catch e
disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]);
spec.help = {};
end
elseif spec.reportable && spec.displayable
disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']);
end
if ~isempty(source)
% uniformize Source syntax
if iscell(source)
% args is a cell array instead of a function: we effectively turn this into a regular
% arg_define-using function (taking & parsing values)
source = @(varargin) arg_define(spec.fmt,varargin,source{:});
else
% args is a function: was a custom format specified?
if isa(spec.fmt,'function_handle')
source = @(varargin) source(spec.fmt(varargin));
elseif ~isempty(spec.fmt)
error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)');
end
end
end
spec = rmfield(spec,'fmt');
% assignment to this object does not touch the value, but instead creates a new children structure
spec.assigner = @(spec,value) assign_argsub(spec,value,reptype,source,defaults,suppressNames);
% assign the default
spec = assign_argsub(spec,defaults,reptype,source,[],suppressNames);
% function to do the value assignment
function spec = assign_argsub(spec,value,reptype,source,default,suppressNames)
if ~isempty(source)
if spec.merge
spec.children = arg_report(reptype,source,[default,value]);
else
spec.children = arg_report(reptype,source,value);
end
end
% toggle the displayable option for children which should be suppressed
if ~isempty(suppressNames)
% identify which children we want to suppress display
hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false)));
% set display flag to false
for k=hidden(:)'
spec.children(k).displayable = false;
end
end
|
github
|
lcnhappe/happe-master
|
arg_subtoggle.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_subtoggle.m
| 15,337 |
utf_8
|
6bfc9dc025de4ebf873f2152b77f7ee4
|
function res = arg_subtoggle(varargin)
% Specify an argument of a function which is a struct of sub-arguments that can be disabled.
% Spec = arg_subtoggle(Names,Default,Source,Help,Options...)
%
% Accessible to the function as a struct, and visible in the GUI as a an expandable sub-list of
% arguments (with a checkbox to toggle). The special field 'arg_selection' (true/false) indicates
% whether the argument is enabled or not. The value assigned to the argument determines whether it
% is turned on or off, as determined by the mapper option.
%
% In:
% Names : The name(s) of the argument. At least one must be specified, and if multiple are
% specified, they must be passed in a cell array.
% * The first name specified is the argument's "code" name, as it should appear in the
% function's code (= the name under which arg_define() returns it to the function).
% * The second name, if specified, is the "Human-readable" name, which is exposed in the
% GUIs (if omitted, the code name is displayed).
% * Further specified names are alternative names for the argument (e.g., for backwards
% compatibility with older function syntaxes/parameter names).
%
% Defaults : A cell array of arguments to override defaults for the Source; all syntax accepted by
% the (selected) Source is allowed here, whereas in the case of positional arguments,
% the leading arg_norep() arguments of the source are implicitly skipped. Note: Whether
% the argument is turned on or off is determined via the 'mapper' option. By default,
% [] and 'off' are mapped to off, whereas {}, non-empty cell arrays and structs are
% mapped to on.
%
% Source : A source of argument specifications, usually a function handle (referring to a function
% which defines arguments via arg_define()).
%
% For convenience, a cell array with a list of argument declarations, formatted like the
% Specification part of an arg_define() clause can be given, instead. In this case, the
% effect is the same as specifying @some_function, for a function implemented as:
%
% function some_function(varargin) arg_define(Format,varargin,Source{:});
%
% Help : The help text for this argument (displayed inside GUIs), optional. (default: []).
% (Developers: Please do *not* omit this, as it is the key bridge between ease of use and
% advanced functionality.)
%
% The first sentence should be the executive summary (max. 60 chars), any further sentences
% are a detailed explanation (examples, units, considerations). The end of the first
% sentence is indicated by a '. ' followed by a capital letter (beginning of the next
% sentence). If ambiguous, the help can also be specified as a cell array of 2 cells.
%
% Options... : Optional name-value pairs to denote additional properties:
% 'cat' : The human-readable category of this argument, helpful to present a list
% of many parameters in a categorized list, and to separate
% "Core Parameters" from "Miscellaneous" arguments. Developers: When
% choosing names, every bit of consistency with other function in the
% toolbox helps the uses find their way (default: []).
%
% 'fmt' : Optional format specification for the Source (if it is a cell array)
% (default: []). See arg_define() for a detailed explanation.
%
% 'mapper' : A function that maps the argument list (e.g., Defaults) to a value in
% the domain of selectors, and a potentially updated argument list. The
% mapper is applied to the argument list prior to any parsing (i.e. it
% faces the raw argument list) to determine the current selection, and
% its its second output (the potentially updated argument list) is
% forwarded to the Source that was selected, for further parsing.
%
% The default mapper maps [] and 'off' to off, whereas 'on', empty or
% non-empty cell arrays and structs are mapped to on.
%
% 'merge': Whether a value (cell array of arguments) assigned to this argument
% should completely replace all arguments of the default, or whether it
% should instead the two cell arrays should be concatenated ('merged'), so
% that defaults are only selectively overridden. Note that for
% concatenation to make sense, the cell array of Defaults cannot be some
% subset of all allowed positional arguments, but must instead either be
% the full set of positional arguments (and possibly some NVPs) or be
% specified as NVPs in the first place.
%
%
% Out:
% Spec : A cell array, that, when called as spec{1}(reptype,spec{2}{:}), yields a specification of
% the argument, for use by arg_define. Technical note: Upon assignment with a value (via
% the assigner field), the 'children' field of the specifier struct is populated according
% to how the selected (by the mapper) Source parses the value into arguments. The
% additional struct field 'arg_selection 'is introduced at this point.
%
% Examples:
% % define a function with an argument that can be turned on or off, and which has sub-arguments
% % that are effective if the argument is turned on (default: on); some valid calls are:
% % myfunction('somearg','testtest', 'myoption','off')
% % myfunction('somearg','testtest', 'myoption',[]) % alternative for: off
% % myfunction('somearg','testtest', 'myoption','on')
% % myfunction('somearg','testtest', 'myoption',{}) % alternatie for: on
% % myfunction('somearg','testtest', 'myoption',{'param1','test','param2',10})
% % myfunction('somearg','testtest', 'myoption',{'param2',10})
% % myfunction('testtest', {'param2',10})
% % myfunction('myoption', {'param2',10})
% function myfunction(varargin)
% arg_define(varargin, ...
% arg('somearg','test',[],'Some help.'), ...
% arg_subtoggle('myoption',},{},{ ...
% arg('param1',[],[],'Parameter 1.'), ...
% arg('param2',5,[],'Parameter 2.') ...
% }, 'Optional processing step. If selected, several sub-argument can be specified.'));
%
% % define a function with an argument that can be turned on or off, and whose sub-arguments match
% % those of some other function (there declared via arg_define)
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'));
%
% % as before, but override some of the defaults of someotherfunction
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subtoggle('myoption',},{'param1',10},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'));
%
% % as before, but specify a custom mapper function that determines how myoption is passed, and
% % what forms map to 'on' and 'off'
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'.'mapper',@mymapper));
%
% % as before, but specify a custom formatting function that determines the arguments in myoption
% % may be passed (keeping the defaults regarding what forms map to 'on' and 'off')
% function myfunction(varargin)
% arg_define(varargin, ...
% arg_subtoggle('myoption',},{},@someotherfunction, 'Optional processing step. If selected, several sub-argument can be specified.'.'fmt',@myparser));
%
% See also:
% arg, arg_nogui, arg_norep, arg_sub, arg_subswitch, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-24
% we return a function that an be invoked to yield a specification (its output is cached for
% efficiency) packed in a cell array together with the remaining arguments
res = {@invoke_argsubtoggle_cached,varargin};
function spec = invoke_argsubtoggle_cached(varargin)
spec = hlp_microcache('arg',@invoke_argsubtoggle,varargin{:});
% the function that does the actual work of building the argument specifier
function spec = invoke_argsubtoggle(reptype,names,defaults,source,help,varargin)
% start with a base specification
spec = arg_specifier('head',@arg_subtoggle, 'fmt',[], 'type','logical', 'shape','scalar', 'mapper',@map_argsubtoggle);
suppressNames = {};
% override properties
if exist('names','var')
spec.names = names; end
if exist('help','var')
spec.help = help; end
for k=1:2:length(varargin)
if isfield(spec,varargin{k})
spec.(varargin{k}) = varargin{k+1};
elseif strcmpi(varargin{k},'suppress')
suppressNames = varargin{k+1};
else
error('BCILAB:arg:no_new_fields','It is not allowed to introduce fields into a specifier that are not declared in arg_specifier.');
end
end
% do checking
if ~iscell(spec.names)
spec.names = {spec.names}; end
if isempty(spec.names) || ~iscellstr(spec.names)
error('The argument must have a name or cell array of names.'); end
if ~exist('source','var') || isempty(source)
error('BCILAB:args:no_options','The Source argument for arg_subtoggle() may not be omitted.'); end %#ok<*NODEF>
if nargin(spec.mapper) == 1
spec.mapper = @(x,y,z) spec.mapper(x); end
% parse the help
if ~isempty(spec.help)
try
spec.help = parse_help(spec.help,100);
catch e
disp(['Problem with the help text for argument ' spec.names{1} ': ' e.message]);
spec.help = {};
end
elseif spec.reportable && spec.displayable
disp(['Please specify a description for argument ' spec.names{1} ', or specify it via arg_nogui() instead.']);
end
% uniformize Source syntax
if iscell(source)
% args is a cell array instead of a function: we effectively turn this into a regular
% arg_define-using function (taking & parsing values)
source = @(varargin) arg_define(spec.fmt,varargin,source{:});
else
% args is a function: was a custom format specified?
if isa(spec.fmt,'function_handle')
source = @(varargin) source(spec.fmt(varargin));
elseif ~isempty(spec.fmt)
error('The only allowed form in which the Format of a Source that is a function may be overridden is as a pre-parser (given as a function handle)');
end
end
spec = rmfield(spec,'fmt');
% wrap the default into a cell if necessary (note: this is convenience syntax)
if isstruct(defaults)
defaults = {defaults};
elseif strcmp(defaults,'off')
defaults = [];
elseif strcmp(defaults,'on')
defaults = {};
elseif ~iscell(defaults) && ~isequal(defaults,[])
error(['It is not allowed to use anything other than a cell array, a struct, [] or ''off'' and ''on'' as defaults of an arg_subtoggle argument (here:' spec.names{1} ')']);
end
% resolve the default configuration into the boolean flag and value set; this is relevant for
% the merging option: in this case, we need to pull up the currect default and merge it with the
% passed value
[default_sel,default_val] = spec.mapper(defaults);
% set up the regular assigner
spec.assigner = @(spec,value) assign_argsubtoggle(spec,value,reptype,source,default_sel,default_val,suppressNames);
% assign the default
if strcmp(reptype,'rich')
spec = assign_argsubtoggle(spec,defaults,'build',source,NaN,{},suppressNames);
else
spec = assign_argsubtoggle(spec,defaults,'lean',source,NaN,{},suppressNames);
end
function spec = assign_argsubtoggle(spec,value,reptype,source,default_sel,default_val,suppressNames)
% precompute things that we might need later
persistent arg_sel arg_desel;
if isempty(arg_sel) || isempty(arg_sel)
arg_sel = arg_nogui('arg_selection',true); arg_sel = arg_sel{1}([],arg_sel{2}{:});
arg_desel = arg_nogui('arg_selection',false); arg_desel = arg_desel{1}([],arg_desel{2}{:});
end
% wrap the value into a cell if necessary (note: this is convenience syntax)
if isstruct(value)
value = {value};
elseif ~iscell(value) && ~isequal(value,[]) && ~isempty(default_val)
error(['For an arg_subtoggle argument that has non-empty defaults (here:' spec.names{1} '), it is not allowed to assign anything other than a cell array, a struct, or [] to it.']);
end
% retrieve the values for the realized switch option...
[selected,value] = spec.mapper(value);
% build the complementary alternative, if requested
if strcmp(reptype,'build')
if selected
spec.alternatives{1} = arg_desel;
else
spec.alternatives{2} = [arg_report('rich',source,{}) arg_sel];
end
reptype = 'rich';
end
% obtain the children
if ~selected
spec.children = arg_desel;
elseif spec.merge && (default_sel==true)
spec.children = [arg_report(reptype,source,[default_val value]) arg_sel];
else
spec.children = [arg_report(reptype,source,value) arg_sel];
end
% toggle the displayable option for children which should be suppressed
if ~isempty(suppressNames)
% identify which children we want to suppress display
hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.children.names},'UniformOutput',false)));
% set display flag to false
for k=hidden(:)'
spec.children(k).displayable = false;
end
% identify which alternatives we want to suppress display
for alt_idx = 1:length(spec.alternatives)
if isempty(spec.alternatives{alt_idx})
continue; end
hidden = find(cellfun(@any,cellfun(@(x,y) ismember(x,suppressNames),{spec.alternatives{alt_idx}.names},'UniformOutput',false)));
% set display flag to false
for k=hidden(:)'
spec.alternatives{alt_idx}(k).displayable = false;
end
end
end
spec.alternatives{selected+1} = spec.children;
% and set the cell's value
spec.value = selected;
% this function maps an argument list onto a binary flag (enabled status) plus value set to assign
function [selected,args] = map_argsubtoggle(args)
if isequal(args,'on')
selected = true;
args = {};
elseif isequal(args,'off') || isequal(args,[])
selected = false;
args = [];
elseif length(args) == 1 && isfield(args,'arg_selection')
selected = args.arg_selection;
elseif length(args) == 1 && iscell(args) && isstruct(args{1}) && isfield(args{1},'arg_selection')
selected = args{1}.arg_selection;
elseif isequal(args,{'arg_selection',0})
selected = false;
args = {};
elseif isequal(args,{'arg_selection',1})
selected = true;
args = {};
elseif iscell(args)
% find the arg_selection in the cell array
pos = find(strcmp('arg_selection',args(1:end-1)),1,'last');
if isempty(pos)
selected = true;
else
[selected,args] = deal(args{pos+1},args([1:pos-1 pos+2:end]));
end
else
selected = true;
end
|
github
|
lcnhappe/happe-master
|
arg_tovals.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_tovals.m
| 2,531 |
utf_8
|
d6b62007b294e20f330fd415633ef2ad
|
function res = arg_tovals(spec,direct)
% Convert a 'rich' argument report into a 'vals' report.
% Vals = arg_tovals(Rich)
%
% In:
% Rich : a 'rich' argument report, as obtained via arg_report('rich',some_function)
%
% Direct : whether to endow the result with an 'arg_direct' flag set to true, which indicates to
% the function taking the Vals struct that the contents of the struct directly correspond
% to workspace variables of the function. If enabled, contents of Vals must be changed
% with care - for example, removing/renaming fields will likely lead to errors in the
% function. (default: true)
%
% Out:
% Vals : a 'vals' argument report, as obtained via arg_report('vals',some_function) this data
% structure can be used as a valid argument to some_function.
%
% Examples:
% % report arguments of myfunction
% report = arg_report('rich',@myfunction)
% % convert the report to a valid argument to the function
% values = arg_tovals(report);
%
% See also:
% arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-18
if ~exist('direct','var')
direct = false; end
% remove unassigned specifiers
spec = spec(~strcmp(unassigned,{spec.value}));
% evaluate expressions
expressions = strcmp('expression',{spec.type}) & cellfun('isclass',{spec.value},'char');
if any(expressions)
try
[spec(expressions).value] = dealout(evalin('base',format_cellstr({spec(expressions).value})));
catch
for e=find(expressions)
try
spec(e).value = evalin('base',spec(e).value);
catch
end
end
end
end
% and replace by structs
res = struct('arg_direct',{direct});
for k=1:length(spec)
if isstruct(spec(k).children)
% has children: replace by struct
val = arg_tovals(spec(k).children,direct);
else
% no children: take value (and possibly convert to double)
val = spec(k).value;
if spec(k).to_double && isinteger(val)
val = double(val); end
end
% and assign the value
res.(spec(k).names{1}) = val;
end
res.arg_direct = direct;
% like deal(), except that the inputs are given as a cell array instead of a comma-separated list
function varargout = dealout(argin)
varargout = argin;
% format a non-empty cell-string array into a string
function x = format_cellstr(x)
x = ['{' sprintf('%s, ',x{1:end-1}) x{end} '}'];
|
github
|
lcnhappe/happe-master
|
arg_specifier.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/arguments/arg_specifier.m
| 2,714 |
utf_8
|
45a0f0bbe159b1d73d533fcbbf4c2576
|
function spec = arg_specifier(varargin)
% Internal: create a base specifier struct for an argument.
% Specifier = arg_specifier(Overrides...)
%
% In:
% Overrides... : name-value pairs of fields that should be overridden
%
% Out:
% A specifier that is recognized by arg_define.
%
% See also:
% arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-09-25
spec = struct(...
... % core properties
'head',{@arg_specifier},...% the expression type that generated this specifier (@arg, @arg_sub, ...)
'names',{{}}, ... % cell array of argument names; first is the "code" name (reported to the function), second (if present) is the human-readable name (reported to the GUI)
'value',{[]}, ... % the assigned value of the argument; can be any data structure
'assigner',{@assign},...% function to be invoked in order to assign a new value the specifier
... % properties for (possibly dependent) child arguments
'children',{{}}, ... % cell array of child arguments (returned to the function in a struct, and made available to the GUI in a subgroup)
'mapper',@(x)x, ... % mapping function: maps a value into the index space of alternatives (possibly via range)
'alternatives',{{}}, ...% cell array of alternative children structures; only used for arg_subtoggle, arg_subswitch
'merge',{true},... % whether the value (a cell array of arguments) should completely replace the default, or be merged with it, such that sub-arguments are only selectively overridden
... % type-related properties
'range',{[]}, ... % the allowed range of the argument (for type checking in GUI and elsewhere); can be [], [lo hi], {'option1','option2','option3',...}
'type',{[]}, ... % the type of the argument: string, only touches the type-checking system & GUI
'shape',{[]}, ... % the shape of the argument: empty. scalar, row, column, matrix
... % user interface properties
'help',{''}, ... % the help text / description for the argument
'cat',{''}, ... % the human-readable category of the argument
... % misc attributes
'to_double',{true}, ... % convert numeric values to double before returning them to the function
'reportable',{true},... % whether the argument can be reported to outer function (given that it is assigned), or not (true/false)
'displayable',{true}... % whether the argument may be displayed by GUIs (true/false)
);
% selectively override fields
for k=1:2:length(varargin)
spec.(varargin{k}) = varargin{k+1}; end
function spec = assign(spec,value)
spec.value = value;
|
github
|
lcnhappe/happe-master
|
is_needing_search.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/queries/is_needing_search.m
| 808 |
utf_8
|
b4e0ea02b09d80b71d7e2970b648578f
|
function res = is_needing_search(argform,args)
% test whether some argument pack requires a search or not (according to the specified argument format)
if strcmp(argform,'direct')
% a search is specified by multielement arguments
res = prod(max(1,cellfun(@length,args))) > 1;
elseif strcmp(argform,'clauses')
% a search is specified by (possibly nested) search clauses
res = contains_search(args);
else
error('unsupported argument form.');
end
% test whether the given data structure contains a search clause
function res = contains_search(x)
if has_canonical_representation(x) && isequal(x.head,@search)
res = true;
elseif iscell(x)
res = any(cellfun(@contains_search,x));
elseif isstruct(x) && numel(x) == 1
res = contains_search(struct2cell(x));
else
res = false;
end
|
github
|
lcnhappe/happe-master
|
is_raw_dataset.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/bcilab_partial/queries/is_raw_dataset.m
| 184 |
utf_8
|
6bcaef74ea534a299898aa10b68af85a
|
% determine whether some object is a raw EEGLAB data set with no BCILAB constituents
function res = is_raw_dataset(x)
res = all(isfield(x,{'data','srate'})) && ~isfield(x,'tracking');
|
github
|
lcnhappe/happe-master
|
shadowplot.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/tmullen-cleanline-696a7181b7d0/external/shadowplot/shadowplot.m
| 7,604 |
utf_8
|
ae6097ee1343157565bb24e6a5f27a32
|
function varargout = shadowplot(varargin)
% SHADOWPLOT Add a shadow to an existing surface or patch plot
%
% For some surface plots, it can be helpful to visualize the shadow (2D
% projection) of the surface. This can give a quick perspective on the
% data's variance.
%
% SHADOWPLOT PLANE Adds a shadow plot on the PLANE boundary
% PLANE can be:
% x, y, or z: Plots on back/top wall of x, y or z
% 1 .. 6 : Plots on Nth wall, numbered as in AXIS:
% [xmin xmax ymin ymax zmin zmax]
%
% SHADOWPLOT(HAX,PLANE) Adds a shadow plot on the Nth wall on axes HAX
% HS = SHADOWPLOT(...) Returns a handle to the shadow (a patch)
%
% Examples:
% figure
% surf(peaks)
% shading interp
% shadowplot x % Back X Wall
% shadowplot y % Back Y Wall
%
% figure
% surf(peaks);hold on
% surf(peaks+10)
% shading interp
% hs = shadowplot(1);
% set(hs,'FaceColor','r'); % Red shadow
% alpha(hs,.1) % More transparent
% set(hs(1),'XData',get(hs(1),'XData')*.9) % Move farther away
%
% UPDATE (9/07): Now includes limited support for data encapsulated in
% HGTRANSFORMS, thanks to Patrick Barney ([email protected]).
% Scott Hirsch
% [email protected]
% Copyright 2004-2007 The MathWorks, Inc
%% We define three dimensions. 1=x, 2=y, 3=z
% dimplane - dimension that's constant in the projection plane (user-specified)
% dimvar - dimension in which data varies (typically 3)
% dimother - the other dimension (couldn't come up with a good name!).
%% Parse input arguments.
if nargin==1
hAx = gca;
plane = lower(varargin{1});
elseif nargin==2
hAx = varargin{1};
plane = lower(varargin{2});
end;
%% Convert plane to numeric dimension
% plane can be specified as a string (x,y,z) or as a number (1..6)
if ~isstr(plane)
dimplane = ceil(plane/2);
axind = plane; % Index into AXIS to get boundary plane
else % string
switch plane
case 'x'
dimplane = 1;
axind = 2; % Index into AXIS to get boundary plane
case 'y'
dimplane = 2;
axind = 4;
case 'z'
dimplane = 3;
axind = 6;
otherwise
error('Plane must be one of: ''x'', ''y'', or ''z'' or a number between 1 and 6');
end;
end;
%% Get coordinates for placing surface from axis limits
ax = axis;
% ============ force axis into 3d mode =============
if length(axis==4)
% axis problem. get the current view, rotate it, then
% redo the axis and return to the original view.
[az,el] = view;
view(45,45)
ax = axis;
view(az,el)
end
planecoord = ax(axind); % Plane Coordinate - back wall
%% Turn hold on
hold_current = ishold(hAx);
if hold_current == 0
hold_current = 'off';
else
hold_current = 'on';
end;
hold(hAx,'on')
%% Get handles to all surfaces
kids = findobj(hAx,'Type','surface');
h = [];
% Also get handles to all patch objects
kidsp = findobj(hAx,'Type','patch');
hp = [];
for ii=1:length(kids) % Do separately for each surface
hSurf = kids(ii); % Current surface
% We do everything with the X, Y, and ZData of the surface
surfdata = get(hSurf,{'XData','YData','ZData'});
% XData and YData might be vectors or matrices. Force them to be
% matrices (a la griddata)
[Ny,Nx] = size(surfdata{3});
if isvector(surfdata{1})
surfdata{1} = repmat(surfdata{1},Ny,1);
end;
if isvector(surfdata{2})
surfdata{2} = repmat(surfdata{2},1,Nx);
end;
% Figure out which two axes are independent (i.e., monotonic)
grids = [ismeshgrid(surfdata{1}) ismeshgrid(surfdata{2}) ismeshgrid(surfdata{3})];
if sum(grids)<2, error('Surface must have at least 2 monotonically increasing dimensions');end
% The remaining dimension is the one along which data varies
dimvar = find(~grids); % Dimension where data varies
if isempty(dimvar) % All 3 dimensions are monotonic. not sure what to do
dimvar = max(setdiff(1:3,dimplane));% pick largest value that isn't dimplane
end;
if dimvar==dimplane
error('Can not project data in the dimension that varies. Try another plane')
end;
%dimdiff: dimension for taking difference (figure out through trial and error)
% dimplane=1, dimvar=3: 2
% dimplane=1, dimvar=2: 2
% dimplane=2, dimvar=1: 2
% dimplane=2, dimvar=3: 1
% dimplane=3, dimvar=2: 1
% dimplane=3, dimvar=1: 1
dimdiff = 2; % Most cases
if (dimplane==2&&dimvar==3) | (dimplane==3)
dimdiff = 1;
end;
% Compute projection
dmin = min(surfdata{dimvar},[],dimdiff); % Min of data projected onto this plane
dmax = max(surfdata{dimvar},[],dimdiff); % Max of data projected onto this plane
dmin = dmin(:); % Force into row vector
dmax = dmax(:);
nval = length(dmin)*2 + 1; % Total number of values we'll use for shadow
% Compute shadow coordinates
% Pull out independent variable
dimother = setxor([dimvar dimplane],1:3); % Remaining dimension
d1 = surfdata{dimother}(:,1); % Not sure if should take row or col. find the dimension that varies
d2 = surfdata{dimother}(1,:);
if d1(1) ~= d1(end)
dind = d1;
else
dind = d2';
end;
shadow{dimplane} = repmat(planecoord,nval,1); % In the plane
shadow{dimother} = [dind;flipud(dind);dind(1)]; % Independent variable
shadow{dimvar} = [dmin;flipud(dmax);dmin(1)]; % the varying data
h(ii) = patch(shadow{1},shadow{2},shadow{3},[.3 .3 .3]);
alpha(h(ii),.3)
set(h(ii),'LineStyle','none')
% set a tag, so that a shadow will not try to cast a shadow
set(h(ii),'Tag','Shadow')
end;
%% Shadow any patches, unless they are already shadows.
hp = [];
for ii=1:length(kidsp) % Do separately for each patch object
hPat = kidsp(ii); % Current patch
% Is this patch already tagged as a Shadow?
if ~strcmpi(get(hPat,'Tag'),'Shadow')
% We do everything with the X, Y, and ZData of the surface
patdata = get(hPat,{'XData','YData','ZData'});
switch get(get(hPat,'par'),'Type')
case 'hgtransform'
M=get(get(hPat,'par'),'Matrix');
try
switch get(get(get(hPat,'par'),'par'),'type')
case 'hgtransform'
M2=get(get(get(hPat,'par'),'par'),'Matrix');
M=M2*M;
end
end
M=M(1:3,1:3);
xyz=[patdata{1}(:),patdata{2}(:),patdata{3}(:)]*M';
[n,m]=size(patdata{1});
patdata{1}=reshape(xyz(:,1),n,m);
patdata{2}=reshape(xyz(:,2),n,m);
patdata{3}=reshape(xyz(:,3),n,m);
otherwise
end
% Just replace the x, y, or z coordinate as indicated by dimplane
patdata{dimplane} = repmat(planecoord,size(patdata{dimplane}));
% then its just a call to patch
hp(ii) = patch(patdata{1},patdata{2},patdata{3},[.3 .3 .3]);
alpha(hp(ii),.3)
set(hp(ii),'LineStyle','none')
% set a tag, so that a shadow will not try to cast a shadow
set(hp(ii),'Tag','Shadow')
end
end;
h=[h,hp];
hold(hAx,hold_current) % Return to original state
if nargout
varargout{1} = h;
end;
function isgrid = ismeshgrid(d)
% Check if d looks like it came from griddata
dd = diff(d);
ddt = diff(d');
if all(~dd(:)) | all(~ddt(:))
isgrid = 1;
else
isgrid = 0;
end;
% if ~any(d(:,1) - d(:,end)) | ~any(d(1,:) - d(end,:))
% isgrid = 1;
% else
% isgrid = 0;
% end;
|
github
|
lcnhappe/happe-master
|
eegplugin_MARA.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/eegplugin_MARA.m
| 2,770 |
utf_8
|
7619f29fb825e45ca839265d7d4046e0
|
% eegplugin_MARA() - EEGLab plugin to classify artifactual ICs based on
% 6 features from the time domain, the frequency domain,
% and the pattern
%
% Inputs:
% fig - [integer] EEGLAB figure
% try_strings - [struct] "try" strings for menu callbacks.
% catch_strings - [struct] "catch" strings for menu callbacks.
%
% See also: pop_processMARA(), processMARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function eegplugin_MARA( fig, try_strings, catch_strings)
toolsmenu = findobj(fig, 'tag', 'tools');
h = uimenu(toolsmenu, 'label', 'IC Artifact Classification (MARA)');
uimenu(h, 'label', 'MARA Classification', 'callback', ...
[try_strings.no_check ...
'[ALLEEG,EEG,CURRENTSET,LASTCOM]= pop_processMARA( ALLEEG ,EEG ,CURRENTSET );' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'Visualize Components', 'tag', 'MARAviz', 'Enable', ...
'off', 'callback', [try_strings.no_check ...
'EEG = pop_selectcomps_MARA(EEG); pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo); ' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'About', 'Separator', 'on', 'Callback', ...
['warndlg2(sprintf([''MARA automatizes the process of hand-labeling independent components for ', ...
'artifact rejection. It is a supervised machine learning algorithm that learns from ', ...
'expert ratings of 1290 components. Features were optimized to solve the binary classification problem ', ...
'reject vs. accept.\n \n', ...
'If you have questions or suggestions about the toolbox, please contact \n ', ...
'Irene Winkler, TU Berlin [email protected] \n \n ', ...
'Reference: \nI. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual', ...
'ICA-components for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.''])', ...
',''About MARA'');']);
|
github
|
lcnhappe/happe-master
|
pop_visualizeMARAfeatures.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/pop_visualizeMARAfeatures.m
| 4,558 |
utf_8
|
c888a9b58c7e7893d090883d152d5e09
|
% pop_visualizeMARAfeatures() - Display features that MARA's decision
% for artifact rejection is based on
%
% Usage:
% >> pop_visualizeMARAfeatures(gcompreject, MARAinfo);
%
% Inputs:
% gcompreject - array <1 x nIC> containing 1 if component was rejected
% MARAinfo - struct containing more information about MARA classification
% (output of function <MARA>)
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact according to
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% See also: MARA(), processMARA(), pop_selectcomps_MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function pop_visualizeMARAfeatures(gcompreject, MARAinfo)
%try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings.rowsize = 200;
panelsettings.columnsize = 200;
panelsettings.columns = floor(width/(2*panelsettings.columnsize));
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.columns * panelsettings.rows;
panelsettings.pages = ceil(length(gcompreject)/ panelsettings.numberPerPage);
% display components on a number of different pages
for page=1:panelsettings.pages
selectcomps_1page(page, panelsettings, gcompreject, MARAinfo);
end;
%catch
% eeglab_error
%end
function EEG = selectcomps_1page(page, panelsettings, gcompreject, MARAinfo)
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', 'Visualize MARA features', 'numbertitle', 'off');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.columns panelsettings.rowsize*panelsettings.rows]);
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : length(gcompreject);
end
% draw each component
% %%%%%%%%%%%%%%%%
for i = 1:length(range)
subplot(panelsettings.rows, panelsettings.columns, i)
for j = 1:6
h = barh(j, MARAinfo.normfeats(j, range(i)));
hold on;
if j <= 4 && MARAinfo.normfeats(j, range(i)) > 0
set(h, 'FaceColor', [0.4 0 0]);
end
if j > 4 && MARAinfo.normfeats(j, range(i)) < 0
set(h, 'FaceColor', [0.4 0 0]);
end
end
axis square;
if mod(i, panelsettings.columns) == 1
set(gca,'YTick', 1:6, 'YTickLabel', {'Current Density Norm', ...
'Range in Pattern', 'Local Skewness', 'lambda', '8-13Hz', 'FitError'})
else
set(gca,'YTick', 1:6, 'YTickLabel', cell(1,6))
end
if gcompreject(range(i)) == 1
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))),...
'Color', [0.4 0 0]);
set(gca, 'Color', [1 0.7 0.7])
%keyboard
else
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))));
end
end
|
github
|
lcnhappe/happe-master
|
processMARA.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/processMARA.m
| 6,510 |
utf_8
|
896a41c6475ec80bf7706cc7166ce7a8
|
% processMARA() - Processing for Automatic Artifact Classification with MARA.
% processMARA() calls MACA and saves the identified artifactual components
% in EEG.reject.gcompreject.
% The functions optionally filters the data, runs ICA, plots components or
% reject artifactual components immediately.
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,options)
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Optional Input:
% options - 1x5 array specifing optional operations, default is [0,0,0,0,0]
% - option(1) = 1 => filter the data before MARA classification
% - option(2) = 1 => run ica before MARA classification
% - option(3) = 1 => plot components to label them for rejection after MARA classification
% (for rejection)
% - option(4) = 1 => plot MARA features for each IC
% - option(4) = 1 => automatically reject MARA's artifactual
% components without inspecting them
%
% See also: pop_eegfilt(), pop_runica, MARA(), pop_selectcomps_MARA(), pop_subcomp
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,varargin)
if isempty(EEG.chanlocs)
try
error('No channel locations. Aborting MARA.')
catch
eeglab_error;
return;
end
end
if not(isempty(varargin))
options = varargin{1};
else
options = [0 0 0 0 0];
end
%% filter the data
if options(1) == 1
disp('Filtering data');
[EEG, LASTCOM] = pop_eegfilt(EEG);
eegh(LASTCOM);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% run ica
if options(2) == 1
disp('Run ICA');
[EEG, LASTCOM] = pop_runica(EEG);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% check if ica components are present
[EEG LASTCOM] = eeg_checkset(EEG, 'ica');
if LASTCOM < 0
disp('There are no ICA components present. Aborting classification.');
return
else
eegh(LASTCOM);
end
%% classify artifactual components with MARA
[artcomps, MARAinfo] = MARA(EEG);
EEG.reject.MARAinfo = MARAinfo;
disp('MARA marked the following components for rejection: ')
if isempty(artcomps)
disp('None')
else
disp(artcomps)
disp(' ')
end
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
else % if gcompreject present check whether labels differ from MARA
if and(length(EEG.reject.gcompreject) == size(EEG.icawinv,2), ...
not(isempty(find(EEG.reject.gcompreject))))
tmp = zeros(1,size(EEG.icawinv,2));
tmp(artcomps) = 1;
if not(isequal(tmp, EEG.reject.gcompreject))
answer = questdlg(...
'Some components are already labeled for rejection. What do you want to do?',...
'Labels already present','Merge artifactual labels','Overwrite old labels', 'Cancel','Cancel');
switch answer,
case 'Overwrite old labels',
gcompreject_old = EEG.reject.gcompreject;
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
disp('Overwrites old labels')
case 'Merge artifactual labels'
disp('Merges MARA''s and old labels')
gcompreject_old = EEG.reject.gcompreject;
case 'Cancel',
return;
end
else
gcompreject_old = EEG.reject.gcompreject;
end
else
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
end
end
EEG.reject.gcompreject(artcomps) = 1;
try
EEGLABfig = findall(0, 'tag', 'EEGLAB');
MARAvizmenu = findobj(EEGLABfig, 'tag', 'MARAviz');
set(MARAvizmenu, 'Enable', 'on');
catch
keyboard
end
%% display components with checkbox to label them for artifact rejection
if options(3) == 1
if isempty(artcomps)
answer = questdlg2(...
'MARA identied no artifacts. Do you still want to visualize components?',...
'No artifacts identified','Yes', 'No', 'No');
if strcmp(answer,'No')
return;
end
end
[EEG, LASTCOM] = pop_selectcomps_MARA(EEG, gcompreject_old);
eegh(LASTCOM);
if options(4) == 1
pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo);
end
end
%% automatically remove artifacts
if and(and(options(5) == 1, not(options(3) == 1)), not(isempty(artcomps)))
try
[EEG LASTCOM] = pop_subcomp(EEG);
eegh(LASTCOM);
catch
eeglab_error
end
[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
disp('Artifact rejection done.');
end
|
github
|
lcnhappe/happe-master
|
MARA.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/MARA.m
| 12,568 |
utf_8
|
5127d8f931932b5c0760a9a61a0d0b6e
|
% MARA() - Automatic classification of multiple artifact components
% Classies artifactual ICs based on 6 features from the time domain,
% the frequency domain, and the pattern
%
% Usage:
% >> [artcomps, info] = MARA(EEG);
%
% Inputs:
% EEG - input EEG structure
%
% Outputs:
% artcomps - array containing the numbers of the artifactual
% components
% info - struct containing more information about MARA classification
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% For more information see:
% I. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual ICA-components
% for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.
%
% See also: processMARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [artcomps, info] = MARA(EEG)
try
%%%%%%%%%%%%%%%%%%%%
%% Calculate features from the pattern (component map)
%%%%%%%%%%%%%%%%%%%%
% extract channel labels
clab = {};
for i=1:length(EEG.chanlocs)
clab{i} = EEG.chanlocs(i).labels;
end
% cut to channel labels common with training data
load('fv_training_MARA'); %load struct fv_tr
[clab_common i_te i_tr ] = intersect(upper(clab), upper(fv_tr.clab));
clab_common = fv_tr.clab(i_tr);
if length(clab_common) == 0
error(['There were no matching channeldescriptions found.' , ...
'MARA needs channel labels of the form Cz, Oz, F3, F4, Fz, etc. Aborting.'])
end
patterns = (EEG.icawinv(i_te,:));
[M100 idx] = get_M100_ADE(clab_common); %needed for Current Density Norm
disp('MARA is computing features. Please wait');
%standardize patterns
patterns = patterns./repmat(std(patterns,0,1),length(patterns(:,1)),1);
%compute current density norm
feats(1,:) = log(sqrt(sum((M100*patterns(idx,:)).^2)));
%compute spatial range
feats(2,:) = log(max(patterns) - min(patterns));
%%%%%%%%%%%%%%%%%%%%
%% Calculate time and frequency features
%%%%%%%%%%%%%%%%%%%%
%compute time and frequency features (Current Density Norm, Range Within Pattern,
%Average Local Skewness, Band Power 8 - 13 Hz)
feats(3:6,:) = extract_time_freq_features(EEG);
disp('Features ready');
%%%%%%%%%%%%%%%%%%%%%%
%% Adapt train features to clab
%%%%%%%%%%%%%%%%%%%%
fv_tr.pattern = fv_tr.pattern(i_tr, :);
fv_tr.pattern = fv_tr.pattern./repmat(std(fv_tr.pattern,0,1),length(fv_tr.pattern(:,1)),1);
fv_tr.x(2,:) = log(max(fv_tr.pattern) - min(fv_tr.pattern));
fv_tr.x(1,:) = log(sqrt(sum((M100 * fv_tr.pattern).^2)));
%%%%%%%%%%%%%%%%%%%%
%% Classification
%%%%%%%%%%%%%%%%%%%%
[C, foo, posterior] = classify(feats',fv_tr.x',fv_tr.labels(1,:));
artcomps = find(C == 0)';
info.posterior_artefactprob = posterior(:, 1)';
info.normfeats = (feats - repmat(mean(fv_tr.x, 2), 1, size(feats, 2)))./ ...
repmat(std(fv_tr.x,0, 2), 1, size(feats, 2));
catch
eeglab_error;
artcomps = [];
end
end
function features = extract_time_freq_features(EEG)
% - 1st row: Average Local Skewness
% - 2nd row: lambda
% - 3rd row: Band Power 8 - 13 Hz
% - 4rd row: Fit Error
%
data = EEG.data;
fs = EEG.srate; %sampling frequency
% transform epoched data into continous data
if length(size(data)) == 3
s = size(data);
data = reshape(data, [EEG.nbchan, prod(s(2:3))]);
end
%downsample (to 100-200Hz)
factor = max(floor(EEG.srate/100),1);
data = data(:, 1:factor:end);
fs = round(fs/factor);
%compute icaactivation and standardise variance to 1
icacomps = (EEG.icaweights * EEG.icasphere * data)';
icacomps = icacomps./repmat(std(icacomps,0,1),length(icacomps(:,1)),1);
icacomps = icacomps';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate featues
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for ic=1:length(icacomps(:,1)) %for each component
fprintf('.');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Proc Spectrum for Channel
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[pxx, freq] = pwelch(icacomps(ic,:), ones(1, fs), [], fs, fs);
pxx = 10*log10(pxx * fs/2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The average log band power between 8 and 13 Hz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p = 0;
for i = 8:13
p = p + pxx(find(freq == i,1));
end
Hz8_13 = p / (13-8+1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% lambda and FitError: deviation of a component's spectrum from
% a protoptypical 1/frequency curve
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1.x = 2; %first point: value at 2 Hz
p1.y = pxx(find(freq == p1.x,1));
p2.x = 3; %second point: value at 3 Hz
p2.y = pxx(find(freq == p2.x,1));
%third point: local minimum in the band 5-13 Hz
p3.y = min(pxx(find(freq == 5,1):find(freq == 13,1)));
p3.x = freq(find(pxx == p3.y,1));
%fourth point: min - 1 in band 5-13 Hz
p4.x = p3.x - 1;
p4.y = pxx(find(freq == p4.x,1));
%fifth point: local minimum in the band 33-39 Hz
p5.y = min(pxx(find(freq == 33,1):find(freq == 39,1)));
p5.x = freq(find(pxx == p5.y,1));
%sixth point: min + 1 in band 33-39 Hz
p6.x = p5.x + 1;
p6.y = pxx(find(freq == p6.x,1));
pX = [p1.x; p2.x; p3.x; p4.x; p5.x; p6.x];
pY = [p1.y; p2.y; p3.y; p4.y; p5.y; p6.y];
myfun = @(x,xdata)(exp(x(1))./ xdata.^exp(x(2))) - x(3);
xstart = [4, -2, 54];
try
fittedmodel = lsqcurvefit(myfun,xstart,double(pX),double(pY), [], [], optimset('Display', 'off'));
catch
try
% If the optimization toolbox is missing we try with the CurveFit toolbox
opt = fitoptions('Method','NonlinearLeastSquares','Startpoint',xstart);
myfun = fittype('exp(x1)./x.^exp(x2) - x3;','options',opt);
fitobject = fit(double(pX),double(pY),myfun);
fittedmodel = [fitobject.x1, fitobject.x2, fitobject.x3];
catch
% If the CurveFit toolbox is also missing we try with the Statistitcs toolbox
myfun = @(p,xdata)(exp(p(1))./ xdata.^exp(p(2))) - p(3);
mdl = NonLinearModel.fit(double(pX),double(pY),myfun,xstart);
fittedmodel = mdl.Coefficients.Estimate(:)';
end
end
%FitError: mean squared error of the fit to the real spectrum in the band 2-40 Hz.
ts_8to15 = freq(find(freq == 8) : find(freq == 15));
fs_8to15 = pxx(find(freq == 8) : find(freq == 15));
fiterror = log(norm(myfun(fittedmodel, ts_8to15)-fs_8to15)^2);
%lambda: parameter of the fit
lambda = fittedmodel(2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Averaged local skewness 15s
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = 15;
abs_local_scewness = [];
for i=1:interval:length(icacomps(ic,:))/fs-interval
abs_local_scewness = [abs_local_scewness, abs(skewness(icacomps(ic, i * fs:(i+interval) * fs)))];
end
if isempty(abs_local_scewness)
error('MARA needs at least 15ms long ICs to compute its features.')
else
mean_abs_local_scewness_15 = log(mean(abs_local_scewness));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Append Features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
features(:,ic)= [mean_abs_local_scewness_15, lambda, Hz8_13, fiterror];
end
disp('.');
end
function [M100, idx_clab_desired] = get_M100_ADE(clab_desired)
% [M100, idx_clab_desired] = get_M100_ADEC(clab_desired)
%
% IN clab_desired - channel setup for which M100 should be calculated
% OUT M100
% idx_clab_desired
% M100 is the matrix such that feature = norm(M100*ica_pattern(idx_clab_desired), 'fro')
%
% (c) Stefan Haufe
lambda = 100;
load inv_matrix_icbm152; %L (forward matrix 115 x 2124 x 3), clab (channel labels)
[cl_ ia idx_clab_desired] = intersect(clab, clab_desired);
F = L(ia, :, :); %forward matrix for desired channels labels
[n_channels m foo] = size(F); %m = 2124, number of dipole locations
F = reshape(F, n_channels, 3*m);
%H - matrix that centralizes the pattern, i.e. mean(H*pattern) = 0
H = eye(n_channels) - ones(n_channels, n_channels)./ n_channels;
%W - inverse of the depth compensation matrix Lambda
W = sloreta_invweights(L);
L = H*F*W;
%We have inv(L'L +lambda eye(size(L'*L))* L' = L'*inv(L*L' + lambda
%eye(size(L*L')), which is easier to calculate as number of dimensions is
%much smaller
%calulate the inverse of L*L' + lambda * eye(size(L*L')
[U D] = eig(L*L');
d = diag(D);
di = d+lambda;
di = 1./di;
di(d < 1e-10) = 0;
inv1 = U*diag(di)*U'; %inv1 = inv(L*L' + lambda *eye(size(L*L'))
%get M100
M100 = L'*inv1*H;
end
function W = sloreta_invweights(LL)
% inverse sLORETA-based weighting
%
% Synopsis:
% W = sloreta_invweights(LL);
%
% Arguments:
% LL: [M N 3] leadfield tensor
%
% Returns:
% W: [3*N 3*N] block-diagonal matrix of weights
%
% Stefan Haufe, 2007, 2008
%
% License
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see http://www.gnu.org/licenses/.
[M N NDUM]=size(LL);
L=reshape(permute(LL, [1 3 2]), M, N*NDUM);
L = L - repmat(mean(L, 1), M, 1);
T = L'*pinv(L*L');
W = spalloc(N*NDUM, N*NDUM, N*NDUM*NDUM);
for ivox = 1:N
W(NDUM*(ivox-1)+(1:NDUM), NDUM*(ivox-1)+(1:NDUM)) = (T(NDUM*(ivox-1)+(1:NDUM), :)*L(:, NDUM*(ivox-1)+(1:NDUM)))^-.5;
end
ind = [];
for idum = 1:NDUM
ind = [ind idum:NDUM:N*NDUM];
end
W = W(ind, ind);
end
function [i_te, i_tr] = findconvertedlabels(pos_3d, chanlocs)
% IN pos_3d - 3d-positions of training channel labels
% chanlocs - EEG.chanlocs structure of data to be classified
%compute spherical coordinates theta and phi for the training channel
%label
[theta, phi, r] = cart2sph(pos_3d(1,:),pos_3d(2,:), pos_3d(3,:));
theta = theta - pi/2;
theta(theta < -pi) = theta(theta < -pi) + 2*pi;
theta = theta*180/pi;
phi = phi * 180/pi;
theta(find(pos_3d(1,:) == 0 & pos_3d(2,:) == 0)) = 0; %exception for Cz
clab_common = {};
i_te = [];
i_tr = [];
%For each channel in EEG.chanlocs, try to find matching channel in
%training data
for chan = 1:length(chanlocs)
if not(isempty(chanlocs(chan).sph_phi))
idx = find((theta <= chanlocs(chan).sph_theta + 6) ...
& (theta >= chanlocs(chan).sph_theta - 6) ...
& (phi <= chanlocs(chan).sph_phi + 6) ...
& (phi >= chanlocs(chan).sph_phi - 6));
if not(isempty(idx))
i_tr = [i_tr, idx(1)];
i_te = [i_te, chan];
end
end
end
end
|
github
|
lcnhappe/happe-master
|
pop_selectcomps_MARA.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/pop_selectcomps_MARA.m
| 7,617 |
utf_8
|
3df13de5291a735a3ae902eb9b7b4349
|
% pop_selectcomps_MARA() - Display components with checkbox to label
% them for artifact rejection
%
% Usage:
% >> EEG = pop_selectcomps_MARA(EEG, gcompreject_old);
%
% Inputs:
% EEG - Input dataset with rejected components (saved in
% EEG.reject.gcompreject)
%
% Optional Input:
% gcompreject_old - gcompreject to revert to in case the "Cancel"
% button is pressed
%
% Output:
% EEG - Output dataset with updated rejected components
%
% See also: processMARA(), pop_selectcomps()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_selectcomps_MARA(EEG, varargin)
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(size(EEG.icawinv,2));
end
if not(isempty(varargin))
gcompreject_old = varargin{1};
com = [ 'pop_selectcomps_MARA(' inputname(1) ',' inputname(2) ');'];
else
gcompreject_old = EEG.reject.gcompreject;
com = [ 'pop_selectcomps_MARA(' inputname(1) ');'];
end
try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings = {};
panelsettings.completeNumber = length(EEG.reject.gcompreject);
panelsettings.rowsize = 250;
panelsettings.columnsize = 300;
panelsettings.column = floor(width/panelsettings.columnsize);
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.column * panelsettings.rows;
panelsettings.pages = ceil(length(EEG.reject.gcompreject)/ panelsettings.numberPerPage);
panelsettings.incy = 110;
panelsettings.incx = 110;
% display components on a number of different pages
for page=1:panelsettings.pages
EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old);
end;
checks = findall(0, 'style', 'checkbox');
for i = 1: length(checks)
set(checks(i), 'Enable', 'on')
end
catch
eeglab_error
end
function EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old)
% Display components with checkbox to label them for artifact rejection
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% compute components (for plotting the spectrum)
if length(size(EEG.data)) == 3
s = size(EEG.data);
data = reshape(EEG.data, [EEG.nbchan, prod(s(2:3))]);
icacomps = EEG.icaweights * EEG.icasphere * data;
else
icacomps = EEG.icaweights * EEG.icasphere * EEG.data;
end
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', [ 'MARA on dataset: ' EEG.setname ''], 'numbertitle', 'off', 'tag', 'ADEC - Plot');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.column panelsettings.rowsize*panelsettings.rows]);
panelsettings.sizewx = 50/panelsettings.column;
panelsettings.sizewy = 80/panelsettings.rows;
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
panelsettings.q = [pos(1) pos(2) 0 0];
panelsettings.s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : panelsettings.completeNumber;
end
data = struct;
data.gcompreject = EEG.reject.gcompreject;
data.gcompreject_old = gcompreject_old;
guidata(gcf, data);
% draw each component
% %%%%%%%%%%%%%%%%
count = 1;
for ri = range
% compute coordinates
X = mod(count-1, panelsettings.column)/panelsettings.column * panelsettings.incx-10;
Y = (panelsettings.rows-floor((count-1)/panelsettings.column))/panelsettings.rows * panelsettings.incy - panelsettings.sizewy*1.3;
% plot the head
if ~strcmp(get(gcf, 'tag'), 'ADEC - Plot');
disp('Aborting plot');
return;
end;
ha = axes('Units','Normalized', 'Position',[X Y panelsettings.sizewx*0.85 panelsettings.sizewy*0.85].*panelsettings.s+panelsettings.q);
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', 'off', 'style' , 'fill');
axis square;
% plot the spectrum
ha = axes('Units','Normalized', 'Position',[X+1.05*panelsettings.sizewx Y-1 (panelsettings.sizewx*1.15)-1 panelsettings.sizewy-1].*panelsettings.s+panelsettings.q);
[pxx, freq] = pwelch(icacomps(ri,:), ones(1, EEG.srate), [], EEG.srate, EEG.srate);
pxx = 10*log10(pxx * EEG.srate/2);
plot(freq, pxx, 'LineWidth', 2)
xlim([0 50]);
grid on;
xlabel('Hz')
set(gca, 'Xtick', 0:10:50)
if isfield(EEG.reject, 'MARAinfo')
title(sprintf('Artifact Probability = %1.2f', ...
EEG.reject.MARAinfo.posterior_artefactprob(ri)));
end
uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[X+panelsettings.sizewx*0.5 Y+panelsettings.sizewy panelsettings.sizewx, ...
panelsettings.sizewy*0.2].*panelsettings.s+panelsettings.q, ...
'Enable', 'off','tag', ['check_' num2str(ri)], 'Value', EEG.reject.gcompreject(ri), ...
'String', ['IC' num2str(ri) ' - Artifact?'], ...
'Callback', {@callback_checkbox, ri});
drawnow;
count = count +1;
end;
% draw the botton buttons
% %%%%%%%%%%%%%%%%
if ~exist('fig')
% cancel button
cancelcommand = ['openplots = findall(0, ''tag'', ''ADEC - Plot'');', ...
'data = guidata(openplots(1)); close(openplots);', ...
'EEG.reject.gcompreject = data.gcompreject_old;'];
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[-10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', cancelcommand );
okcommand = ['data = guidata(gcf); EEG.reject.gcompreject = data.gcompreject; ' ...
'[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); '...
'eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); '...
'close(gcf);' ];
% ok button
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', okcommand);
end;
function callback_checkbox(hObject,eventdata, position)
openplots = findall(0, 'tag', 'ADEC - Plot');
data = guidata(openplots(1));
data.gcompreject(position) = mod(data.gcompreject(position) + 1, 2);
%save changes in every plot
for i = 1: length(openplots)
guidata(openplots(i), data);
end
|
github
|
lcnhappe/happe-master
|
pop_processMARA.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/MARA-master/pop_processMARA.m
| 5,095 |
utf_8
|
7932742793cce3ca7b8caeb78ae22d82
|
% pop_processMARA() - graphical interface to select MARA's actions
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA(ALLEEG,EEG,CURRENTSET );
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Output:
% com - last command, call to itself
%
% See also: processMARA(), pop_selectcomps_MARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA (ALLEEG,EEG,CURRENTSET )
com = 'pop_processMARA ( ALLEEG,EEG,CURRENTSET )';
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%%
figure('name', 'MARA', ...
'numbertitle', 'off', 'tag', 'ADEC - Init');
set(gcf,'MenuBar', 'none', 'Color', BACKCOLOR);
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) 350 350 350]);
if ~strcmp(get(gcf, 'tag'), 'ADEC - Init');
disp('Aborting plot');
return;
end;
% set standards for options and store them with guidata()
% order: filter, run_ica, plot data, remove automatically
options = [0, 0, 0, 0, 0];
guidata(gcf, options);
% text
% %%%%%%%%%%%%%%%%%
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.85 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'Select preprocessing operations:');
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.55 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'After MARA classification:');
% checkboxes
% %%%%%%%%%%%%%%%%%
filterBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.75 0.75 0.075], 'String', 'Filter the data', 'Callback', ...
'options = guidata(gcf); options(1) = mod(options(1) + 1, 2); guidata(gcf,options);');
icaBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.65 0.75 0.075], 'String', 'Run ICA', 'Callback', ...
'options = guidata(gcf); options(2) = mod(options(2) + 1, 2); guidata(gcf,options);');
% radio button group
% %%%%%%%%%%%%%%%%%
vizBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.2 0.2 0.9 0.2], 'String', 'Visualize Classifcation Features', 'Enable', 'Off', ...
'tag', 'vizBox');
h = uibuttongroup('visible','off','Units','Normalized','Position',[0.075 0.15 0.9 0.35]);
% Create two radio buttons in the button group.
radNothing = uicontrol('Style','radiobutton','String','Continue using EEGLab functions',...
'Units','Normalized','Position',[0.02 0.8 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radNothing');
radPlot = uicontrol('Style','radiobutton','String','Plot and select components for removal',...
'Units','Normalized','Position',[0.02 0.5 0.9 0.2],'parent',h,'HandleVisibility','off',...
'tag', 'radPlot');
radAuto = uicontrol('Style','radiobutton','String','Automatically remove components',...
'Units','Normalized','Position',[0.02 0.1 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radAuto');
set(h,'SelectedObject',radNothing,'Visible','on', 'tag', 'h','BackGroundColor', BACKCOLOR);
set(h, 'SelectionChangeFcn',['s = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; ' ...
'set(s.vizBox,''Enable'', ''on''); else; set(s.vizBox,''Enable'', ''off''); end;']);
% bottom buttons
% %%%%%%%%%%%%%%%%%
cancel = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.075 0.05 0.4 0.08],'String', 'Cancel','BackgroundColor', GUIBUTTONCOLOR,...
'Callback', 'close(gcf);');
ok = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.5 0.05 0.4 0.08],'String', 'Ok','BackgroundColor', GUIBUTTONCOLOR, ...
'Callback', ['options = guidata(gcf);' ...
's = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; options(3) = 1; end; '...
'options(4) = get(s.vizBox, ''Value''); ' ...
'if get(s.h, ''SelectedObject'') == s.radAuto; options(5) = 1; end;' ...
'close(gcf); pause(eps); [ALLEEG, EEG, CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET, options);']);
|
github
|
lcnhappe/happe-master
|
eegplugin_MARA.m
|
.m
|
happe-master/Packages/MARA-master/eegplugin_MARA.m
| 2,770 |
utf_8
|
7619f29fb825e45ca839265d7d4046e0
|
% eegplugin_MARA() - EEGLab plugin to classify artifactual ICs based on
% 6 features from the time domain, the frequency domain,
% and the pattern
%
% Inputs:
% fig - [integer] EEGLAB figure
% try_strings - [struct] "try" strings for menu callbacks.
% catch_strings - [struct] "catch" strings for menu callbacks.
%
% See also: pop_processMARA(), processMARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function eegplugin_MARA( fig, try_strings, catch_strings)
toolsmenu = findobj(fig, 'tag', 'tools');
h = uimenu(toolsmenu, 'label', 'IC Artifact Classification (MARA)');
uimenu(h, 'label', 'MARA Classification', 'callback', ...
[try_strings.no_check ...
'[ALLEEG,EEG,CURRENTSET,LASTCOM]= pop_processMARA( ALLEEG ,EEG ,CURRENTSET );' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'Visualize Components', 'tag', 'MARAviz', 'Enable', ...
'off', 'callback', [try_strings.no_check ...
'EEG = pop_selectcomps_MARA(EEG); pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo); ' ...
catch_strings.add_to_hist ]);
uimenu(h, 'label', 'About', 'Separator', 'on', 'Callback', ...
['warndlg2(sprintf([''MARA automatizes the process of hand-labeling independent components for ', ...
'artifact rejection. It is a supervised machine learning algorithm that learns from ', ...
'expert ratings of 1290 components. Features were optimized to solve the binary classification problem ', ...
'reject vs. accept.\n \n', ...
'If you have questions or suggestions about the toolbox, please contact \n ', ...
'Irene Winkler, TU Berlin [email protected] \n \n ', ...
'Reference: \nI. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual', ...
'ICA-components for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.''])', ...
',''About MARA'');']);
|
github
|
lcnhappe/happe-master
|
pop_visualizeMARAfeatures.m
|
.m
|
happe-master/Packages/MARA-master/pop_visualizeMARAfeatures.m
| 4,558 |
utf_8
|
c888a9b58c7e7893d090883d152d5e09
|
% pop_visualizeMARAfeatures() - Display features that MARA's decision
% for artifact rejection is based on
%
% Usage:
% >> pop_visualizeMARAfeatures(gcompreject, MARAinfo);
%
% Inputs:
% gcompreject - array <1 x nIC> containing 1 if component was rejected
% MARAinfo - struct containing more information about MARA classification
% (output of function <MARA>)
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact according to
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% See also: MARA(), processMARA(), pop_selectcomps_MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function pop_visualizeMARAfeatures(gcompreject, MARAinfo)
%try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings.rowsize = 200;
panelsettings.columnsize = 200;
panelsettings.columns = floor(width/(2*panelsettings.columnsize));
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.columns * panelsettings.rows;
panelsettings.pages = ceil(length(gcompreject)/ panelsettings.numberPerPage);
% display components on a number of different pages
for page=1:panelsettings.pages
selectcomps_1page(page, panelsettings, gcompreject, MARAinfo);
end;
%catch
% eeglab_error
%end
function EEG = selectcomps_1page(page, panelsettings, gcompreject, MARAinfo)
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', 'Visualize MARA features', 'numbertitle', 'off');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.columns panelsettings.rowsize*panelsettings.rows]);
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : length(gcompreject);
end
% draw each component
% %%%%%%%%%%%%%%%%
for i = 1:length(range)
subplot(panelsettings.rows, panelsettings.columns, i)
for j = 1:6
h = barh(j, MARAinfo.normfeats(j, range(i)));
hold on;
if j <= 4 && MARAinfo.normfeats(j, range(i)) > 0
set(h, 'FaceColor', [0.4 0 0]);
end
if j > 4 && MARAinfo.normfeats(j, range(i)) < 0
set(h, 'FaceColor', [0.4 0 0]);
end
end
axis square;
if mod(i, panelsettings.columns) == 1
set(gca,'YTick', 1:6, 'YTickLabel', {'Current Density Norm', ...
'Range in Pattern', 'Local Skewness', 'lambda', '8-13Hz', 'FitError'})
else
set(gca,'YTick', 1:6, 'YTickLabel', cell(1,6))
end
if gcompreject(range(i)) == 1
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))),...
'Color', [0.4 0 0]);
set(gca, 'Color', [1 0.7 0.7])
%keyboard
else
title(sprintf('IC %d, p-artifact = %1.2f', range(i),MARAinfo.posterior_artefactprob(range(i))));
end
end
|
github
|
lcnhappe/happe-master
|
processMARA.m
|
.m
|
happe-master/Packages/MARA-master/processMARA.m
| 6,510 |
utf_8
|
896a41c6475ec80bf7706cc7166ce7a8
|
% processMARA() - Processing for Automatic Artifact Classification with MARA.
% processMARA() calls MACA and saves the identified artifactual components
% in EEG.reject.gcompreject.
% The functions optionally filters the data, runs ICA, plots components or
% reject artifactual components immediately.
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,options)
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Optional Input:
% options - 1x5 array specifing optional operations, default is [0,0,0,0,0]
% - option(1) = 1 => filter the data before MARA classification
% - option(2) = 1 => run ica before MARA classification
% - option(3) = 1 => plot components to label them for rejection after MARA classification
% (for rejection)
% - option(4) = 1 => plot MARA features for each IC
% - option(4) = 1 => automatically reject MARA's artifactual
% components without inspecting them
%
% See also: pop_eegfilt(), pop_runica, MARA(), pop_selectcomps_MARA(), pop_subcomp
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET,varargin)
if isempty(EEG.chanlocs)
try
error('No channel locations. Aborting MARA.')
catch
eeglab_error;
return;
end
end
if not(isempty(varargin))
options = varargin{1};
else
options = [0 0 0 0 0];
end
%% filter the data
if options(1) == 1
disp('Filtering data');
[EEG, LASTCOM] = pop_eegfilt(EEG);
eegh(LASTCOM);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% run ica
if options(2) == 1
disp('Run ICA');
[EEG, LASTCOM] = pop_runica(EEG);
[ALLEEG EEG CURRENTSET, LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
end
%% check if ica components are present
[EEG LASTCOM] = eeg_checkset(EEG, 'ica');
if LASTCOM < 0
disp('There are no ICA components present. Aborting classification.');
return
else
eegh(LASTCOM);
end
%% classify artifactual components with MARA
[artcomps, MARAinfo] = MARA(EEG);
EEG.reject.MARAinfo = MARAinfo;
disp('MARA marked the following components for rejection: ')
if isempty(artcomps)
disp('None')
else
disp(artcomps)
disp(' ')
end
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
else % if gcompreject present check whether labels differ from MARA
if and(length(EEG.reject.gcompreject) == size(EEG.icawinv,2), ...
not(isempty(find(EEG.reject.gcompreject))))
tmp = zeros(1,size(EEG.icawinv,2));
tmp(artcomps) = 1;
if not(isequal(tmp, EEG.reject.gcompreject))
answer = questdlg(...
'Some components are already labeled for rejection. What do you want to do?',...
'Labels already present','Merge artifactual labels','Overwrite old labels', 'Cancel','Cancel');
switch answer,
case 'Overwrite old labels',
gcompreject_old = EEG.reject.gcompreject;
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
disp('Overwrites old labels')
case 'Merge artifactual labels'
disp('Merges MARA''s and old labels')
gcompreject_old = EEG.reject.gcompreject;
case 'Cancel',
return;
end
else
gcompreject_old = EEG.reject.gcompreject;
end
else
EEG.reject.gcompreject = zeros(1,size(EEG.icawinv,2));
gcompreject_old = EEG.reject.gcompreject;
end
end
EEG.reject.gcompreject(artcomps) = 1;
try
EEGLABfig = findall(0, 'tag', 'EEGLAB');
MARAvizmenu = findobj(EEGLABfig, 'tag', 'MARAviz');
set(MARAvizmenu, 'Enable', 'on');
catch
keyboard
end
%% display components with checkbox to label them for artifact rejection
if options(3) == 1
if isempty(artcomps)
answer = questdlg2(...
'MARA identied no artifacts. Do you still want to visualize components?',...
'No artifacts identified','Yes', 'No', 'No');
if strcmp(answer,'No')
return;
end
end
[EEG, LASTCOM] = pop_selectcomps_MARA(EEG, gcompreject_old);
eegh(LASTCOM);
if options(4) == 1
pop_visualizeMARAfeatures(EEG.reject.gcompreject, EEG.reject.MARAinfo);
end
end
%% automatically remove artifacts
if and(and(options(5) == 1, not(options(3) == 1)), not(isempty(artcomps)))
try
[EEG LASTCOM] = pop_subcomp(EEG);
eegh(LASTCOM);
catch
eeglab_error
end
[ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET);
eegh(LASTCOM);
disp('Artifact rejection done.');
end
|
github
|
lcnhappe/happe-master
|
MARA.m
|
.m
|
happe-master/Packages/MARA-master/MARA.m
| 12,568 |
utf_8
|
5127d8f931932b5c0760a9a61a0d0b6e
|
% MARA() - Automatic classification of multiple artifact components
% Classies artifactual ICs based on 6 features from the time domain,
% the frequency domain, and the pattern
%
% Usage:
% >> [artcomps, info] = MARA(EEG);
%
% Inputs:
% EEG - input EEG structure
%
% Outputs:
% artcomps - array containing the numbers of the artifactual
% components
% info - struct containing more information about MARA classification
% .posterior_artefactprob : posterior probability for each
% IC of being an artefact
% .normfeats : <6 x nIC > features computed by MARA for each IC,
% normalized by the training data
% The features are: (1) Current Density Norm, (2) Range
% in Pattern, (3) Local Skewness of the Time Series,
% (4) Lambda, (5) 8-13 Hz, (6) FitError.
%
% For more information see:
% I. Winkler, S. Haufe, and M. Tangermann, Automatic classification of artifactual ICA-components
% for artifact removal in EEG signals, Behavioral and Brain Functions, 7, 2011.
%
% See also: processMARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [artcomps, info] = MARA(EEG)
try
%%%%%%%%%%%%%%%%%%%%
%% Calculate features from the pattern (component map)
%%%%%%%%%%%%%%%%%%%%
% extract channel labels
clab = {};
for i=1:length(EEG.chanlocs)
clab{i} = EEG.chanlocs(i).labels;
end
% cut to channel labels common with training data
load('fv_training_MARA'); %load struct fv_tr
[clab_common i_te i_tr ] = intersect(upper(clab), upper(fv_tr.clab));
clab_common = fv_tr.clab(i_tr);
if length(clab_common) == 0
error(['There were no matching channeldescriptions found.' , ...
'MARA needs channel labels of the form Cz, Oz, F3, F4, Fz, etc. Aborting.'])
end
patterns = (EEG.icawinv(i_te,:));
[M100 idx] = get_M100_ADE(clab_common); %needed for Current Density Norm
disp('MARA is computing features. Please wait');
%standardize patterns
patterns = patterns./repmat(std(patterns,0,1),length(patterns(:,1)),1);
%compute current density norm
feats(1,:) = log(sqrt(sum((M100*patterns(idx,:)).^2)));
%compute spatial range
feats(2,:) = log(max(patterns) - min(patterns));
%%%%%%%%%%%%%%%%%%%%
%% Calculate time and frequency features
%%%%%%%%%%%%%%%%%%%%
%compute time and frequency features (Current Density Norm, Range Within Pattern,
%Average Local Skewness, Band Power 8 - 13 Hz)
feats(3:6,:) = extract_time_freq_features(EEG);
disp('Features ready');
%%%%%%%%%%%%%%%%%%%%%%
%% Adapt train features to clab
%%%%%%%%%%%%%%%%%%%%
fv_tr.pattern = fv_tr.pattern(i_tr, :);
fv_tr.pattern = fv_tr.pattern./repmat(std(fv_tr.pattern,0,1),length(fv_tr.pattern(:,1)),1);
fv_tr.x(2,:) = log(max(fv_tr.pattern) - min(fv_tr.pattern));
fv_tr.x(1,:) = log(sqrt(sum((M100 * fv_tr.pattern).^2)));
%%%%%%%%%%%%%%%%%%%%
%% Classification
%%%%%%%%%%%%%%%%%%%%
[C, foo, posterior] = classify(feats',fv_tr.x',fv_tr.labels(1,:));
artcomps = find(C == 0)';
info.posterior_artefactprob = posterior(:, 1)';
info.normfeats = (feats - repmat(mean(fv_tr.x, 2), 1, size(feats, 2)))./ ...
repmat(std(fv_tr.x,0, 2), 1, size(feats, 2));
catch
eeglab_error;
artcomps = [];
end
end
function features = extract_time_freq_features(EEG)
% - 1st row: Average Local Skewness
% - 2nd row: lambda
% - 3rd row: Band Power 8 - 13 Hz
% - 4rd row: Fit Error
%
data = EEG.data;
fs = EEG.srate; %sampling frequency
% transform epoched data into continous data
if length(size(data)) == 3
s = size(data);
data = reshape(data, [EEG.nbchan, prod(s(2:3))]);
end
%downsample (to 100-200Hz)
factor = max(floor(EEG.srate/100),1);
data = data(:, 1:factor:end);
fs = round(fs/factor);
%compute icaactivation and standardise variance to 1
icacomps = (EEG.icaweights * EEG.icasphere * data)';
icacomps = icacomps./repmat(std(icacomps,0,1),length(icacomps(:,1)),1);
icacomps = icacomps';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Calculate featues
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for ic=1:length(icacomps(:,1)) %for each component
fprintf('.');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Proc Spectrum for Channel
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[pxx, freq] = pwelch(icacomps(ic,:), ones(1, fs), [], fs, fs);
pxx = 10*log10(pxx * fs/2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% The average log band power between 8 and 13 Hz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p = 0;
for i = 8:13
p = p + pxx(find(freq == i,1));
end
Hz8_13 = p / (13-8+1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% lambda and FitError: deviation of a component's spectrum from
% a protoptypical 1/frequency curve
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
p1.x = 2; %first point: value at 2 Hz
p1.y = pxx(find(freq == p1.x,1));
p2.x = 3; %second point: value at 3 Hz
p2.y = pxx(find(freq == p2.x,1));
%third point: local minimum in the band 5-13 Hz
p3.y = min(pxx(find(freq == 5,1):find(freq == 13,1)));
p3.x = freq(find(pxx == p3.y,1));
%fourth point: min - 1 in band 5-13 Hz
p4.x = p3.x - 1;
p4.y = pxx(find(freq == p4.x,1));
%fifth point: local minimum in the band 33-39 Hz
p5.y = min(pxx(find(freq == 33,1):find(freq == 39,1)));
p5.x = freq(find(pxx == p5.y,1));
%sixth point: min + 1 in band 33-39 Hz
p6.x = p5.x + 1;
p6.y = pxx(find(freq == p6.x,1));
pX = [p1.x; p2.x; p3.x; p4.x; p5.x; p6.x];
pY = [p1.y; p2.y; p3.y; p4.y; p5.y; p6.y];
myfun = @(x,xdata)(exp(x(1))./ xdata.^exp(x(2))) - x(3);
xstart = [4, -2, 54];
try
fittedmodel = lsqcurvefit(myfun,xstart,double(pX),double(pY), [], [], optimset('Display', 'off'));
catch
try
% If the optimization toolbox is missing we try with the CurveFit toolbox
opt = fitoptions('Method','NonlinearLeastSquares','Startpoint',xstart);
myfun = fittype('exp(x1)./x.^exp(x2) - x3;','options',opt);
fitobject = fit(double(pX),double(pY),myfun);
fittedmodel = [fitobject.x1, fitobject.x2, fitobject.x3];
catch
% If the CurveFit toolbox is also missing we try with the Statistitcs toolbox
myfun = @(p,xdata)(exp(p(1))./ xdata.^exp(p(2))) - p(3);
mdl = NonLinearModel.fit(double(pX),double(pY),myfun,xstart);
fittedmodel = mdl.Coefficients.Estimate(:)';
end
end
%FitError: mean squared error of the fit to the real spectrum in the band 2-40 Hz.
ts_8to15 = freq(find(freq == 8) : find(freq == 15));
fs_8to15 = pxx(find(freq == 8) : find(freq == 15));
fiterror = log(norm(myfun(fittedmodel, ts_8to15)-fs_8to15)^2);
%lambda: parameter of the fit
lambda = fittedmodel(2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Averaged local skewness 15s
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = 15;
abs_local_scewness = [];
for i=1:interval:length(icacomps(ic,:))/fs-interval
abs_local_scewness = [abs_local_scewness, abs(skewness(icacomps(ic, i * fs:(i+interval) * fs)))];
end
if isempty(abs_local_scewness)
error('MARA needs at least 15ms long ICs to compute its features.')
else
mean_abs_local_scewness_15 = log(mean(abs_local_scewness));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Append Features
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
features(:,ic)= [mean_abs_local_scewness_15, lambda, Hz8_13, fiterror];
end
disp('.');
end
function [M100, idx_clab_desired] = get_M100_ADE(clab_desired)
% [M100, idx_clab_desired] = get_M100_ADEC(clab_desired)
%
% IN clab_desired - channel setup for which M100 should be calculated
% OUT M100
% idx_clab_desired
% M100 is the matrix such that feature = norm(M100*ica_pattern(idx_clab_desired), 'fro')
%
% (c) Stefan Haufe
lambda = 100;
load inv_matrix_icbm152; %L (forward matrix 115 x 2124 x 3), clab (channel labels)
[cl_ ia idx_clab_desired] = intersect(clab, clab_desired);
F = L(ia, :, :); %forward matrix for desired channels labels
[n_channels m foo] = size(F); %m = 2124, number of dipole locations
F = reshape(F, n_channels, 3*m);
%H - matrix that centralizes the pattern, i.e. mean(H*pattern) = 0
H = eye(n_channels) - ones(n_channels, n_channels)./ n_channels;
%W - inverse of the depth compensation matrix Lambda
W = sloreta_invweights(L);
L = H*F*W;
%We have inv(L'L +lambda eye(size(L'*L))* L' = L'*inv(L*L' + lambda
%eye(size(L*L')), which is easier to calculate as number of dimensions is
%much smaller
%calulate the inverse of L*L' + lambda * eye(size(L*L')
[U D] = eig(L*L');
d = diag(D);
di = d+lambda;
di = 1./di;
di(d < 1e-10) = 0;
inv1 = U*diag(di)*U'; %inv1 = inv(L*L' + lambda *eye(size(L*L'))
%get M100
M100 = L'*inv1*H;
end
function W = sloreta_invweights(LL)
% inverse sLORETA-based weighting
%
% Synopsis:
% W = sloreta_invweights(LL);
%
% Arguments:
% LL: [M N 3] leadfield tensor
%
% Returns:
% W: [3*N 3*N] block-diagonal matrix of weights
%
% Stefan Haufe, 2007, 2008
%
% License
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see http://www.gnu.org/licenses/.
[M N NDUM]=size(LL);
L=reshape(permute(LL, [1 3 2]), M, N*NDUM);
L = L - repmat(mean(L, 1), M, 1);
T = L'*pinv(L*L');
W = spalloc(N*NDUM, N*NDUM, N*NDUM*NDUM);
for ivox = 1:N
W(NDUM*(ivox-1)+(1:NDUM), NDUM*(ivox-1)+(1:NDUM)) = (T(NDUM*(ivox-1)+(1:NDUM), :)*L(:, NDUM*(ivox-1)+(1:NDUM)))^-.5;
end
ind = [];
for idum = 1:NDUM
ind = [ind idum:NDUM:N*NDUM];
end
W = W(ind, ind);
end
function [i_te, i_tr] = findconvertedlabels(pos_3d, chanlocs)
% IN pos_3d - 3d-positions of training channel labels
% chanlocs - EEG.chanlocs structure of data to be classified
%compute spherical coordinates theta and phi for the training channel
%label
[theta, phi, r] = cart2sph(pos_3d(1,:),pos_3d(2,:), pos_3d(3,:));
theta = theta - pi/2;
theta(theta < -pi) = theta(theta < -pi) + 2*pi;
theta = theta*180/pi;
phi = phi * 180/pi;
theta(find(pos_3d(1,:) == 0 & pos_3d(2,:) == 0)) = 0; %exception for Cz
clab_common = {};
i_te = [];
i_tr = [];
%For each channel in EEG.chanlocs, try to find matching channel in
%training data
for chan = 1:length(chanlocs)
if not(isempty(chanlocs(chan).sph_phi))
idx = find((theta <= chanlocs(chan).sph_theta + 6) ...
& (theta >= chanlocs(chan).sph_theta - 6) ...
& (phi <= chanlocs(chan).sph_phi + 6) ...
& (phi >= chanlocs(chan).sph_phi - 6));
if not(isempty(idx))
i_tr = [i_tr, idx(1)];
i_te = [i_te, chan];
end
end
end
end
|
github
|
lcnhappe/happe-master
|
pop_selectcomps_MARA.m
|
.m
|
happe-master/Packages/MARA-master/pop_selectcomps_MARA.m
| 7,617 |
utf_8
|
3df13de5291a735a3ae902eb9b7b4349
|
% pop_selectcomps_MARA() - Display components with checkbox to label
% them for artifact rejection
%
% Usage:
% >> EEG = pop_selectcomps_MARA(EEG, gcompreject_old);
%
% Inputs:
% EEG - Input dataset with rejected components (saved in
% EEG.reject.gcompreject)
%
% Optional Input:
% gcompreject_old - gcompreject to revert to in case the "Cancel"
% button is pressed
%
% Output:
% EEG - Output dataset with updated rejected components
%
% See also: processMARA(), pop_selectcomps()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_selectcomps_MARA(EEG, varargin)
if isempty(EEG.reject.gcompreject)
EEG.reject.gcompreject = zeros(size(EEG.icawinv,2));
end
if not(isempty(varargin))
gcompreject_old = varargin{1};
com = [ 'pop_selectcomps_MARA(' inputname(1) ',' inputname(2) ');'];
else
gcompreject_old = EEG.reject.gcompreject;
com = [ 'pop_selectcomps_MARA(' inputname(1) ');'];
end
try
set(0,'units','pixels');
resolution = get(0, 'Screensize');
width = resolution(3);
height = resolution(4);
panelsettings = {};
panelsettings.completeNumber = length(EEG.reject.gcompreject);
panelsettings.rowsize = 250;
panelsettings.columnsize = 300;
panelsettings.column = floor(width/panelsettings.columnsize);
panelsettings.rows = floor(height/panelsettings.rowsize);
panelsettings.numberPerPage = panelsettings.column * panelsettings.rows;
panelsettings.pages = ceil(length(EEG.reject.gcompreject)/ panelsettings.numberPerPage);
panelsettings.incy = 110;
panelsettings.incx = 110;
% display components on a number of different pages
for page=1:panelsettings.pages
EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old);
end;
checks = findall(0, 'style', 'checkbox');
for i = 1: length(checks)
set(checks(i), 'Enable', 'on')
end
catch
eeglab_error
end
function EEG = selectcomps_1page(EEG, page, panelsettings, gcompreject_old)
% Display components with checkbox to label them for artifact rejection
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% compute components (for plotting the spectrum)
if length(size(EEG.data)) == 3
s = size(EEG.data);
data = reshape(EEG.data, [EEG.nbchan, prod(s(2:3))]);
icacomps = EEG.icaweights * EEG.icasphere * data;
else
icacomps = EEG.icaweights * EEG.icasphere * EEG.data;
end
% set up the figure
% %%%%%%%%%%%%%%%%
if ~exist('fig')
mainFig = figure('name', [ 'MARA on dataset: ' EEG.setname ''], 'numbertitle', 'off', 'tag', 'ADEC - Plot');
set(mainFig, 'Color', BACKCOLOR)
set(gcf,'MenuBar', 'none');
pos = get(gcf,'Position');
set(gcf,'Position', [20 20 panelsettings.columnsize*panelsettings.column panelsettings.rowsize*panelsettings.rows]);
panelsettings.sizewx = 50/panelsettings.column;
panelsettings.sizewy = 80/panelsettings.rows;
pos = get(gca,'position'); % plot relative to current axes
hh = gca;
panelsettings.q = [pos(1) pos(2) 0 0];
panelsettings.s = [pos(3) pos(4) pos(3) pos(4)]./100;
axis off;
end;
% compute range of components to display
if page < panelsettings.pages
range = (1 + (panelsettings.numberPerPage * (page-1))) : (panelsettings.numberPerPage + ( panelsettings.numberPerPage * (page-1)));
else
range = (1 + (panelsettings.numberPerPage * (page-1))) : panelsettings.completeNumber;
end
data = struct;
data.gcompreject = EEG.reject.gcompreject;
data.gcompreject_old = gcompreject_old;
guidata(gcf, data);
% draw each component
% %%%%%%%%%%%%%%%%
count = 1;
for ri = range
% compute coordinates
X = mod(count-1, panelsettings.column)/panelsettings.column * panelsettings.incx-10;
Y = (panelsettings.rows-floor((count-1)/panelsettings.column))/panelsettings.rows * panelsettings.incy - panelsettings.sizewy*1.3;
% plot the head
if ~strcmp(get(gcf, 'tag'), 'ADEC - Plot');
disp('Aborting plot');
return;
end;
ha = axes('Units','Normalized', 'Position',[X Y panelsettings.sizewx*0.85 panelsettings.sizewy*0.85].*panelsettings.s+panelsettings.q);
topoplot( EEG.icawinv(:,ri), EEG.chanlocs, 'verbose', 'off', 'style' , 'fill');
axis square;
% plot the spectrum
ha = axes('Units','Normalized', 'Position',[X+1.05*panelsettings.sizewx Y-1 (panelsettings.sizewx*1.15)-1 panelsettings.sizewy-1].*panelsettings.s+panelsettings.q);
[pxx, freq] = pwelch(icacomps(ri,:), ones(1, EEG.srate), [], EEG.srate, EEG.srate);
pxx = 10*log10(pxx * EEG.srate/2);
plot(freq, pxx, 'LineWidth', 2)
xlim([0 50]);
grid on;
xlabel('Hz')
set(gca, 'Xtick', 0:10:50)
if isfield(EEG.reject, 'MARAinfo')
title(sprintf('Artifact Probability = %1.2f', ...
EEG.reject.MARAinfo.posterior_artefactprob(ri)));
end
uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[X+panelsettings.sizewx*0.5 Y+panelsettings.sizewy panelsettings.sizewx, ...
panelsettings.sizewy*0.2].*panelsettings.s+panelsettings.q, ...
'Enable', 'off','tag', ['check_' num2str(ri)], 'Value', EEG.reject.gcompreject(ri), ...
'String', ['IC' num2str(ri) ' - Artifact?'], ...
'Callback', {@callback_checkbox, ri});
drawnow;
count = count +1;
end;
% draw the botton buttons
% %%%%%%%%%%%%%%%%
if ~exist('fig')
% cancel button
cancelcommand = ['openplots = findall(0, ''tag'', ''ADEC - Plot'');', ...
'data = guidata(openplots(1)); close(openplots);', ...
'EEG.reject.gcompreject = data.gcompreject_old;'];
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'Cancel', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[-10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', cancelcommand );
okcommand = ['data = guidata(gcf); EEG.reject.gcompreject = data.gcompreject; ' ...
'[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET); '...
'eegh(''[ALLEEG EEG] = eeg_store(ALLEEG, EEG, CURRENTSET);''); '...
'close(gcf);' ];
% ok button
hh = uicontrol(gcf, 'Style', 'pushbutton', 'string', 'OK', ...
'Units','Normalized', 'BackgroundColor', GUIBUTTONCOLOR, ...
'Position',[10 -11 15 panelsettings.sizewy*0.25].*panelsettings.s+panelsettings.q, ...
'callback', okcommand);
end;
function callback_checkbox(hObject,eventdata, position)
openplots = findall(0, 'tag', 'ADEC - Plot');
data = guidata(openplots(1));
data.gcompreject(position) = mod(data.gcompreject(position) + 1, 2);
%save changes in every plot
for i = 1: length(openplots)
guidata(openplots(i), data);
end
|
github
|
lcnhappe/happe-master
|
pop_processMARA.m
|
.m
|
happe-master/Packages/MARA-master/pop_processMARA.m
| 5,095 |
utf_8
|
7932742793cce3ca7b8caeb78ae22d82
|
% pop_processMARA() - graphical interface to select MARA's actions
%
% Usage:
% >> [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA(ALLEEG,EEG,CURRENTSET );
%
% Inputs and Outputs:
% ALLEEG - array of EEG dataset structures
% EEG - current dataset structure or structure array
% (EEG.reject.gcompreject will be updated)
% CURRENTSET - index(s) of the current EEG dataset(s) in ALLEEG
%
%
% Output:
% com - last command, call to itself
%
% See also: processMARA(), pop_selectcomps_MARA(), MARA()
% Copyright (C) 2013 Irene Winkler and Eric Waldburger
% Berlin Institute of Technology, Germany
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ALLEEG,EEG,CURRENTSET,com] = pop_processMARA (ALLEEG,EEG,CURRENTSET )
com = 'pop_processMARA ( ALLEEG,EEG,CURRENTSET )';
try, icadefs;
catch,
BACKCOLOR = [0.8 0.8 0.8];
GUIBUTTONCOLOR = [0.8 0.8 0.8];
end;
% set up the figure
% %%%%%%%%%%%%%%%%%
figure('name', 'MARA', ...
'numbertitle', 'off', 'tag', 'ADEC - Init');
set(gcf,'MenuBar', 'none', 'Color', BACKCOLOR);
pos = get(gcf,'Position');
set(gcf,'Position', [pos(1) 350 350 350]);
if ~strcmp(get(gcf, 'tag'), 'ADEC - Init');
disp('Aborting plot');
return;
end;
% set standards for options and store them with guidata()
% order: filter, run_ica, plot data, remove automatically
options = [0, 0, 0, 0, 0];
guidata(gcf, options);
% text
% %%%%%%%%%%%%%%%%%
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.85 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'Select preprocessing operations:');
text = uicontrol(gcf, 'Style', 'text', 'Units','Normalized', 'Position',...
[0 0.55 0.75 0.06],'BackGroundColor', BACKCOLOR, 'FontWeight', 'bold', ...
'String', 'After MARA classification:');
% checkboxes
% %%%%%%%%%%%%%%%%%
filterBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.75 0.75 0.075], 'String', 'Filter the data', 'Callback', ...
'options = guidata(gcf); options(1) = mod(options(1) + 1, 2); guidata(gcf,options);');
icaBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.075 0.65 0.75 0.075], 'String', 'Run ICA', 'Callback', ...
'options = guidata(gcf); options(2) = mod(options(2) + 1, 2); guidata(gcf,options);');
% radio button group
% %%%%%%%%%%%%%%%%%
vizBox = uicontrol(gcf, 'Style', 'checkbox', 'Units','Normalized', 'Position',...
[0.2 0.2 0.9 0.2], 'String', 'Visualize Classifcation Features', 'Enable', 'Off', ...
'tag', 'vizBox');
h = uibuttongroup('visible','off','Units','Normalized','Position',[0.075 0.15 0.9 0.35]);
% Create two radio buttons in the button group.
radNothing = uicontrol('Style','radiobutton','String','Continue using EEGLab functions',...
'Units','Normalized','Position',[0.02 0.8 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radNothing');
radPlot = uicontrol('Style','radiobutton','String','Plot and select components for removal',...
'Units','Normalized','Position',[0.02 0.5 0.9 0.2],'parent',h,'HandleVisibility','off',...
'tag', 'radPlot');
radAuto = uicontrol('Style','radiobutton','String','Automatically remove components',...
'Units','Normalized','Position',[0.02 0.1 0.9 0.2],'parent',h,'HandleVisibility','off','tag', 'radAuto');
set(h,'SelectedObject',radNothing,'Visible','on', 'tag', 'h','BackGroundColor', BACKCOLOR);
set(h, 'SelectionChangeFcn',['s = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; ' ...
'set(s.vizBox,''Enable'', ''on''); else; set(s.vizBox,''Enable'', ''off''); end;']);
% bottom buttons
% %%%%%%%%%%%%%%%%%
cancel = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.075 0.05 0.4 0.08],'String', 'Cancel','BackgroundColor', GUIBUTTONCOLOR,...
'Callback', 'close(gcf);');
ok = uicontrol(gcf, 'Style', 'pushbutton', 'Units','Normalized', 'Position',...
[0.5 0.05 0.4 0.08],'String', 'Ok','BackgroundColor', GUIBUTTONCOLOR, ...
'Callback', ['options = guidata(gcf);' ...
's = guihandles(gcf); if get(s.h, ''SelectedObject'') == s.radPlot; options(3) = 1; end; '...
'options(4) = get(s.vizBox, ''Value''); ' ...
'if get(s.h, ''SelectedObject'') == s.radAuto; options(5) = 1; end;' ...
'close(gcf); pause(eps); [ALLEEG, EEG, CURRENTSET] = processMARA(ALLEEG,EEG,CURRENTSET, options);']);
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
haversine-formula.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/haversine-formula/matlab/haversine-formula.m
| 544 |
utf_8
|
4d8ed7ec87e14b539dc6bba3595059d9
|
function rad = radians(degree)
% degrees to radians
rad = degree .* pi / 180;
end;
function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
% HAVERSINE_FORMULA.AWK - converted from AWK
dlat = radians(lat2-lat1);
dlon = radians(lon2-lon1);
lat1 = radians(lat1);
lat2 = radians(lat2);
a = (sin(dlat./2)).^2 + cos(lat1) .* cos(lat2) .* (sin(dlon./2)).^2;
c = 2 .* asin(sqrt(a));
arrayfun(@(x) printf("distance: %.4f km\n",6372.8 * x), c);
end;
[a,c,dlat,dlon] = haversine(36.12,-86.67,33.94,-118.40); % BNA to LAX
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
bulls-and-cows-player.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/bulls-and-cows-player/matlab/bulls-and-cows-player.m
| 2,012 |
utf_8
|
df5a15858fa8b7b20809a1d6267363fa
|
function BullsAndCowsPlayer
% Plays the game Bulls and Cows as the player
% Generate list of all possible numbers
nDigits = 4;
lowVal = 1;
highVal = 9;
combs = nchoosek(lowVal:highVal, nDigits);
nCombs = size(combs, 1);
nPermsPerComb = factorial(nDigits);
gList = zeros(nCombs.*nPermsPerComb, nDigits);
for k = 1:nCombs
gList(nPermsPerComb*(k-1)+1:nPermsPerComb*k, :) = perms(combs(k, :));
end
% Prompt user
fprintf('Think of a number with:\n')
fprintf(' %d digits\n', nDigits)
fprintf(' Each digit between %d and %d inclusive\n', lowVal, highVal)
fprintf(' No repeated digits\n')
fprintf('I''ll try to guess that number and you score me:\n')
fprintf(' 1 Bull per correct digit in the correct place\n')
fprintf(' 1 Cow per correct digit in the wrong place\n')
fprintf('Think of your number and press Enter when ready\n')
pause
% Play game until all digits are correct
nBulls = 0;
nGuesses = 0;
while nBulls < 4 && ~isempty(gList)
nList = size(gList, 1);
g = gList(randi(nList), :); % Random guess from list
fprintf('My guess: %s?\n', sprintf('%d', g))
nBulls = input('How many bulls? ');
if nBulls < 4
nCows = input('How many cows? ');
del = false(nList, 1);
for k = 1:nList
del(k) = any([nBulls nCows] ~= CountBullsCows(g, gList(k, :)));
end
gList(del, :) = [];
end
nGuesses = nGuesses+1;
end
if isempty(gList)
fprintf('That''s bull! You messed up your scoring.\n')
else
fprintf('Yay, I won! Only took %d guesses.\n', nGuesses)
end
end
function score = CountBullsCows(guess, correct)
% Checks the guessed array of digits against the correct array to find the score
% Assumes arrays of same length and valid numbers
bulls = guess == correct;
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
honeycombs.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/honeycombs/matlab/honeycombs.m
| 2,850 |
utf_8
|
8ecce457b119ea563b391513719558d8
|
function Honeycombs
nRows = 4; % Number of rows
nCols = 5; % Number of columns
nHexs = nRows*nCols; % Number of hexagons
rOuter = 1; % Circumradius
startX = 0; % x-coordinate of upper left hexagon
startY = 0; % y-coordinate of upper left hexagon
delX = rOuter*1.5; % Horizontal distance between hexagons
delY = rOuter*sqrt(3); % Vertical distance between hexagons
offY = delY/2; % Vertical offset between columns
genHexX = rOuter.*cos(2.*pi.*(0:5).'./6); % x-coords of general hexagon
genHexY = rOuter.*sin(2.*pi.*(0:5).'./6); % y-coords of general hexagon
centX = zeros(1, nHexs); % x-coords of hexagon centers
centY = zeros(1, nHexs); % y-coords of hexagon centers
for c = 1:nCols
idxs = (c-1)*nRows+1:c*nRows; % Indeces of hexagons in that column
if mod(c, 2) % Odd numbered column - higher y-values
centY(idxs) = startY:-delY:startY-delY*(nRows-1);
else % Even numbered column - lower y-values
centY(idxs) = startY-offY:-delY:startY-offY-delY*(nRows-1);
end
centX(idxs) = (startX+(c-1)*delX).*ones(1, nRows);
end
[MCentX, MGenHexX] = meshgrid(centX, genHexX);
[MCentY, MGenHexY] = meshgrid(centY, genHexY);
HexX = MCentX+MGenHexX; % x-coords of hexagon vertices
HexY = MCentY+MGenHexY; % y-coords of hexagon vertices
figure
hold on
letters = char([65:90 97:122]);
randIdxs = randperm(26);
letters = [letters(randIdxs) letters(26+randIdxs)];
hexH = zeros(1, nHexs);
for k = 1:nHexs % Create patches individually
hexH(k) = patch(HexX(:, k), HexY(:, k), [1 1 0]);
textH = text(centX(k), centY(k), letters(mod(k, length(letters))), ...
'HorizontalAlignment', 'center', 'FontSize', 14, ...
'FontWeight', 'bold', 'Color', [1 0 0], 'HitTest', 'off');
set(hexH(k), 'UserData', textH) % Save to object for easy access
end
axis equal
axis off
set(gca, 'UserData', '') % List of clicked patch labels
set(hexH, 'ButtonDownFcn', @onClick)
end
function onClick(obj, event)
axesH = get(obj, 'Parent');
textH = get(obj, 'UserData');
set(obj, 'FaceColor', [1 0 1]) % Change color
set(textH, 'Color', [0 0 0]) % Change label color
set(obj, 'HitTest', 'off') % Ignore future clicks
currList = get(axesH, 'UserData'); % Hexs already clicked
newList = [currList get(textH, 'String')]; % Update list
set(axesH, 'UserData', newList)
title(newList)
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
image-convolution.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/image-convolution/matlab/image-convolution.m
| 7,433 |
utf_8
|
d070d20a112b6e944d34feac79521dd3
|
function testConvImage
Im = [1 2 1 5 5 ; ...
1 2 7 9 9 ; ...
5 5 5 5 5 ; ...
5 2 2 2 2 ; ...
1 1 1 1 1 ]; % Sample image for example illustration only
Ker = [1 2 1 ; ...
2 4 2 ; ...
1 2 1 ]; % Gaussian smoothing (without normalizing)
fprintf('Original image:\n')
disp(Im)
fprintf('Original kernal:\n')
disp(Ker)
fprintf('Padding with zeroes:\n')
disp(convImage(Im, Ker, 'zeros'))
fprintf('Padding with fives:\n')
disp(convImage(Im, Ker, 'value', 5))
fprintf('Duplicating border pixels to pad image:\n')
disp(convImage(Im, Ker, 'extend'))
fprintf('Renormalizing kernal and using only values within image:\n')
disp(convImage(Im, Ker, 'partial'))
fprintf('Only processing inner (non-border) pixels:\n')
disp(convImage(Im, Ker, 'none'))
% Ker = [1 2 1 ; ...
% 2 4 2 ; ...
% 1 2 1 ]./16;
% Im = imread('testConvImageTestImage.png', 'png');
% figure
% imshow(imresize(Im, 10))
% title('Original image')
% figure
% imshow(imresize(convImage(Im, Ker, 'zeros'), 10))
% title('Padding with zeroes')
% figure
% imshow(imresize(convImage(Im, Ker, 'value', 50), 10))
% title('Padding with fifty: 50')
% figure
% imshow(imresize(convImage(Im, Ker, 'extend'), 10))
% title('Duplicating border pixels to pad image')
% figure
% imshow(imresize(convImage(Im, Ker, 'partial'), 10))
% title('Renormalizing kernal and using only values within image')
% figure
% imshow(imresize(convImage(Im, Ker, 'none'), 10))
% title('Only processing inner (non-border) pixels')
end
function ImOut = convImage(Im, Ker, varargin)
% ImOut = convImage(Im, Ker)
% Filters an image using sliding-window kernal convolution.
% Convolution is done layer-by-layer. Use rgb2gray if single-layer needed.
% Zero-padding convolution will be used if no border handling is specified.
% Im - Array containing image data (output from imread)
% Ker - 2-D array to convolve image, needs odd number of rows and columns
% ImOut - Filtered image, same dimensions and datatype as Im
%
% ImOut = convImage(Im, Ker, 'zeros')
% Image will be padded with zeros when calculating convolution
% (useful for magnitude calculations).
%
% ImOut = convImage(Im, Ker, 'value', padVal)
% Image will be padded with padVal when calculating convolution
% (possibly useful for emphasizing certain data with unusual kernal)
%
% ImOut = convImage(Im, Ker, 'extend')
% Image will be padded with the value of the closest image pixel
% (useful for smoothing or blurring filters).
%
% ImOut = convImage(Im, Ker, 'partial')
% Image will not be padded. Borders will be convoluted with only valid pixels,
% and convolution matrix will be renormalized counting only the pixels within
% the image (also useful for smoothing or blurring filters).
%
% ImOut = convImage(Im, Ker, 'none')
% Image will not be padded. Convolution will only be applied to inner pixels
% (useful for edge and corner detection filters)
% Handle input
if mod(size(Ker, 1), 2) ~= 1 || mod(size(Ker, 2), 2) ~= 1
eid = sprintf('%s:evenRowsCols', mfilename);
error(eid,'''Ker'' parameter must have odd number of rows and columns.')
elseif nargin > 4
eid = sprintf('%s:maxrhs', mfilename);
error(eid, 'Too many input arguments.');
elseif nargin == 4 && ~strcmp(varargin{1}, 'value')
eid = sprintf('%s:invalidParameterCombination', mfilename);
error(eid, ['The ''padVal'' parameter is only valid with the ' ...
'''value'' option.'])
elseif nargin < 4 && strcmp(varargin{1}, 'value')
eid = sprintf('%s:minrhs', mfilename);
error(eid, 'Not enough input arguments.')
elseif nargin < 3
method = 'zeros';
else
method = lower(varargin{1});
if ~any(strcmp(method, {'zeros' 'value' 'extend' 'partial' 'none'}))
eid = sprintf('%s:invalidParameter', mfilename);
error(eid, 'Invalid option parameter. Must be one of:%s', ...
sprintf('\n\t\t%s', ...
'zeros', 'value', 'extend', 'partial', 'none'))
end
end
% Gather information and prepare for convolution
[nImRows, nImCols, nImLayers] = size(Im);
classIm = class(Im);
Im = double(Im);
ImOut = zeros(nImRows, nImCols, nImLayers);
[nKerRows, nKerCols] = size(Ker);
nPadRows = nImRows+nKerRows-1;
nPadCols = nImCols+nKerCols-1;
padH = (nKerRows-1)/2;
padW = (nKerCols-1)/2;
% Convolute on a layer-by-layer basis
for k = 1:nImLayers
if strcmp(method, 'zeros')
ImOut(:, :, k) = conv2(Im(:, :, k), Ker, 'same');
elseif strcmp(method, 'value')
padding = varargin{2}.*ones(nPadRows, nPadCols);
padding(padH+1:end-padH, padW+1:end-padW) = Im(:, :, k);
ImOut(:, :, k) = conv2(padding, Ker, 'valid');
elseif strcmp(method, 'extend')
padding = zeros(nPadRows, nPadCols);
padding(padH+1:end-padH, padW+1:end-padW) = Im(:, :, k); % Middle
padding(1:padH, 1:padW) = Im(1, 1, k); % TopLeft
padding(end-padH+1:end, 1:padW) = Im(end, 1, k); % BotLeft
padding(1:padH, end-padW+1:end) = Im(1, end, k); % TopRight
padding(end-padH+1:end, end-padW+1:end) = Im(end, end, k);% BotRight
padding(padH+1:end-padH, 1:padW) = ...
repmat(Im(:, 1, k), 1, padW); % Left
padding(padH+1:end-padH, end-padW+1:end) = ...
repmat(Im(:, end, k), 1, padW); % Right
padding(1:padH, padW+1:end-padW) = ...
repmat(Im(1, :, k), padH, 1); % Top
padding(end-padH+1:end, padW+1:end-padW) = ...
repmat(Im(end, :, k), padH, 1); % Bottom
ImOut(:, :, k) = conv2(padding, Ker, 'valid');
elseif strcmp(method, 'partial')
ImOut(padH+1:end-padH, padW+1:end-padW, k) = ...
conv2(Im(:, :, k), Ker, 'valid'); % Middle
unprocessed = true(nImRows, nImCols);
unprocessed(padH+1:end-padH, padW+1:end-padW) = false; % Border
for r = 1:nImRows
for c = 1:nImCols
if unprocessed(r, c)
limitedIm = Im(max(1, r-padH):min(nImRows, r+padH), ...
max(1, c-padW):min(nImCols, c+padW), k);
limitedKer = Ker(max(1, 2-r+padH): ...
min(nKerRows, nKerRows+nImRows-r-padH), ...
max(1, 2-c+padW):...
min(nKerCols, nKerCols+nImCols-c-padW));
limitedKer = limitedKer.*sum(Ker(:))./ ...
sum(limitedKer(:));
ImOut(r, c, k) = sum(sum(limitedIm.*limitedKer));
end
end
end
else % method is 'none'
ImOut(:, :, k) = Im(:, :, k);
ImOut(padH+1:end-padH, padW+1:end-padW, k) = ...
conv2(Im(:, :, k), Ker, 'valid');
end
end
% Convert back to former image data type
ImOut = cast(ImOut, classIm);
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
bitmap-bresenhams-line-algorithm-1.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/bitmap-bresenhams-line-algorithm/matlab/bitmap-bresenhams-line-algorithm-1.m
| 1,186 |
utf_8
|
73849f70792c46a646e103935a779958
|
%screen = Bitmap object
%startPoint = [x0,y0]
%endPoint = [x1,y1]
%color = [red,green,blue]
function bresenhamLine(screen,startPoint,endPoint,color)
if( any(color > 255) )
error 'RGB colors must be between 0 and 255';
end
%Check for vertical line, x0 == x1
if( startPoint(1) == endPoint(1) )
%Draw vertical line
for i = (startPoint(2):endPoint(2))
setPixel(screen,[startPoint(1) i],color);
end
end
%Simplified Bresenham algorithm
dx = abs(endPoint(1) - startPoint(1));
dy = abs(endPoint(2) - startPoint(2));
if(startPoint(1) < endPoint(1))
sx = 1;
else
sx = -1;
end
if(startPoint(2) < endPoint(2))
sy = 1;
else
sy = -1;
end
err = dx - dy;
pixel = startPoint;
while(true)
screen.setPixel(pixel,color); %setPixel(x0,y0)
if( pixel == endPoint )
break;
end
e2 = 2*err;
if( e2 > -dy )
err = err - dy;
pixel(1) = pixel(1) + sx;
end
if( e2 < dx )
err = err + dx;
pixel(2) = pixel(2) + sy;
end
end
assignin('caller',inputname(1),screen); %saves the changes to the object
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
flipping-bits-game.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/flipping-bits-game/matlab/flipping-bits-game.m
| 2,733 |
utf_8
|
b5225ac55b751f26e68d02d1049f2829
|
function FlippingBitsGame(n)
% Play the flipping bits game on an n x n array
% Generate random target array
fprintf('Welcome to the Flipping Bits Game!\n')
if nargin < 1
n = input('What dimension array should we use? ');
end
Tar = logical(randi([0 1], n));
% Generate starting array by randomly flipping rows or columns
Cur = Tar;
while all(Cur(:) == Tar(:))
nFlips = randi([3*n max(10*n, 100)]);
randDim = randi([0 1], nFlips, 1);
randIdx = randi([1 n], nFlips, 1);
for k = 1:nFlips
if randDim(k)
Cur(randIdx(k), :) = ~Cur(randIdx(k), :);
else
Cur(:, randIdx(k)) = ~Cur(:, randIdx(k));
end
end
end
% Print rules
fprintf('Given a %d x %d logical array,\n', n, n)
fprintf('and a target array configuration,\n')
fprintf('attempt to transform the array to the target\n')
fprintf('by inverting the bits in a whole row or column\n')
fprintf('at once in as few moves as possible.\n')
fprintf('Enter the corresponding letter to invert a column,\n')
fprintf('or the corresponding number to invert a row.\n')
fprintf('0 will reprint the target array, and no entry quits.\n\n')
fprintf('Target:\n')
PrintArray(Tar)
% Play until player wins or quits
move = true;
nMoves = 0;
while ~isempty(move) && any(Cur(:) ~= Tar(:))
fprintf('Move %d:\n', nMoves)
PrintArray(Cur)
move = lower(input('Enter move: ', 's'));
if length(move) > 1
fprintf('Invalid move, try again\n')
elseif move
r = str2double(move);
if isnan(r)
c = move-96;
if c > n || c < 1
fprintf('Invalid move, try again\n')
else
Cur(:, c) = ~Cur(:, c);
nMoves = nMoves+1;
end
else
if r > n || r < 0
fprintf('Invalid move, try again\n')
elseif r == 0
fprintf('Target:\n')
PrintArray(Tar)
else
Cur(r, :) = ~Cur(r, :);
nMoves = nMoves+1;
end
end
end
end
if all(Cur(:) == Tar(:))
fprintf('You win in %d moves! Try not to flip out!\n', nMoves)
else
fprintf('Quitting? The challenge a bit much for you?\n')
end
end
function PrintArray(A)
[nRows, nCols] = size(A);
fprintf(' ')
fprintf(' %c', (1:nCols)+96)
fprintf('\n')
for r = 1:nRows
fprintf('%8d%s\n', r, sprintf(' %d', A(r, :)))
end
fprintf('\n')
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
abc-problem.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/abc-problem/matlab/abc-problem.m
| 790 |
utf_8
|
81f2c22e2247a71e1dafda16915f99f4
|
function testABC
combos = ['BO' ; 'XK' ; 'DQ' ; 'CP' ; 'NA' ; 'GT' ; 'RE' ; 'TG' ; 'QD' ; ...
'FS' ; 'JW' ; 'HU' ; 'VI' ; 'AN' ; 'OB' ; 'ER' ; 'FS' ; 'LY' ; ...
'PC' ; 'ZM'];
words = {'A' 'BARK' 'BOOK' 'TREAT' 'COMMON' 'SQUAD' 'CONFUSE'};
for k = 1:length(words)
possible = canMakeWord(words{k}, combos);
fprintf('Can%s make word %s.\n', char(~possible.*'NOT'), words{k})
end
end
function isPossible = canMakeWord(word, combos)
word = lower(word);
combos = lower(combos);
isPossible = true;
k = 1;
while isPossible && k <= length(word)
[r, c] = find(combos == word(k), 1);
if ~isempty(r)
combos(r, :) = '';
else
isPossible = false;
end
k = k+1;
end
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
iban-1.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/iban/matlab/iban-1.m
| 1,028 |
utf_8
|
b5dcb998fd69d25b80748f43f2a8697f
|
function valid = validateIBAN(iban)
% Determine if International Bank Account Number is valid IAW ISO 13616
% iban - string containing account number
if length(iban) < 5
valid = false;
else
iban(iban == ' ') = ''; % Remove spaces
iban = lower([iban(5:end) iban(1:4)])+0; % Rearrange and convert
iban(iban > 96 & iban < 123) = iban(iban > 96 & iban < 123)-87; % Letters
iban(iban > 47 & iban < 58) = iban(iban > 47 & iban < 58)-48; % Numbers
valid = piecewiseMod97(iban) == 1;
end
end
function result = piecewiseMod97(x)
% Conduct a piecewise version of mod(x, 97) to support large integers
% x is a vector of integers
x = sprintf('%d', x); % Get to single-digits per index
nDig = length(x);
i1 = 1;
i2 = min(9, nDig);
prefix = '';
while i1 <= nDig
y = str2double([prefix x(i1:i2)]);
result = mod(y, 97);
prefix = sprintf('%d', result);
i1 = i2+1;
i2 = min(i1+8, nDig);
end
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
classes-3.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/classes/matlab/classes-3.m
| 140 |
utf_8
|
9f9ed312eb6b69f944bc51a63731d8c9
|
%Set function
function GenericClassInstance = setValue(GenericClassInstance,newValue)
GenericClassInstance.classVariable = newValue;
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
classes-7.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/classes/matlab/classes-7.m
| 114 |
utf_8
|
e170f5bcd0eb8257d26831dfd9d76f38
|
%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
classes-2.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/classes/matlab/classes-2.m
| 114 |
utf_8
|
e170f5bcd0eb8257d26831dfd9d76f38
|
%Get function
function value = getValue(GenericClassInstance)
value = GenericClassInstance.classVariable;
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
ethiopian-multiplication-3.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/ethiopian-multiplication/matlab/ethiopian-multiplication-3.m
| 144 |
utf_8
|
eca009509a1c505dcdfbd6a65357e247
|
%Returns a logical 1 if the number is even, 0 otherwise.
function trueFalse = isEven(number)
trueFalse = logical( mod(number,2)==0 );
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
bulls-and-cows.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/bulls-and-cows/matlab/bulls-and-cows.m
| 2,359 |
utf_8
|
c763a0feaf16bec664158452df37a237
|
function BullsAndCows
% Plays the game Bulls and Cows as the "game master"
% Create a secret number
nDigits = 4;
lowVal = 1;
highVal = 9;
digitList = lowVal:highVal;
secret = zeros(1, 4);
for k = 1:nDigits
idx = randi(length(digitList));
secret(k) = digitList(idx);
digitList(idx) = [];
end
% Give game information
fprintf('Welcome to Bulls and Cows!\n')
fprintf('Try to guess the %d-digit number (no repeated digits).\n', nDigits)
fprintf('Digits are between %d and %d (inclusive).\n', lowVal, highVal)
fprintf('Score: 1 Bull per correct digit in correct place.\n')
fprintf(' 1 Cow per correct digit in incorrect place.\n')
fprintf('The number has been chosen. Now it''s your moooooove!\n')
gs = input('Guess: ', 's');
% Loop until user guesses right or quits (no guess)
nGuesses = 1;
while gs
gn = str2double(gs);
if isnan(gn) || length(gn) > 1 % Not a scalar
fprintf('Malformed guess. Keep to valid scalars.\n')
gs = input('Try again: ', 's');
else
g = sprintf('%d', gn) - '0';
if length(g) ~= nDigits || any(g < lowVal) || any(g > highVal) || ...
length(unique(g)) ~= nDigits % Invalid number for game
fprintf('Malformed guess. Remember:\n')
fprintf(' %d digits\n', nDigits)
fprintf(' Between %d and %d inclusive\n', lowVal, highVal)
fprintf(' No repeated digits\n')
gs = input('Try again: ', 's');
else
score = CountBullsCows(g, secret);
if score(1) == nDigits
fprintf('You win! Bully for you! Only %d guesses.\n', nGuesses)
gs = '';
else
fprintf('Score: %d Bulls, %d Cows\n', score)
gs = input('Guess: ', 's');
end
end
end
nGuesses = nGuesses+1; % Counts malformed guesses
end
end
function score = CountBullsCows(guess, correct)
% Checks the guessed array of digits against the correct array to find the score
% Assumes arrays of same length and valid numbers
bulls = guess == correct;
cows = ismember(guess(~bulls), correct);
score = [sum(bulls) sum(cows)];
end
|
github
|
stefanos1316/Rosetta_Code_Research_MSR-master
|
happy-numbers.m
|
.m
|
Rosetta_Code_Research_MSR-master/Scripts/Task/happy-numbers/matlab/happy-numbers.m
| 441 |
utf_8
|
b439e5762f0d9c6de15ca3d2169f6028
|
function findHappyNumbers
nHappy = 0;
k = 1;
while nHappy < 8
if isHappyNumber(k, [])
fprintf('%d ', k)
nHappy = nHappy+1;
end
k = k+1;
end
fprintf('\n')
end
function hap = isHappyNumber(k, prev)
if k == 1
hap = true;
elseif ismember(k, prev)
hap = false;
else
hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
end
end
|
github
|
lcarasik/TORCHE-master
|
StaggeredPressureDrop.m
|
.m
|
TORCHE-master/LEGACY/MATLAB/StaggeredPressureDrop.m
| 3,356 |
utf_8
|
f7d830d90a37536111a52f19052983fc
|
%Original Author: Jonah Haefner
%Last Modified: 10/27/2015
%Most Reecent Author: Jonah Haefner
%References: Julien Clayton, Lane Carasik, ...
%%%Units%%%
%a = dimensionless transverse pitch
%b = dimensionless longitudinal pitch
%v = the free stream fluid velocity in m/s
%rho = density in kg/m^3
%u = dynamic viscosity in pa*s
%N = number of rows in the tube bundle
%D_tube = The diamter of the tubes in the bundle in m
%Will work for values of b = 1.25, 1.5, or 2
%Reynolds number needs to be below 150000 and greater than E2
%coefficients for Euler number (calculated using the power series)
%coefficients come from here: http://www.thermopedia.com/content/1211/#TUBE_BANKS_CROSSFLOW_OVER_FIG2
% These are valid for Reynolds numbers between 2E3 and 2E6 %
function [dP_total, Re, v_mean,Eu] = StaggeredPressureDrop(a,b,v,rho,u,N,D_tube, Re)
x = double((a)./(b)); %Used for correction factor k_1 which I don't have data for.
%Mean Velocity Calculations. Found on same website as above
if a <= (2*b^2 -.5)
v_mean = v.*(a./(a-1));
elseif a > (2*b^2 -.5)
v_mean = v.*(a./(sqrt(4*b^2+a^2)-2))
end
% Coefficients, c_i, to generate pressure drop coefficients for equilateral triangle banks.
if Re < 1E3
c_0 = [.795,.683,.343]; %b = 1.25, 1.5, and 2
c_1 = [.247E3,.111E3,.303E3]; %b = 1.25, 1.5, and 2
c_2 = [.335E3,-.973E2,-.717E5]; %b = 1.25, 1.5, and 2
c_3 = [-.155E4,-.426E3,.88E7]; %b = 1.25, 1.5, and 2
c_4 = [.241E4,.574E3,-.38E9]; %b = 1.25, 1.5, and 2
elseif Re >= 1E3 && Re < 1E4
c_0 = [.245,.203,.343]; %b = 1.25, 1.5, and 2
c_1 = [.339E4, .248E4, .303E3 ]; %b = 1.25, 1.5, and 2
c_2 = [-.984E7, -.758E7, -.717E5]; %b = 1.25, 1.5, and 2
c_3 = [.132E11, .104E11, .88E7]; %b = 1.25, 1.5, and 2
c_4 = [-.599E13, -.482E13, -.38E9]; %b = 1.25, 1.5, and 2
elseif Re >= 1E4
c_0 = [.245, .203, .162 ]; %b = 1.25, 1.5, and 2
c_1 = [.339E4, .248E4, .181E4 ]; %b = 1.25, 1.5, and 2
c_2 = [-.984E7, -.758E7, .792E8]; %b = 1.25, 1.5, and 2
c_3 = [.132E11, .104E11, -.165E13]; %b = 1.25, 1.5, and 2
c_4 = [-.599E13, -.482E13, .872E16]; %b = 1.25, 1.5, and 2
end
% Assigning correct values to each tube spacing
if (b == 1.25)
i = 1;
else if (b == 1.5)
i = 2;
else if (b == 2)
i = 3;
end
end
end
%%%%%%%%% Correction Factors %%%%%%%%%%
%k_1 is the influence of pitch ratio
%Will add later if data can be found
%k_2 = Influence of Temperature on Fluid properties. Neglected
% k_3 is Entry length effects
%Entry loss coefficients (Re < 1E2 but < 1E4)
el_1 = [1.4, 1.3, 1.2, 1.1, 1, 1, 1];
%Entry loss coefficients (Re > 1E4 but < 1E6)
el_2 = [1.1, 1.05, 1, 1, 1, 1, 1];
%Entry loss coefficients (Re > 1E6)
el_3 = [.25, .45, .6, .65, .7, .75, .8];
k_3 = 1; %Setting for tubes > 7
if (N < 7 && N > 0 && Re < 1E4 && Re > 1E2)
k_3 = el_1(N);
elseif (N < 7 && N > 0 && Re < 1E6 && Re >= 1E4)
k_3 = el_2(N);
elseif (N < 7 && N > 0 && Re > 1E6)
k_3 = el_3(N);
end
%Power series for Euler number per row. From same website as above.
Eu_p = (c_0(i)./Re.^0)+(c_1(i)./Re.^1)+(c_2(i)./Re.^2)+(c_3(i)./Re.^3)+(c_4(i)./Re.^4);
%%%Corrected Euler Number
Eu = Eu_p.*k_3; %.*k_1;
%Using the relation Eu = dP/((1/2)*rho*v^2)
dP = Eu.*((rho.*v_mean.^2)./2); %Pressure drop per row
dP_total = dP.*N/1000; %pressure drop across 10 rows expressed in kPa
end
|
github
|
lcarasik/TORCHE-master
|
InlinePressureDrop.m
|
.m
|
TORCHE-master/LEGACY/MATLAB/InlinePressureDrop.m
| 3,484 |
utf_8
|
8101bcce59d041d275ebc71899c2eacc
|
%Original Author: Julien Clayton
%Last Modified: 7/9/2016
%Most Recent Author: Jonah Haefner
%All Authors: Jonah Haefner, Julien Clayton, Lane Carasik, ...
%%%Units%%%
%a = dimensionless transverse pitch
%b = dimensionless longitudinal pitch
%v = the free stream fluid velocity in m/s
%rho = density in g/cm^3
%u = dynamic viscosity in pa*s
%N = number of rows in the tube bundle
%D_tube = The diamter of the tubes in the bundle in m
%Will work for values of b = 1.25, 1.5, or 2
%Reynolds number needs to be below 150000
function [dP_total, Re, v_mean,Eu] = InlinePressureDrop(a,b,v,rho,u,N,D_tube, Re)
x = double((a-1)./(b-1));
rho = rho*1000; %g/cm^3 ---> kg/m^3(density)
v_mean = v.*(a./(a-1)); %mean flow velocity in min XSection of tube bank (Zukauska's book assumes avg flow velocity is approx. max velocity)
%Re = double((rho.*D_tube.*v_mean)./u); %MinXS Reynolds number (if not already known)
%coefficients for Euler number (calculated using the power series)
%coefficients come from here: http://www.thermopedia.com/content/1211/#TUBE_BANKS_CROSSFLOW_OVER_FIG2
% These are valid for Reynolds numbers between 2E3 and 2E6 %
if Re > 2E3
c_0 = [.267, .235, .247]; %b = 1.25, 1.5, and 2
c_1 = [.249E4, .197E4, -.595]; %b = 1.25, 1.5, and 2
c_2 = [-.927E7, -.124E8, .15]; %b = 1.25, 1.5, and 2
c_3 = [.1E11, .312E11, -.137]; %b = 1.25, 1.5, and 2
c_4 = [0, -.274E14, .396]; %b = 1.25, 1.5, and 2
elseif Re <= 800 && Re > 3
c_0 = [.272, .263, .188]; %b = 1.25, 1.5, and 2
c_1 = [.207E3, .867E2, 56.6]; %b = 1.25, 1.5, and 2
c_2 = [.102E3, -.202, -646]; %b = 1.25, 1.5, and 2
c_3 = [-.286E3, 0, 6010]; %b = 1.25, 1.5, and 2
c_4 = [0, 0, -18300]; %b = 1.25, 1.5, and 2
elseif Re <= 2E3 && Re > 800
c_0 = [.272, .263, .247]; %b = 1.25, 1.5, and 2
c_1 = [.207E3, .867E2, 56.6-(4.766E-2*Re)]; %b = 1.25, 1.5, and 2
c_2 = [.102E3, -.202, .15]; %b = 1.25, 1.5, and 2
c_3 = [-.286E3, 0, -.137]; %b = 1.25, 1.5, and 2
c_4 = [0, 0, .396]; %b = 1.25, 1.5, and 2
%There may be errors when b=2 and Re < 800 but didn't input for code
%simplicity.
end
%%%%%%%%% Correction Factors %%%%%%%%%%
% Non-rectangular bundle % (valid up to Reynolds numbers of 150000)
k_1 = 1;
if x ~= 1.00
if (Re >= 1000 && Re < 10000)
k_1 = .9849.*x.^(-.8129);
else if (Re >= 10000 && Re < 70000)
k_1 = .9802.*x.^(-.7492);
else if (Re >= 70000 && Re < 150000)
k_1 = .988.*x.^(-.6388);
end
end
end
end
%%% Entry losses %%%
%Entry loss coefficients (Re > 1E4 but < 1E6)
el_1 = [1.9, 1.1, 1, 1, 1, 1, 1];
%Entry loss coefficients (Re > 1E6)
el_2 = [2.7, 1.8, 1.5, 1.4, 1.3, 1.2, 1.2];
if (b == 1.25)
i = 1;
else if (b == 1.5)
i = 2;
else if (b == 2)
i = 3;
end
end
end
k_3 = 1;
if (N < 7 && N > 0 && Re < 1E6 && Re > 1E2)
k_3 = el_1(N);
else if (N < 7 && N > 0 && Re >= 1E6)
k_3 = el_2(N);
else if (Re <= 1E2)
disp('Reynolds number needs to be greater than 100')
%break
end
end
end
%Power series for Euler number per row. From same website as above.
Eu_p = (c_0(i)./Re.^0)+(c_1(i)./Re.^1)+(c_2(i)./Re.^2)+(c_3(i)./Re.^3)+(c_4(i)./Re.^4);
%%%Corrected Euler Number%%%
Eu = Eu_p.*k_3.*k_1;
%Using the relation Eu = dP/((1/2)*rho*v^2)
dP = Eu.*((rho.*v_mean.^2)./2); %Pressure drop per row
dP_total = dP.*N/1000; %pressure drop across 10 rows expressed in kPa
end
|
github
|
ubiquiti/ubnt_libjingle-main
|
readDetection.m
|
.m
|
ubnt_libjingle-main/modules/audio_processing/transient/test/readDetection.m
| 927 |
utf_8
|
f6af5020971d028a50a4d19a31b33bcb
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [d, t] = readDetection(file, fs, chunkSize)
%[d, t] = readDetection(file, fs, chunkSize)
%
%Reads a detection signal from a DAT file.
%
%d: The detection signal.
%t: The respective time vector.
%
%file: The DAT file where the detection signal is stored in float format.
%fs: The signal sample rate in Hertz.
%chunkSize: The chunk size used for the detection in seconds.
fid = fopen(file);
d = fread(fid, inf, 'float');
fclose(fid);
t = 0:(1 / fs):(length(d) * chunkSize - 1 / fs);
d = d(floor(t / chunkSize) + 1);
|
github
|
ubiquiti/ubnt_libjingle-main
|
readPCM.m
|
.m
|
ubnt_libjingle-main/modules/audio_processing/transient/test/readPCM.m
| 821 |
utf_8
|
76b2955e65258ada1c1e549a4fc9bf79
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [x, t] = readPCM(file, fs)
%[x, t] = readPCM(file, fs)
%
%Reads a signal from a PCM file.
%
%x: The read signal after normalization.
%t: The respective time vector.
%
%file: The PCM file where the signal is stored in int16 format.
%fs: The signal sample rate in Hertz.
fid = fopen(file);
x = fread(fid, inf, 'int16');
fclose(fid);
x = x - mean(x);
x = x / max(abs(x));
t = 0:(1 / fs):((length(x) - 1) / fs);
|
github
|
ubiquiti/ubnt_libjingle-main
|
plotDetection.m
|
.m
|
ubnt_libjingle-main/modules/audio_processing/transient/test/plotDetection.m
| 923 |
utf_8
|
e8113bdaf5dcfe4f50200a3ca29c3846
|
%
% Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [] = plotDetection(PCMfile, DATfile, fs, chunkSize)
%[] = plotDetection(PCMfile, DATfile, fs, chunkSize)
%
%Plots the signal alongside the detection values.
%
%PCMfile: The file of the input signal in PCM format.
%DATfile: The file containing the detection values in binary float format.
%fs: The sample rate of the signal in Hertz.
%chunkSize: The chunk size used to compute the detection values in seconds.
[x, tx] = readPCM(PCMfile, fs);
[d, td] = readDetection(DATfile, fs, chunkSize);
plot(tx, x, td, d);
|
github
|
ubiquiti/ubnt_libjingle-main
|
apmtest.m
|
.m
|
ubnt_libjingle-main/modules/audio_processing/test/apmtest.m
| 9,874 |
utf_8
|
17ad6af59f6daa758d983dd419e46ff0
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function apmtest(task, testname, filepath, casenumber, legacy)
%APMTEST is a tool to process APM file sets and easily display the output.
% APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs:
% 'test' Processes the files to produce test output.
% 'list' Prints a list of cases in the test set, preceded by their
% CASENUMBERs.
% 'show' Uses spclab to show the test case specified by the
% CASENUMBER parameter.
%
% using a set of test files determined by TESTNAME:
% 'all' All tests.
% 'apm' The standard APM test set (default).
% 'apmm' The mobile APM test set.
% 'aec' The AEC test set.
% 'aecm' The AECM test set.
% 'agc' The AGC test set.
% 'ns' The NS test set.
% 'vad' The VAD test set.
%
% FILEPATH specifies the path to the test data files.
%
% CASENUMBER can be used to select a single test case. Omit CASENUMBER,
% or set to zero, to use all test cases.
%
if nargin < 5 || isempty(legacy)
% Set to true to run old VQE recordings.
legacy = false;
end
if nargin < 4 || isempty(casenumber)
casenumber = 0;
end
if nargin < 3 || isempty(filepath)
filepath = 'data/';
end
if nargin < 2 || isempty(testname)
testname = 'all';
end
if nargin < 1 || isempty(task)
task = 'test';
end
if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show')
error(['TASK ' task ' is not recognized']);
end
if casenumber == 0 && strcmp(task, 'show')
error(['CASENUMBER must be specified for TASK ' task]);
end
inpath = [filepath 'input/'];
outpath = [filepath 'output/'];
refpath = [filepath 'reference/'];
if strcmp(testname, 'all')
tests = {'apm','apmm','aec','aecm','agc','ns','vad'};
else
tests = {testname};
end
if legacy
progname = './test';
else
progname = './process_test';
end
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
if legacy
farFile = 'vqeFar.pcm';
nearFile = 'vqeNear.pcm';
eventFile = 'vqeEvent.dat';
delayFile = 'vqeBuf.dat';
driftFile = 'vqeDrift.dat';
else
farFile = 'apm_far.pcm';
nearFile = 'apm_near.pcm';
eventFile = 'apm_event.dat';
delayFile = 'apm_delay.dat';
driftFile = 'apm_drift.dat';
end
simulateMode = false;
nErr = 0;
nCases = 0;
for i=1:length(tests)
simulateMode = false;
if strcmp(tests{i}, 'apm')
testdir = ['apm/'];
outfile = ['out'];
if legacy
opt = ['-ec 1 -agc 2 -nc 2 -vad 3'];
else
opt = ['--no_progress -hpf' ...
' -aec --drift_compensation -agc --fixed_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apm-swb')
simulateMode = true;
testdir = ['apm-swb/'];
outfile = ['out'];
if legacy
opt = ['-fs 32000 -ec 1 -agc 2 -nc 2'];
else
opt = ['--no_progress -fs 32000 -hpf' ...
' -aec --drift_compensation -agc --adaptive_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apmm')
testdir = ['apmm/'];
outfile = ['out'];
opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ...
'--ns_moderate'];
else
error(['TESTNAME ' tests{i} ' is not recognized']);
end
inpathtest = [inpath testdir];
outpathtest = [outpath testdir];
refpathtest = [refpath testdir];
if ~exist(inpathtest,'dir')
error(['Input directory ' inpathtest ' does not exist']);
end
if ~exist(refpathtest,'dir')
warning(['Reference directory ' refpathtest ' does not exist']);
end
[status, errMsg] = mkdir(outpathtest);
if (status == 0)
error(errMsg);
end
[nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ...
progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy);
if strcmp(task, 'test') || strcmp(task, 'show')
system(['rm ' farFile]);
system(['rm ' nearFile]);
if simulateMode == false
system(['rm ' eventFile]);
system(['rm ' delayFile]);
system(['rm ' driftFile]);
end
end
end
if ~strcmp(task, 'list')
if nErr == 0
fprintf(1, '\nAll files are bit-exact to reference\n', nErr);
else
fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr);
end
end
function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ...
outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ...
legacy)
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
dirs = dir(inpath);
nDirs = 0;
nErrOut = nErr;
for i=3:length(dirs) % skip . and ..
nDirs = nDirs + dirs(i).isdir;
end
if nDirs == 0
nCases = nCases + 1;
if casenumber == nCases || casenumber == 0
if strcmp(task, 'list')
fprintf([num2str(nCases) '. ' outfile '\n'])
else
vadoutfile = ['vad_' outfile '.dat'];
outfile = [outfile '.pcm'];
% Check for VAD test
vadTest = 0;
if ~isempty(findstr(opt, '-vad'))
vadTest = 1;
if legacy
opt = [opt ' ' outpath vadoutfile];
else
opt = [opt ' --vad_out_file ' outpath vadoutfile];
end
end
if exist([inpath 'vqeFar.pcm'])
system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]);
elseif exist([inpath 'apm_far.pcm'])
system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]);
end
if exist([inpath 'vqeNear.pcm'])
system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]);
elseif exist([inpath 'apm_near.pcm'])
system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]);
end
if exist([inpath 'vqeEvent.dat'])
system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]);
elseif exist([inpath 'apm_event.dat'])
system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]);
end
if exist([inpath 'vqeBuf.dat'])
system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]);
elseif exist([inpath 'apm_delay.dat'])
system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]);
end
if exist([inpath 'vqeSkew.dat'])
system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]);
elseif exist([inpath 'vqeDrift.dat'])
system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]);
elseif exist([inpath 'apm_drift.dat'])
system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]);
end
if simulateMode == false
command = [progname ' -o ' outpath outfile ' ' opt];
else
if legacy
inputCmd = [' -in ' nearFile];
else
inputCmd = [' -i ' nearFile];
end
if exist([farFile])
if legacy
inputCmd = [' -if ' farFile inputCmd];
else
inputCmd = [' -ir ' farFile inputCmd];
end
end
command = [progname inputCmd ' -o ' outpath outfile ' ' opt];
end
% This prevents MATLAB from using its own C libraries.
shellcmd = ['bash -c "unset LD_LIBRARY_PATH;'];
fprintf([command '\n']);
[status, result] = system([shellcmd command '"']);
fprintf(result);
fprintf(['Reference file: ' refpath outfile '\n']);
if vadTest == 1
equal_to_ref = are_files_equal([outpath vadoutfile], ...
[refpath vadoutfile], ...
'int8');
if ~equal_to_ref
nErr = nErr + 1;
end
end
[equal_to_ref, diffvector] = are_files_equal([outpath outfile], ...
[refpath outfile], ...
'int16');
if ~equal_to_ref
nErr = nErr + 1;
end
if strcmp(task, 'show')
% Assume the last init gives the sample rate of interest.
str_idx = strfind(result, 'Sample rate:');
fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17));
fprintf('Using %d Hz\n', fs);
if exist([farFile])
spclab(fs, farFile, nearFile, [refpath outfile], ...
[outpath outfile], diffvector);
%spclab(fs, diffvector);
else
spclab(fs, nearFile, [refpath outfile], [outpath outfile], ...
diffvector);
%spclab(fs, diffvector);
end
end
end
end
else
for i=3:length(dirs)
if dirs(i).isdir
[nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ...
refpath,[outfile '_' dirs(i).name], progname, opt, ...
simulateMode, nErr, nCases, task, casenumber, legacy);
end
end
end
nErrOut = nErr;
function [are_equal, diffvector] = ...
are_files_equal(newfile, reffile, precision, diffvector)
are_equal = false;
diffvector = 0;
if ~exist(newfile,'file')
warning(['Output file ' newfile ' does not exist']);
return
end
if ~exist(reffile,'file')
warning(['Reference file ' reffile ' does not exist']);
return
end
fid = fopen(newfile,'rb');
new = fread(fid,inf,precision);
fclose(fid);
fid = fopen(reffile,'rb');
ref = fread(fid,inf,precision);
fclose(fid);
if length(new) ~= length(ref)
warning('Reference is not the same length as output');
minlength = min(length(new), length(ref));
new = new(1:minlength);
ref = ref(1:minlength);
end
diffvector = new - ref;
if isequal(new, ref)
fprintf([newfile ' is bit-exact to reference\n']);
are_equal = true;
else
if isempty(new)
warning([newfile ' is empty']);
return
end
snr = snrseg(new,ref,80);
fprintf('\n');
are_equal = false;
end
|
github
|
ubiquiti/ubnt_libjingle-main
|
parse_delay_file.m
|
.m
|
ubnt_libjingle-main/modules/audio_coding/neteq/test/delay_tool/parse_delay_file.m
| 6,405 |
utf_8
|
4cc70d6f90e1ca5901104f77a7e7c0b3
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function outStruct = parse_delay_file(file)
fid = fopen(file, 'rb');
if fid == -1
error('Cannot open file %s', file);
end
textline = fgetl(fid);
if ~strncmp(textline, '#!NetEQ_Delay_Logging', 21)
error('Wrong file format');
end
ver = sscanf(textline, '#!NetEQ_Delay_Logging%d.%d');
if ~all(ver == [2; 0])
error('Wrong version of delay logging function')
end
start_pos = ftell(fid);
fseek(fid, -12, 'eof');
textline = fgetl(fid);
if ~strncmp(textline, 'End of file', 21)
error('File ending is not correct. Seems like the simulation ended abnormally.');
end
fseek(fid,-12-4, 'eof');
Npackets = fread(fid, 1, 'int32');
fseek(fid, start_pos, 'bof');
rtpts = zeros(Npackets, 1);
seqno = zeros(Npackets, 1);
pt = zeros(Npackets, 1);
plen = zeros(Npackets, 1);
recin_t = nan*ones(Npackets, 1);
decode_t = nan*ones(Npackets, 1);
playout_delay = zeros(Npackets, 1);
optbuf = zeros(Npackets, 1);
fs_ix = 1;
clock = 0;
ts_ix = 1;
ended = 0;
late_packets = 0;
fs_now = 8000;
last_decode_k = 0;
tot_expand = 0;
tot_accelerate = 0;
tot_preemptive = 0;
while not(ended)
signal = fread(fid, 1, '*int32');
switch signal
case 3 % NETEQ_DELAY_LOGGING_SIGNAL_CLOCK
clock = fread(fid, 1, '*float32');
% keep on reading batches of M until the signal is no longer "3"
% read int32 + float32 in one go
% this is to save execution time
temp = [3; 0];
M = 120;
while all(temp(1,:) == 3)
fp = ftell(fid);
temp = fread(fid, [2 M], '*int32');
end
% back up to last clock event
fseek(fid, fp - ftell(fid) + ...
(find(temp(1,:) ~= 3, 1 ) - 2) * 2 * 4 + 4, 'cof');
% read the last clock value
clock = fread(fid, 1, '*float32');
case 1 % NETEQ_DELAY_LOGGING_SIGNAL_RECIN
temp_ts = fread(fid, 1, 'uint32');
if late_packets > 0
temp_ix = ts_ix - 1;
while (temp_ix >= 1) && (rtpts(temp_ix) ~= temp_ts)
% TODO(hlundin): use matlab vector search instead?
temp_ix = temp_ix - 1;
end
if temp_ix >= 1
% the ts was found in the vector
late_packets = late_packets - 1;
else
temp_ix = ts_ix;
ts_ix = ts_ix + 1;
end
else
temp_ix = ts_ix;
ts_ix = ts_ix + 1;
end
rtpts(temp_ix) = temp_ts;
seqno(temp_ix) = fread(fid, 1, 'uint16');
pt(temp_ix) = fread(fid, 1, 'int32');
plen(temp_ix) = fread(fid, 1, 'int16');
recin_t(temp_ix) = clock;
case 2 % NETEQ_DELAY_LOGGING_SIGNAL_FLUSH
% do nothing
case 4 % NETEQ_DELAY_LOGGING_SIGNAL_EOF
ended = 1;
case 5 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE
last_decode_ts = fread(fid, 1, 'uint32');
temp_delay = fread(fid, 1, 'uint16');
k = find(rtpts(1:(ts_ix - 1))==last_decode_ts,1,'last');
if ~isempty(k)
decode_t(k) = clock;
playout_delay(k) = temp_delay + ...
5 * fs_now / 8000; % add overlap length
last_decode_k = k;
end
case 6 % NETEQ_DELAY_LOGGING_SIGNAL_CHANGE_FS
fsvec(fs_ix) = fread(fid, 1, 'uint16');
fschange_ts(fs_ix) = last_decode_ts;
fs_now = fsvec(fs_ix);
fs_ix = fs_ix + 1;
case 7 % NETEQ_DELAY_LOGGING_SIGNAL_MERGE_INFO
playout_delay(last_decode_k) = playout_delay(last_decode_k) ...
+ fread(fid, 1, 'int32');
case 8 % NETEQ_DELAY_LOGGING_SIGNAL_EXPAND_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_expand = tot_expand + temp / (fs_now / 1000);
end
case 9 % NETEQ_DELAY_LOGGING_SIGNAL_ACCELERATE_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_accelerate = tot_accelerate + temp / (fs_now / 1000);
end
case 10 % NETEQ_DELAY_LOGGING_SIGNAL_PREEMPTIVE_INFO
temp = fread(fid, 1, 'int32');
if last_decode_k ~= 0
tot_preemptive = tot_preemptive + temp / (fs_now / 1000);
end
case 11 % NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF
optbuf(last_decode_k) = fread(fid, 1, 'int32');
case 12 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE_ONE_DESC
last_decode_ts = fread(fid, 1, 'uint32');
k = ts_ix - 1;
while (k >= 1) && (rtpts(k) ~= last_decode_ts)
% TODO(hlundin): use matlab vector search instead?
k = k - 1;
end
if k < 1
% packet not received yet
k = ts_ix;
rtpts(ts_ix) = last_decode_ts;
late_packets = late_packets + 1;
end
decode_t(k) = clock;
playout_delay(k) = fread(fid, 1, 'uint16') + ...
5 * fs_now / 8000; % add overlap length
last_decode_k = k;
end
end
fclose(fid);
outStruct = struct(...
'ts', rtpts, ...
'sn', seqno, ...
'pt', pt,...
'plen', plen,...
'arrival', recin_t,...
'decode', decode_t,...
'fs', fsvec(:),...
'fschange_ts', fschange_ts(:),...
'playout_delay', playout_delay,...
'tot_expand', tot_expand,...
'tot_accelerate', tot_accelerate,...
'tot_preemptive', tot_preemptive,...
'optbuf', optbuf);
|
github
|
ubiquiti/ubnt_libjingle-main
|
plot_neteq_delay.m
|
.m
|
ubnt_libjingle-main/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m
| 5,967 |
utf_8
|
cce342fed6406ef0f12d567fe3ab6eef
|
%
% Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
%
function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin)
% InfoStruct = plot_neteq_delay(delayfile)
% InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds)
%
% Henrik Lundin, 2006-11-17
% Henrik Lundin, 2011-05-17
%
try
s = parse_delay_file(delayfile);
catch
error(lasterr);
end
delayskip=0;
noplot=0;
arg_ptr=1;
delaypoints=[];
s.sn=unwrap_seqno(s.sn);
while arg_ptr+1 <= nargin
switch lower(varargin{arg_ptr})
case {'skipdelay', 'delayskip'}
% skip a number of seconds in the beginning when calculating delays
delayskip = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
case 'noplot'
noplot=1;
arg_ptr = arg_ptr + 1;
case {'get_delay', 'getdelay'}
% return a vector of delay values for the points in the given vector
delaypoints = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
otherwise
warning('Unknown switch %s\n', varargin{arg_ptr});
arg_ptr = arg_ptr + 1;
end
end
% find lost frames that were covered by one-descriptor decoding
one_desc_ix=find(isnan(s.arrival));
for k=1:length(one_desc_ix)
ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts)));
s.sn(one_desc_ix(k))=s.sn(ix)+1;
s.pt(one_desc_ix(k))=s.pt(ix);
s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix);
end
% remove duplicate received frames that were never decoded (RED codec)
if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts)))
ix=find(isfinite(s.decode));
s.sn=s.sn(ix);
s.ts=s.ts(ix);
s.arrival=s.arrival(ix);
s.playout_delay=s.playout_delay(ix);
s.pt=s.pt(ix);
s.optbuf=s.optbuf(ix);
plen=plen(ix);
s.decode=s.decode(ix);
end
% find non-unique sequence numbers
[~,un_ix]=unique(s.sn);
nonun_ix=setdiff(1:length(s.sn),un_ix);
if ~isempty(nonun_ix)
warning('RTP sequence numbers are in error');
end
% sort vectors
[s.sn,sort_ix]=sort(s.sn);
s.ts=s.ts(sort_ix);
s.arrival=s.arrival(sort_ix);
s.decode=s.decode(sort_ix);
s.playout_delay=s.playout_delay(sort_ix);
s.pt=s.pt(sort_ix);
send_t=s.ts-s.ts(1);
if length(s.fs)<1
warning('No info about sample rate found in file. Using default 8000.');
s.fs(1)=8000;
s.fschange_ts(1)=min(s.ts);
elseif s.fschange_ts(1)>min(s.ts)
s.fschange_ts(1)=min(s.ts);
end
end_ix=length(send_t);
for k=length(s.fs):-1:1
start_ix=find(s.ts==s.fschange_ts(k));
send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000;
s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000;
s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000;
end_ix=start_ix-1;
end
tot_time=max(send_t)-min(send_t);
seq_ix=s.sn-min(s.sn)+1;
send_t=send_t+max(min(s.arrival-send_t),0);
plot_send_t=nan*ones(max(seq_ix),1);
plot_send_t(seq_ix)=send_t;
plot_nw_delay=nan*ones(max(seq_ix),1);
plot_nw_delay(seq_ix)=s.arrival-send_t;
cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID
if noplot==0
h=plot(plot_send_t/1000,plot_nw_delay);
set(h,'color',0.75*[1 1 1]);
hold on
if any(s.optbuf~=0)
peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values
no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix);
h1=plot(send_t(cng_ix(peak_ix))/1000,...
s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),...
'r.');
h2=plot(send_t(cng_ix(no_peak_ix))/1000,...
s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),...
'g.');
set([h1, h2],'markersize',1)
end
%h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix));
h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix));
set(h,'linew',1.5);
hold off
ax1=axis;
axis tight
ax2=axis;
axis([ax2(1:3) ax1(4)])
end
% calculate delays and other parameters
delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 );
use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames...
intersect(find(isfinite(s.decode)),... % ... that did arrive ...
(delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds
mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix));
neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix));
Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1;
nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack;
neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack;
delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,...
'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,...
'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),...
'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,...
'filename',delayfile,'units','ms','fs',unique(s.fs));
if not(isempty(delaypoints))
delayvalues=interp1(send_t(cng_ix),...
s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),...
delaypoints,'nearest',NaN);
else
delayvalues=[];
end
% SUBFUNCTIONS %
function y=unwrap_seqno(x)
jumps=find(abs((diff(x)-1))>65000);
while ~isempty(jumps)
n=jumps(1);
if x(n+1)-x(n) < 0
% negative jump
x(n+1:end)=x(n+1:end)+65536;
else
% positive jump
x(n+1:end)=x(n+1:end)-65536;
end
jumps=find(abs((diff(x(n+1:end))-1))>65000);
end
y=x;
return;
|
github
|
ubiquiti/ubnt_libjingle-main
|
rtpAnalyze.m
|
.m
|
ubnt_libjingle-main/tools_webrtc/matlab/rtpAnalyze.m
| 7,892 |
utf_8
|
46e63db0fa96270c14a0c205bbab42e4
|
function rtpAnalyze( input_file )
%RTP_ANALYZE Analyze RTP stream(s) from a txt file
% The function takes the output from the command line tool rtp_analyze
% and analyzes the stream(s) therein. First, process your rtpdump file
% through rtp_analyze (from command line):
% $ out/Debug/rtp_analyze my_file.rtp my_file.txt
% Then load it with this function (in Matlab):
% >> rtpAnalyze('my_file.txt')
% Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
%
% Use of this source code is governed by a BSD-style license
% that can be found in the LICENSE file in the root of the source
% tree. An additional intellectual property rights grant can be found
% in the file PATENTS. All contributing project authors may
% be found in the AUTHORS file in the root of the source tree.
[SeqNo,TimeStamp,ArrTime,Size,PT,M,SSRC] = importfile(input_file);
%% Filter out RTCP packets.
% These appear as RTP packets having payload types 72 through 76.
ix = not(ismember(PT, 72:76));
fprintf('Removing %i RTCP packets\n', length(SeqNo) - sum(ix));
SeqNo = SeqNo(ix);
TimeStamp = TimeStamp(ix);
ArrTime = ArrTime(ix);
Size = Size(ix);
PT = PT(ix);
M = M(ix);
SSRC = SSRC(ix);
%% Find streams.
[uSSRC, ~, uix] = unique(SSRC);
% If there are multiple streams, select one and purge the other
% streams from the data vectors. If there is only one stream, the
% vectors are good to use as they are.
if length(uSSRC) > 1
for i=1:length(uSSRC)
uPT = unique(PT(uix == i));
fprintf('%i: %s (%d packets, pt: %i', i, uSSRC{i}, ...
length(find(uix==i)), uPT(1));
if length(uPT) > 1
fprintf(', %i', uPT(2:end));
end
fprintf(')\n');
end
sel = input('Select stream number: ');
if sel < 1 || sel > length(uSSRC)
error('Out of range');
end
ix = find(uix == sel);
% This is where the data vectors are trimmed.
SeqNo = SeqNo(ix);
TimeStamp = TimeStamp(ix);
ArrTime = ArrTime(ix);
Size = Size(ix);
PT = PT(ix);
M = M(ix);
SSRC = SSRC(ix);
end
%% Unwrap SeqNo and TimeStamp.
SeqNoUW = maxUnwrap(SeqNo, 65535);
TimeStampUW = maxUnwrap(TimeStamp, 4294967295);
%% Generate some stats for the stream.
fprintf('Statistics:\n');
fprintf('SSRC: %s\n', SSRC{1});
uPT = unique(PT);
if length(uPT) > 1
warning('This tool cannot yet handle changes in codec sample rate');
end
fprintf('Payload type(s): %i', uPT(1));
if length(uPT) > 1
fprintf(', %i', uPT(2:end));
end
fprintf('\n');
fprintf('Packets: %i\n', length(SeqNo));
SortSeqNo = sort(SeqNoUW);
fprintf('Missing sequence numbers: %i\n', ...
length(find(diff(SortSeqNo) > 1)));
fprintf('Duplicated packets: %i\n', length(find(diff(SortSeqNo) == 0)));
reorderIx = findReorderedPackets(SeqNoUW);
fprintf('Reordered packets: %i\n', length(reorderIx));
tsdiff = diff(TimeStampUW);
tsdiff = tsdiff(diff(SeqNoUW) == 1);
[utsdiff, ~, ixtsdiff] = unique(tsdiff);
fprintf('Common packet sizes:\n');
for i = 1:length(utsdiff)
fprintf(' %i samples (%i%%)\n', ...
utsdiff(i), ...
round(100 * length(find(ixtsdiff == i))/length(ixtsdiff)));
end
%% Trying to figure out sample rate.
fs_est = (TimeStampUW(end) - TimeStampUW(1)) / (ArrTime(end) - ArrTime(1));
fs_vec = [8, 16, 32, 48];
fs = 0;
for f = fs_vec
if abs((fs_est-f)/f) < 0.05 % 5% margin
fs = f;
break;
end
end
if fs == 0
fprintf('Cannot determine sample rate. I get it to %.2f kHz\n', ...
fs_est);
fs = input('Please, input a sample rate (in kHz): ');
else
fprintf('Sample rate estimated to %i kHz\n', fs);
end
SendTimeMs = (TimeStampUW - TimeStampUW(1)) / fs;
fprintf('Stream duration at sender: %.1f seconds\n', ...
(SendTimeMs(end) - SendTimeMs(1)) / 1000);
fprintf('Stream duration at receiver: %.1f seconds\n', ...
(ArrTime(end) - ArrTime(1)) / 1000);
fprintf('Clock drift: %.2f%%\n', ...
100 * ((ArrTime(end) - ArrTime(1)) / ...
(SendTimeMs(end) - SendTimeMs(1)) - 1));
fprintf('Sent average bitrate: %i kbps\n', ...
round(sum(Size) * 8 / (SendTimeMs(end)-SendTimeMs(1))));
fprintf('Received average bitrate: %i kbps\n', ...
round(sum(Size) * 8 / (ArrTime(end)-ArrTime(1))));
%% Plots.
delay = ArrTime - SendTimeMs;
delay = delay - min(delay);
delayOrdered = delay;
delayOrdered(reorderIx) = nan; % Set reordered packets to NaN.
delayReordered = delay(reorderIx); % Pick the reordered packets.
sendTimeMsReordered = SendTimeMs(reorderIx);
% Sort time arrays in packet send order.
[~, sortix] = sort(SeqNoUW);
SendTimeMs = SendTimeMs(sortix);
Size = Size(sortix);
delayOrdered = delayOrdered(sortix);
figure
plot(SendTimeMs / 1000, delayOrdered, ...
sendTimeMsReordered / 1000, delayReordered, 'r.');
xlabel('Send time [s]');
ylabel('Relative transport delay [ms]');
title(sprintf('SSRC: %s', SSRC{1}));
SendBitrateKbps = 8 * Size(1:end-1) ./ diff(SendTimeMs);
figure
plot(SendTimeMs(1:end-1)/1000, SendBitrateKbps);
xlabel('Send time [s]');
ylabel('Send bitrate [kbps]');
end
%% Subfunctions.
% findReorderedPackets returns the index to all packets that are considered
% old compared with the largest seen sequence number. The input seqNo must
% be unwrapped for this to work.
function reorderIx = findReorderedPackets(seqNo)
largestSeqNo = seqNo(1);
reorderIx = [];
for i = 2:length(seqNo)
if seqNo(i) < largestSeqNo
reorderIx = [reorderIx; i]; %#ok<AGROW>
else
largestSeqNo = seqNo(i);
end
end
end
%% Auto-generated subfunction.
function [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = ...
importfile(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as column vectors.
% [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME) Reads
% data from text file FILENAME for the default selection.
%
% [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME,
% STARTROW, ENDROW) Reads data from rows STARTROW through ENDROW of text
% file FILENAME.
%
% Example:
% [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] =
% importfile('rtpdump_recv.txt',2, 123);
%
% See also TEXTSCAN.
% Auto-generated by MATLAB on 2015/05/28 09:55:50
%% Initialize variables.
if nargin<=2
startRow = 2;
endRow = inf;
end
%% Format string for each line of text:
% column1: double (%f)
% column2: double (%f)
% column3: double (%f)
% column4: double (%f)
% column5: double (%f)
% column6: double (%f)
% column7: text (%s)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%5f%11f%11f%6f%6f%3f%s%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ...
'Delimiter', '', 'WhiteSpace', '', 'HeaderLines', startRow(1)-1, ...
'ReturnOnError', false);
for block=2:length(startRow)
frewind(fileID);
dataArrayBlock = textscan(fileID, formatSpec, ...
endRow(block)-startRow(block)+1, 'Delimiter', '', 'WhiteSpace', ...
'', 'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
for col=1:length(dataArray)
dataArray{col} = [dataArray{col};dataArrayBlock{col}];
end
end
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Allocate imported array to column variable names
SeqNo = dataArray{:, 1};
TimeStamp = dataArray{:, 2};
SendTime = dataArray{:, 3};
Size = dataArray{:, 4};
PT = dataArray{:, 5};
M = dataArray{:, 6};
SSRC = dataArray{:, 7};
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
medianFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/medianFilter.m
| 1,257 |
utf_8
|
0b72b3acb2875c12e7bbffaab80de4c7
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Median filter implementation using MATLAB's processing toolbox
%
% [outputImage] = medianFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% windowSize: mask size
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = medianFilter(inputImage, windowSize, plotResult)
%Using processing toolbox
outputImage = medfilt2(inputImage,[windowSize windowSize]);
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
gaussianFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/gaussianFilter.m
| 2,259 |
utf_8
|
ca917db62ab616e6c91bb43b33d93bf0
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
%
% Gaussian filter. Takes an image and the mask radius and
% oupts the filtered image in same type
%
% [outputImage] = gaussianFilter(inputImage,type,radius,order,plotResult)
%
% Parameters
% inputImage------: input image (any type)
% type------------: 'low' for low-pass or 'high' for high-pass
% radius----------: filter radius
% order-----------: radius of ideal filter
% plotResult------: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage-----: output image (same type as inputImage)
%
function [outputImage] = gaussianFilter(inputImage,type, radius,plotResult)
[rows, cols] = size (inputImage);
if radius > min(rows,cols)
radius = min(rows,cols);
end
[x,y] = meshgrid(-floor(cols/2):floor(cols-1)/2, ...
-floor(rows/2):floor(rows-1)/2);
%Gaussian filter transfer function
% mask = (1./(2*pi*radius^2)).*(exp((-(x.^2+y.^2))./(2.*radius^2)));
mask = (exp((-(x.^2+y.^2))./(2.*radius^2)));
mask = mask - min(mask(:));
mask = mask ./ max(mask(:));
if strcmp(type,'high')
mask = 1 - mask;
elseif strcmp(type,'low')
mask = mask;
end
DFT = fft2(inputImage);
DFTC = fftshift(DFT);
GC = mask .* DFTC;
G = ifftshift(GC);
outputImage = real(ifft2(G));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure()
imshow(mask)
title 'Mask used'
figure ();
im1 = subplot (2,2,1);
imshow (inputImage);
title 'Input Image'
subplot (2,2,2);
imshow (log(1+abs(DFTC)) , [3, 10]);
title 'Input Image FFT'
im2 = subplot (2,2,3);
imshow (outputImage);
title 'Output Image'
subplot (2,2,4);
imshow (log(1+abs(GC)) , [3, 10]);
title 'Output Image FFT'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
quadTreeSegmentation.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/quadTreeSegmentation.m
| 3,239 |
utf_8
|
3274f9ad9bc68bf061743b266ae4ddb0
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
%
% quadTreeSegmentation performs a tree segmentation on input image. Tree
% segmentation segments the input image in squares with similar pixels
%
% [outputImage] = quadTreeSegmentation(inputImage,plotResult)
%
% Parameters
% inputImage------: input image (any type)
% threshold-------: higher value means bigger segmentation
% plotResult------: 'yes' or 'no'. Plot input and output images.
%
% Outputs
% outputImage-----: output image (same type as inputImage)
%
function [outputImage] = quadTreeSegmentation(inputImage,threshold,plotResult)
%This is really bad implementation, but in order to do quadtree
%segmentation, one must assure that the image is a power of 2. So... if
%anyone ever read this, please, do it in a more elegant way.
[rows, cols] = size (inputImage);
if rows > cols
disp('Not square image');
toPad = rows - cols;
padding = zeros(rows,round(toPad/2));
inputImage = [padding,inputImage,padding];
elseif cols > rows
disp('Not square image');
toPad = cols - rows;
padding = zeros(round(toPad/2),cols);
inputImage = [padding;inputImage;padding];
end
%triming excess
[rows, cols] = size (inputImage);
if rows>cols
inputImage = inputImage(1:end-1,:);
elseif cols>rows
inputImage = inputImage(:,1:end-1);
end
%at this point, the image is a square
r = rem(sqrt(length(inputImage)),2);
%if not a perfect square
if r ~= 0
toPad = abs(pow2(nextpow2(length(inputImage))) - length(inputImage));
padding = zeros(ceil(toPad/2),length(inputImage));
inputImage = [padding;inputImage;padding];
padding = zeros(length(inputImage),ceil(toPad/2));
inputImage = [padding,inputImage,padding];
%triming excess
[rows, cols] = size (inputImage);
if rem(rows,2) ~= 0
inputImage = inputImage(1:end-1,1:end-1);
end
end
%So, I belive this code will run for every image size
S = qtdecomp(inputImage,threshold);
outputImage = repmat(uint8(0),size(S));
%potential problem: what if the image is really big, like over 9000!!
%generate an array with all pow2. Challenge proposed!
%hint: pow2(length(inputImage))-1 recursively will do it
for dim = [512 256 128 64 32 16 8 4 2 1];
numblocks = length(find(S==dim));
if (numblocks > 0)
values = repmat(uint8(1),[dim dim numblocks]);
values(2:dim,2:dim,:) = 0;
outputImage = qtsetblk(outputImage,S,dim,values);
end
end
outputImage(end,1:end) = 1;
outputImage(1:end,end) = 1;
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow(outputImage,[]);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
butterworthFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/butterworthFilter.m
| 2,213 |
utf_8
|
f1d44f573adf23a13c9e0f0e81480220
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
%
% Butterworth filter. Takes an image and the mask radius and
% oupts the filtered image in same type
%
% [outputImage] = butterworhtFilter(inputImage,type,radius,order,plotResult)
%
% Parameters
% inputImage------: input image (any type)
% type------------: 'low' for low-pass or 'high' for high-pass
% radius----------: filter radius
% order-----------: radius of ideal filter
% plotResult------: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage-----: output image (same type as inputImage)
%
function [outputImage] = butterworthFilter(inputImage,type, radius,...
order,plotResult)
[rows, cols] = size (inputImage);
if radius > min(rows,cols)
radius = min(rows,cols);
end
[x,y] = meshgrid(-floor(cols/2):floor(cols-1)/2, ...
-floor(rows/2):floor(rows-1)/2);
%Butterworth transfer function
if strcmp(type,'high')
mask = 1./(1.+((radius./(x.^2+y.^2).^0.5).^(2*order)));
elseif strcmp(type,'low')
mask = 1./(1.+(((x.^2+y.^2).^0.5./radius).^(2*order)));
end
DFT = fft2(inputImage);
DFTC = fftshift(DFT);
GC = mask .* DFTC;
G = ifftshift(GC);
outputImage = real(ifft2(G));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure()
imshow(mask)
title 'Mask used'
figure ();
im1 = subplot (2,2,1);
imshow (inputImage);
title 'Input Image'
subplot (2,2,2);
imshow (log(1+abs(DFTC)) , [3, 10]);
title 'Input Image FFT'
im2 = subplot (2,2,3);
imshow (outputImage);
title 'Output Image'
subplot (2,2,4);
imshow (log(1+abs(GC)) , [3, 10]);
title 'Output Image FFT'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
idealFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/idealFilter.m
| 2,287 |
utf_8
|
73e9c1c7813ad2acb176585d59cb8aab
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Ideal low pass filter. Takes an image and the mask radius and
% oupts the filtered image in same type
%
% [outputImage] = idealFilter(inputImage, type, radius, plotResult)
%
% Parameters
% inputImage: input image (any type)
% type: 'low' for low-pass or 'high' for high-pass
% radius: radius of ideal filter
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = idealFilter(inputImage, type, radius, plotResult)
[rows, cols] = size (inputImage);
if radius > min(rows,cols)
radius = min(rows,cols);
end
mask = zeros(rows,cols);
%'Drawing' a circle
radius = radius^2;
centerX = rows/2;
centerY = cols/2;
for i = 1 : rows
for j = 1 : cols
dx = i - centerX;
dx = dx^2;
dy = j - centerY;
dy = dy^2;
if strcmp(type,'low')
mask(i, j) = dx + dy <= radius;
elseif strcmp(type,'high')
mask(i, j) = dx + dy >= radius;
end
end;
end;
DFT = fft2(inputImage);
DFTC = fftshift(DFT);
GC = mask .* DFTC;
G = ifftshift(GC);
outputImage = real(ifft2(G));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure()
imshow(mask)
title 'Mask used'
figure ();
im1 = subplot (2,2,1);
imshow (inputImage);
title 'Input Image'
subplot (2,2,2);
imshow (log(1+abs(DFTC)) , [3, 10]);
title 'Input Image FFT'
im2 = subplot (2,2,3);
imshow (outputImage);
title 'Output Image'
subplot (2,2,4);
imshow (log(1+abs(GC)) , [3, 10]);
title 'Output Image FFT'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
k_means.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/k_means.m
| 1,591 |
utf_8
|
0946d0bdb704d4adc3796ad0a8efb53e
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% This script is the one mentioned during the Computerphile's Image
% Segmentation video by Dr. Mike Pound.
%
% Takes a gray-scale input image and performs k-means algorithm on it.
%
% [outputImage] = averageFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% classes: split the image in that many classes
% plotResult: 'yes' or 'no'.
%
% Outputs
% outputImage: output image (same type as inputImage)
%
% Note: maximum iterations was set to 100, so don't try to run this using
% more than a few classes. The output won't be accurate.
%
function [ outputImage ] = k_means( inputImage, classes, plotResult )
im=inputImage;
imflat = double(reshape(im, size(im,1) * size(im,2), 1));
[kIDs] = kmeans(imflat,classes, 'Display', 'iter', 'MaxIter', 100,...
'Start', 'sample');
outputImage = reshape(uint8(kIDs), size(im,1), size(im,2));
outputImage = histeq(outputImage);
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
geoAverageFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/geoAverageFilter.m
| 1,480 |
utf_8
|
30906f3ec1bbcea31846b337cbd915aa
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code.
% Also to Steve Eddins @ Mathworks!
%
% Geometric average filter implementation using MATLAB's processing toolbox
%
% [outputImage] = geoAverageFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% windowSize: mask size
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = geoAverageFilter(inputImage, windowSize, plotResult)
%Using processing toolbox
%For geometric average, it requires double type
image = double(inputImage);
geo_mean = imfilter(log(image), windowSize, 'replicate');
geo_mean = exp(geo_mean);
outputImage = geo_mean .^ (1/numel(windowSize));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
averageFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/averageFilter.m
| 1,290 |
utf_8
|
a1c9d731983b078ec2bfc1447531b091
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Average filter implementation using MATLAB's processing toolbox
%
% [outputImage] = averageFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% windowSize: Mask size
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = averageFilter(inputImage, windowSize, plotResult)
%Using processing toolbox
h = ones(windowSize,windowSize) / windowSize^2;
outputImage = imfilter(inputImage,h);
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
minimumFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/minimumFilter.m
| 1,253 |
utf_8
|
dc2c5c1b743521123a571dd059341a37
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Minimum filter implementation using MATLAB's processing toolbox
%
% [outputImage] = maximumFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% windowSize: mask size
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = minimumFilter(inputImage, windowSize, plotResult)
%Using processing toolbox
outputImage = imerode(inputImage, true(windowSize));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
maximumFilter.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/maximumFilter.m
| 1,254 |
utf_8
|
bbdd97b8ef7a62d5967dfd13de04083f
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Maximum filter implementation using MATLAB's processing toolbox
%
% [outputImage] = maximumFilter(inputImage, windowSize, plotResult)
%
% Parameters
% inputImage: input image (any type)
% windowSize: mask size
% plotResult: 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
function [outputImage] = maximumFilter(inputImage, windowSize, plotResult)
%Using processing toolbox
outputImage = imdilate(inputImage, true(windowSize));
%Same type guaranteed
outputImage = cast(outputImage,class(inputImage));
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
insertNoise.m
|
.m
|
imagens-medicas-2-master/toolbox/matlab/insertNoise.m
| 4,556 |
utf_8
|
77f090eeef512021c89243525ec982d0
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% Ideal high pass filter. Takes in an image and a mask size and
% oupts the filtered image in same type as original one
%
% [outputImage] = idealHighPass(inputImage, radius, plotResult)
%
% Parameters
% inputImage: Input image (any type)
% noiseType: Select one of
% 'Uniform'
% 'Gaussian'
% 'Rayleight'
% 'Exponential'
% 'Gamma'
% 'SaltAndPepper'
% par: Optional. Cell array with noise specific parameters
% plotResult: Optional. 'yes' or 'no'. Plot input and output images with
% respective frequency spectrogram
%
% Outputs
% outputImage: output image (same type as inputImage)
%
% Use example:
% Insert 2% of noise in the image, (1% salt and 1% pepper)
% outputImage = insertNoise(inputImage, 'SaltAndPepper', 'yes',{0.01});
%
% By default, insert 10% of noise in the image, (5% salt and 5% pepper)
% outputImage = insertNoise(inputImage, 'SaltAndPepper');
%
function [outputImage] = insertNoise(inputImage, noiseType, plotResult, par)
%Same type guaranteed
outputImage = inputImage;
outputImage = cast(outputImage,class(inputImage));
switch noiseType
case 'Uniform'
if ~exist('par','var')
par = {0,80};
end
try
uniformNoise = unifrnd(par{1},par{2},size(inputImage));
uniformNoise = cast(uniformNoise,class(inputImage));
outputImage = inputImage + uniformNoise;
catch
disp('Invalid noise parameters');
end
case 'Gaussian'
if ~exist('par','var')
par = {5,30};
end
try
gaussianNoise = normrnd(par{1},par{2},size(inputImage));
gaussianNoise = cast(gaussianNoise,class(inputImage));
outputImage = inputImage + gaussianNoise;
catch
disp('Invalid noise parameters');
end
case 'Rayleight'
if ~exist('par','var')
par = {20};
end
try
rayleightNoise = raylrnd(par{1},size(inputImage));
rayleightNoise = cast(rayleightNoise,class(inputImage));
outputImage = inputImage + rayleightNoise;
catch
disp('Invalid noise parameters');
end
case 'Exponential'
if ~exist('par','var')
par = {5};
end
try
exponentialNoise = exprnd(par{1},size(inputImage));
exponentialNoise = cast(exponentialNoise,class(inputImage));
outputImage = inputImage + exponentialNoise;
catch
disp('Invalid noise parameters');
end
case 'Gamma'
if ~exist('par','var')
par = {1,8};
end
try
gammalNoise = gamrnd(par{1},par{2},size(inputImage));
gammalNoise = cast(gammalNoise,class(inputImage));
outputImage = inputImage + gammalNoise;
catch
disp('Invalid noise parameters');
end
case 'SaltAndPepper'
if ~exist('par','var')
par = {0.05};
end
try
SaltAndPepperNoise = rand(size(inputImage));
pepperProportion = par{1};
saltProportion = 1 - pepperProportion;
pepper = find(SaltAndPepperNoise <= pepperProportion);
outputImage(pepper) = 0;
salt = find(SaltAndPepperNoise >= saltProportion);
%Max value of variable type
outputImage(salt) = intmax(class(inputImage));
catch
disp('Invalid noise parameters');
end
otherwise
disp('Not valid type');
end
if ~exist('plotResult','var')
plotResult = 'no';
end
if strcmp(plotResult,'yes')
figure ();
im1 = subplot (1,2,1);
imshow (inputImage);
title 'Input Image'
im2 = subplot (1,2,2);
imshow (outputImage);
title 'Output Image'
linkaxes([im1,im2],'xy')
end
end
|
github
|
italogsfernandes/imagens-medicas-2-master
|
IM2_app.m
|
.m
|
imagens-medicas-2-master/Apps/mIM2_app/IM2_app.m
| 13,520 |
utf_8
|
80c70f2ad2b7d9634737a578730ca7fc
|
%% Ronaldo Sena
% [email protected]
% December 2017
% Use it as you please. If we meet some day, and you think
% this stuff was helpful, you can buy me a beer
% Shout out to professor Ana Claudia, for the inspiring code
%
% GUI to process medical images
%
%
% CONFIGURAÇÕES INCIAIS
%
%
function varargout = IM2_app(varargin)
% IM2_APP MATLAB code for IM2_app.fig
% IM2_APP, by itself, creates a new IM2_APP or raises the existing
% singleton*.
%
% H = IM2_APP returns the handle to a new IM2_APP or the handle to
% the existing singleton*.
%
% IM2_APP('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in IM2_APP.M with the given input arguments.
%
% IM2_APP('Property','Value',...) creates a new IM2_APP or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before IM2_app_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to IM2_app_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 IM2_app
% Last Modified by GUIDE v2.5 25-Dec-2017 21:40:39
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @IM2_app_OpeningFcn, ...
'gui_OutputFcn', @IM2_app_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 IM2_app is made visible.
function IM2_app_OpeningFcn(hObject, eventdata, handles, varargin)
global raio ordem limiarArvore limiarCrescimento limiarKmeans ...
mascara seeds comparar segmentar filtrar Kclasses seedsInv;
handles.output = hObject;
% set(handles.panel_filtros,'visible','off')
% set(handles.panel_segmentacao,'visible','on')
raio = str2double(handles.text_raio.String);
ordem = str2double(handles.text_ordem.String);
comparar = 0;
segmentar = 0;
filtrar = 1;
limiarArvore = 0.27;
limiarCrescimento = 0.27;
limiarKmeans = 0.27;
mascara = str2double(handles.text_mascara.String);
Kclasses = 3;
seeds = [];
seedsInv = [];
handles.panel_filtros.Visible = 'on';
handles.panel_segmentacao.Visible = 'off';
% Caminho a partir desta pasta para a pasta onde estão as imagens
% utilizadas
addpath('../../toolbox/matlab')
% Update handles structure
guidata(hObject, handles);
function varargout = IM2_app_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
function edit2_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%
%
% CONFIGURAÇÕES INCIAIS
%
%
%
%
% INSERIR RUIDOS
%
%
function pushbutton_salEpimenta_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'SaltAndPepper',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_gamma_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'Gamma',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_exponential_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'Exponential',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_rayleight_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'Rayleight',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_gaussiano_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'Gaussian',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_uniforme_Callback(hObject, eventdata, handles)
global imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
imagemSaida = insertNoise(imagemSaida,'Uniform',plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
%
%
% INSERIR RUIDOS
%
%
%
%
% FILTROS ESPACIAIS
%
%
function pushbutton_media_Callback(hObject, eventdata, handles)
global imagemSaida comparar mascara;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
[imagemSaida] = averageFilter(imagemSaida, mascara,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_mediana_Callback(hObject, eventdata, handles)
global imagemSaida comparar mascara;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
[imagemSaida] = medianFilter(imagemSaida, mascara,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_minimo_Callback(hObject, eventdata, handles)
global imagemSaida comparar mascara;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
[imagemSaida] = minimumFilter(imagemSaida, mascara,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_maximo_Callback(hObject, eventdata, handles)
global imagemSaida comparar mascara;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
[imagemSaida] = maximumFilter(imagemSaida, mascara,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
%
%
% FILTROS ESPACIAIS
%
%
%
%
% CONFIGURAÇÕES
%
%
function text_mascara_Callback(hObject, eventdata, handles)
global mascara;
mascara = str2double(get(hObject,'String'));
function text_mascara_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function pushbutton_carregar_Callback(hObject, eventdata, handles)
global imagemSaida imagemEntrada;
[FileName,PathName] = uigetfile({'*.*', 'All Files (*.*)'}, ...
'Escolha uma imagem');
imagemEntrada = imread([PathName FileName]);
imagemSaida = imagemEntrada;
axes(handles.axes_saida);
imshow(imagemSaida);
axes(handles.axes_original);
imshow(imagemEntrada);
linkaxes([handles.axes_original,handles.axes_saida],'xy')
function pushbutton_reset_Callback(hObject, eventdata, handles)
global imagemEntrada imagemSaida seeds seedsInv;
imagemSaida = imagemEntrada;
axes(handles.axes_saida);
cla
axes(handles.axes_original);
cla
axes(handles.axes_saida);
imshow(imagemSaida);
axes(handles.axes_original);
imshow(imagemEntrada);
seeds = [];
seedsInv = [];
function radiobutton_filtragem_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
handles.panel_segmentacao.Visible = 'off';
handles.panel_filtros.Visible = 'on';
end
function radiobutton_segmentacao_Callback(hObject, eventdata, handles)
if get(hObject,'Value')
set(handles.panel_filtros,'visible','off')
set(handles.panel_segmentacao,'visible','on')
end
function radiobutton_comparar_Callback(hObject, eventdata, handles)
global comparar;
comparar = get(hObject,'Value');
%
%
% CONFIGURAÇÕES
%
%
%
%
% FILTROS DE FREQUÊNCIA
%
%
function pushbutton_ideal_Callback(hObject, eventdata, handles)
global raio imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
if handles.radiobutton_passaAlta.Value
tipo = 'high';
elseif handles.radiobutton_passaBaixa.Value
tipo = 'low';
end
[imagemSaida] = idealFilter(imagemSaida, tipo, raio, plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_butter_Callback(hObject, eventdata, handles)
global raio ordem imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
if handles.radiobutton_passaAlta.Value
tipo = 'high';
elseif handles.radiobutton_passaBaixa.Value
tipo = 'low';
end
[imagemSaida] = butterworthFilter(imagemSaida,tipo,raio,ordem,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function pushbutton_gauss_Callback(hObject, eventdata, handles)
global raio imagemSaida comparar;
if comparar == 0
plotResult = 'no';
else
plotResult = 'yes';
end
if handles.radiobutton_passaAlta.Value
tipo = 'high';
elseif handles.radiobutton_passaBaixa.Value
tipo = 'low';
end
[imagemSaida] = gaussianFilter(imagemSaida,tipo,raio,plotResult);
axes(handles.axes_saida);
imshow(imagemSaida);
function text_raio_Callback(hObject, eventdata, handles)
global raio;
raio = str2double(get(hObject,'String'));
function text_raio_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function text_ordem_Callback(hObject, eventdata, handles)
global ordem;
ordem = str2double(get(hObject,'String'));
function text_ordem_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%
%
% FILTROS DE FREQUÊNCIA
%
%
%
%
% SEGMENTAÇÃO
%
%
% --- Executes on button press in pushbutton_lancarSementes.
function pushbutton_lancarSementes_Callback(hObject, eventdata, handles)
global seeds seedsInv imagemSaida imagemMarcada;
imagemMarcada = [];
% Hint: get(hObject,'Value') returns toggle state of checkbox_sementes
p = ginput(1);
y = round(axes2pix(size(imagemSaida, 2), get(handles.axes_original.Children, 'XData'), p(2)));
x = round(axes2pix(size(imagemSaida, 1), get(handles.axes_original.Children, 'YData'), p(1)));
seeds = [seeds; [x y]];
disp('xablaus');
imagemMarcada = insertMarker(imagemSaida,seeds);
% inverte para proxima funcao
seedsInv = [seedsInv; [y x]];
axes(handles.axes_saida);
imshow(imagemMarcada);
function pushbutton_arvore_Callback(hObject, eventdata, handles)
global imagemSaida limiarArvore;
quadTreeSegmentation(imagemSaida',limiarArvore,'yes');
function pushbutton_crescimento_Callback(hObject, eventdata, handles)
global seedsInv imagemSaida limiar;
limiarCrescimento = round(limiar*255);
% imagemMarcada = handles.axes_input.Children.CData;
axes(handles.axes_saida);
cla
imshow(imagemSaida);
for i=1:size(seedsInv,1);
poly = regionGrowing(imagemSaida, [seedsInv(i,:) 1], limiarCrescimento);
hold on
plot(poly(:,1), poly(:,2), 'LineWidth', 2)
end
hold off
function pushbutton_kmeans_Callback(hObject, eventdata, handles)
global Kclasses imagemSaida;
k_means(imagemSaida,Kclasses,'yes');
function slider_arvore_Callback(hObject, eventdata, handles)
global limiarArvore;
limiarArvore = get(hObject,'Value');
set(handles.label_arvore,'String',num2str(limiarArvore));
function slider_arvore_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
function slider_kmeans_Callback(hObject, eventdata, handles)
global limiarKmeans;
limiarKmeans = get(hObject,'Value');
set(handles.label_kmeans,'String',num2str(limiarKmeans));
function slider_kmeans_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
function slider_crescimento_Callback(hObject, eventdata, handles)
global limiarCrescimento;
limiarCrescimento = get(hObject,'Value');
set(handles.label_crescimento,'String',num2str(limiarCrescimento));
function slider_crescimento_CreateFcn(hObject, eventdata, handles)
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
function text_classes_Callback(hObject, eventdata, handles)
global Kclasses;
Kclasses = str2double(get(hObject,'String'));
function text_classes_CreateFcn(hObject, eventdata, handles)
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
%
%
% SEGMENTAÇÃO
%
%
function pushbutton_histograma_Callback(hObject, eventdata, handles)
global imagemEntrada imagemSaida;
figure ();
im1 = subplot (1,2,1);
imhist(imagemEntrada);
title 'Input Image'
im2 = subplot (1,2,2);
imhist(imagemSaida);
title 'Output Image'
linkaxes([im1,im2],'xy')
function pushbutton_equalizar_Callback(hObject, eventdata, handles)
global imagemSaida;
imagemSaida = histeq(imagemSaida);
axes(handles.axes_saida);
imshow(imagemSaida);
|
github
|
namanUIUC/NonlinearComponentAnalysis-master
|
swap.m
|
.m
|
NonlinearComponentAnalysis-master/src/KPCA-projectcode/swap.m
| 203 |
utf_8
|
6a8e44f4608a6dbb307c50c538b7eb4e
|
%%FUNCTION USED TO SWAP WHILE SORTING (Not relevent for pca)
function x = swap(x,i,j)
% Swap x(i) and x(j)
% Note: In practice, x should be passed by reference
val = x(i);
x(i) = x(j);
x(j) = val;
end
|
github
|
namanUIUC/NonlinearComponentAnalysis-master
|
kpca_code.m
|
.m
|
NonlinearComponentAnalysis-master/src/KPCA-projectcode/kpca_code.m
| 2,884 |
utf_8
|
defa54c6d19a8a59ee48eaee69be9ead
|
clear all;
clc;
% loading data
load('usps_all')
% TEST DATA : M(observation/sample points) x N(features/dimensions)
X_test = double(data(:, 1:800, 1)');
% Center Data
mu = mean(X_test);
X_centered = bsxfun(@minus, X_test, mu);
% Define kernel
kernel = 'linear';
n= 3;
%Def: M and N
M = size(X_centered,1);
N = size(X_centered,2);
% Create matrix K
switch kernel
case 'poly'
K = (X_centered*X_centered').^n;
case 'linear'
K = X_centered*X_centered';
case 'gauss'
% Using the Gaussian Kernel to construct the Kernel K
% K(x,y) = -exp((x-y)^2/(sigma)^2)
% K is a symmetric Kernel
K = zeros(M,M);
for row = 1:(M)
for col = 1:row
temp = sum(((X_centered(row,:) - X_centered(col,:)).^2));
K(row,col) = exp(-temp); % sigma = 1
end
end
K = K + K';
% Dividing the diagonal element by 2 since it has been added to itself
for row = 1:(M)
K(row,row) = K(row,row)/2;
end
otherwise
error('Unknown kernel function.');
end
% Centering of K in F space
one_mat = ones(size(K))./M;
K_center = K - one_mat*K - K*one_mat + one_mat*K*one_mat;
% Eigen values and vectors for K_centered (i.e. lamda.M and alpha)
[V_K,D_K] = eig(K_center);
eigval_K = real(diag(D_K));
eigvec_K = real(V_K);
% Sorting Eigen Vectors w.r.t Eigen Values of K
% (Bubble sort)
Sorted_eigval_K=eigval_K;
Sorted_eigvec_K=eigvec_K;
n = length(Sorted_eigval_K);
while (n > 0)
% Iterate through x
nnew = 0;
for i = 2:n
% Swap elements in wrong order
if (Sorted_eigval_K(i) > Sorted_eigval_K(i - 1))
Sorted_eigval_K = swap(Sorted_eigval_K,i,i - 1);
Sorted_eigvec_K(:,[i-1 i]) = Sorted_eigvec_K(:,[i i-1]);
nnew = i;
end
end
n = nnew;
end
% Calculate lamda
lamda = (Sorted_eigval_K)./M;
% Select 99 percent of the cumulative eigen values (dim = dimensions k)
dim = 0;
percent = 0;
for indx=1:size(lamda)
if percent < 0.90
dim = dim + 1;
else
break;
end
percent = sum(lamda(1:indx))/sum(lamda);
end
% Normalize all the alpha (i.e. normalizing all significant sorted eigen vectors of K )
lamda = lamda(1:dim);
alpha = Sorted_eigvec_K(:,1:dim);
for indx=1:dim
alpha(:,indx)=alpha(:,indx)./dot(alpha(:,indx),alpha(:,indx));
alpha(:,indx)=alpha(:,indx)./sqrt(lamda(indx));
end
% Project data
data_out = zeros(dim,M);
for count = 1:dim
data_out(count,:) = alpha(:,count)'*K_center';
end
data_out = data_out';
% FUNCTION USED TO SWAP WHILE SORTING (Not relevent for pca)
function x = swap(x,i,j)
% Swap x(i) and x(j)
% Note: In practice, x should be passed by reference
val = x(i);
x(i) = x(j);
x(j) = val;
end
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
pr_evaluate_voxel_logit.m
|
.m
|
vesicle-cnn-2-master/evaluation/pr_evaluate_voxel_logit.m
| 3,951 |
utf_8
|
1a0b911f8f934aa2eefb05476c76396d
|
function [metrics] = pr_evaluate_voxel_logit(path, h5File, channel, pp, fileOut)
% Takes inputs of the predicted volume (matrix or location) and the truth
% volume (matrix or location) and sweeps through thresholds of probability,
% evalating F1 (and F1 related metrics) at each bin. Then saves this data
% to saveloc.
evaluation_bins = 500;
test = false;
val = false;
train = false;
state = '';
detectFileOnes = h5read(strcat(path, h5File), strcat('/', channel, '/ones'));
detectFileZeros = h5read(strcat(path, h5File), strcat('/', channel, '/zeros'));
sDataTest = h5read(strcat(path, h5File), strcat('/', channel, '/truth'));
% Are we test? in which case load the preoptimized.
if contains(h5File, 'test')
% Load optimized settings.
load(strcat(path, '/', channel, '_voxel_metrics_optimized_val.mat'))
metrics.thresholds = thresholds;
test = true;
state = 'test';
evaluation_bins = 1;
echo_to_file(sprintf('Beginning application of optimized parameters to test set (pr_evaluation_voxel_logit.m; test).\n'), fileOut);
else
metrics.thresholds = linspace(-10,10,evaluation_bins);
echo_to_file(sprintf('Beginning voxel-level hyperparameter optimization (pr_evaluation_voxel_logit.m; val).\n'), fileOut);
if contains(h5File, 'train')
train = true;
state = 'train';
else
val = true;
state = 'val';
end
end
st = tic;
precision = zeros(evaluation_bins,1);
recall = zeros(evaluation_bins,1);
TP = zeros(evaluation_bins,1);
FP = zeros(evaluation_bins,1);
FN = zeros(evaluation_bins,1);
F1 = zeros(evaluation_bins,1);
parfor i = 1:evaluation_bins
metricsTemp = pr_voxel(detectFileOnes>detectFileZeros+metrics.thresholds(i), sDataTest);
precision(i) = metricsTemp.precision;
recall(i) = metricsTemp.recall;
TP(i) = metricsTemp.TP;
FP(i) = metricsTemp.FP;
FN(i) = metricsTemp.FN;
F1(i) = metricsTemp.F1;
end
metrics.precision = precision;
metrics.recall = recall;
metrics.TP = TP;
metrics.FP = FP;
metrics.FN = FN;
metrics.F1 = F1;
t = toc(st);
save(strcat(path, '/', channel, '_voxel_metrics_full_', state), 'metrics')
if val
echo_to_file(sprintf('Voxel-level hyperparameter optimization complete, time elapsed: %0.2f.\n', t), fileOut);
[~, optimalBin] = max(metrics.F1);
thresholds = [metrics.thresholds(optimalBin)];
precision = [metrics.precision(optimalBin)];
recall = [metrics.recall(optimalBin)];
TP = [metrics.TP(optimalBin)];
FP = [metrics.FP(optimalBin)];
FN = [metrics.FN(optimalBin)];
F1 = [metrics.F1(optimalBin)];
echo_to_file(sprintf('Validation complete.\n F1: %f\n Precision: %f\n Recall: %f\n Threshold %f\n\n\n',F1,precision,recall, thresholds), fileOut);
save(strcat(path, '/', channel, '_voxel_metrics_optimized_val'), 'thresholds', 'precision', 'recall', 'F1');
end
if test
[~, optimalBin] = max(metrics.F1);
thresholds = [metrics.thresholds(optimalBin)];
precision = [metrics.precision(optimalBin)];
recall = [metrics.recall(optimalBin)];
TP = [metrics.TP(optimalBin)];
FP = [metrics.FP(optimalBin)];
FN = [metrics.FN(optimalBin)];
F1 = [metrics.F1(optimalBin)];
echo_to_file(sprintf('Application to test set complete.\n F1: %f\n Precision: %f\n Recall: %f\n Threshold %f\n\n\n',F1,precision,recall, thresholds), fileOut);
end
function [metrics] = pr_voxel(detectVol, truthVol)
% Adapted from W. Gray Roncal - 02.12.2015
% Feedback welcome and encouraged. Let's make this better!
% Other options (size filters, morphological priors, etc. can be added.
%
TP = sum(sum(sum((detectVol ~= 0) & (truthVol ~= 0))));
FP = sum(sum(sum((detectVol ~= 0) & (truthVol == 0))));
FN = sum(sum(sum((detectVol == 0) & (truthVol ~= 0))));
metrics.precision = TP./(TP+FP);
metrics.recall = TP./(TP+FN);
metrics.TP = TP;
metrics.FP = FP;
metrics.FN = FN;
metrics.F1 = 2*metrics.precision*metrics.recall/(metrics.precision+metrics.recall);
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
bwdistsc1.m
|
.m
|
vesicle-cnn-2-master/Prior_art/vesicle/packages/vesiclerf/tools/bwdistsc/bwdistsc1.m
| 19,630 |
utf_8
|
003a8729f0ccdb35a49d8429ea605c64
|
function D=bwdistsc1(bw,aspect,maxval)
% D=BWDISTSC1(BW,ASPECT,MAXVAL)
% BWDISTSC1 computes Euclidean distance transform of a binary 3D image
% BW out to a specified value MAXVAL. This allows accelerating the
% calculations in some cases with strongly nonconvex geometries, if the
% distance transform only needs to be calculated out to a specific value.
% The distance transform assigns to each pixel in BW a number that is
% the distance from that pixel to the nearest nonzero pixel in BW. BW may
% be a 3D array or a cell array of 2D slices. BWDISTSC1 can also accept
% regular 2D images. ASPECT is a 3-component vector defining the aspect
% ratios to use when calculating the distances in BW. If ASPECT is not set,
% isotropic aspect ratio [1 1 1] is used. If MAXVAL is specified, the
% distance transform will be only calculated out to the value MAXVAL.
%
% BWDISTSC1 uses the same algorithm as BWDISTSC but without forward-
% backward scan.
%
% BWDISTSC1 tries to use MATLAB's bwdist for 2D scans if possible, which
% is faster. Otherwise BWDISTSC1 will use its own algorithm for 2D scans.
% Also incorporates the fix for Matlab version detection bug in the
% original BWDISTSC contributed by Tudor Dima.
%
%(c) Yuriy Mishchenko HHMI JFRC Chklovskii Lab JUL 2007
% This function written Yuriy Mishchenko JUL 2011
% This function updated Yuriy Mishchenko SEP 2013
% This code is free for use or modifications, just please give credit where
% appropriate. If you modify the code or fix bugs, please drop me a message
% at [email protected].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Scan algorithms below use the following Lema: %
% LEMA: let F(X,z) be lower envelope of a family of parabola: %
% F(X,z)=min_{k} [G(X)+(z-k)^2]; %
% and let H_k(X,z)=A(X)+(z-k)^2 be a parabola. %
% Then for H_k(X,z)==F(X,z) at each X there exist at most %
% two solutions k1<k2 such that H_k12(X,z)=F(X,z), and %
% H_k(X,z)<F(X,z) is restricted to at most k1<k2. %
% Here X is any-dimensional coordinate. %
% %
% Thus, simply scan away from any z such that H_k(X,z)<F(X,z) %
% in either direction as long as H_k(X,z)<F(X,z) and update %
% F(X,z). Note that need to properly choose starting point; %
% starting point is any z such that H_k(X,z)<F(X,z); z==k is %
% usually, but not always the starting point! %
% %
% Citation: %
% Mishchenko Y. (2013) A function for fastcomputation of large %
% discrete Euclidean distance transforms in three or more %
% dimensions in Matlab. Signal, Image and Video Processing %
% DOI: 10.1007/s11760-012-0419-9. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parse inputs
if(nargin<2 || isempty(aspect)) aspect=[1 1 1]; end
if(nargin<3 || isempty(maxval)) maxval=Inf; end
% establish (once) whether we will use the "regionprops";
% on Matlab versions earlier than 7.3 regionprops is too slow for simply
% collecting regions, as we want, and internal algorithm will be faster
UseRegionProps = exist('regionprops', 'file') && VersionNewerThan(7.3);
% need this to remove pixels from consideration in the scan if current
% distance becomes greater than MAXVAL
maxval2=maxval^2;
% determine geometry of the data
if(iscell(bw)) shape=[size(bw{1}),length(bw)]; else shape=size(bw); end
% correct this for 2D data
if(length(shape)==2) shape=[shape,1]; end
if(length(aspect)==2) aspect=[aspect,1]; end
% allocate internal memory
D=cell(1,shape(3)); for k=1:shape(3) D{k}=zeros(shape(1:2)); end
%%%%%%%%%%%%% scan along XY %%%%%%%%%%%%%%%%
for k=1:shape(3)
if(iscell(bw)) bwXY=bw{k}; else bwXY=bw(:,:,k); end
DXY=zeros(shape(1:2));
% if can, use 2D bwdist from image processing toolbox
if(exist('bwdist') && aspect(1)==aspect(2))
DXY=aspect(1)^2*bwdist(bwXY).^2;
DXY(DXY>maxval2)=Inf;
else % if not, use full XY-scan
%%%%%%%%%%%%%%% X-SCAN %%%%%%%%%%%%%%%
% reference nearest bwXY "on"-pixel in x direction downward:
% scan bottow-up, copy x-reference from previous row unless
% there is bwXY "on"-pixel in that point in current row
xlower=repmat(Inf,shape(1:2));
xlower(1,find(bwXY(1,:)))=1; % fill in first row
for i=2:shape(1)
xlower(i,:)=xlower(i-1,:); % copy previous row
xlower(i,find(bwXY(i,:)))=i;% unless there is pixel
end
% reference nearest bwXY "on"-pixel in x direction upward:
xupper=repmat(Inf,shape(1:2));
xupper(end,find(bwXY(end,:)))=shape(1);
for i=shape(1)-1:-1:1
xupper(i,:)=xupper(i+1,:);
xupper(i,find(bwXY(i,:)))=i;
end
% find pixels for which distance needs to be updated
idx=find(~bwXY); [x,y]=ind2sub(shape(1:2),idx);
% set distance as the shortest to upward or to downward
DXY(idx)=aspect(1)^2*min((x-xlower(idx)).^2,(x-xupper(idx)).^2);
DXY(DXY>maxval2)=Inf;
%%%%%%%%%%%%%%% Y-SCAN %%%%%%%%%%%%%%%
% this will be the envelop
D1=repmat(Inf,shape(1:2));
% these will be the references to parabolas defining the envelop
DK=repmat(Inf,shape(1:2));
for i=1:shape(2)
% need to select starting point for each X:
% * starting point should be below current envelop
% * i0==i is not necessarily a starting point
% * there is at most one starting point
% * there may be no starting point
% i0 is the starting points for each X: i0(X) is the first
% y-index such that parabola from line i is below the envelop
% first guess is the current y-line
i0=repmat(i,shape(1),1);
% some auxiliary datasets
d0=DXY(:,i);
x=(1:shape(1))';
% L0 indicates for which X starting point had been fixed
L0=isinf(d0);
while(~isempty(find(~L0,1)))
% reference starting points in DXY
idx=sub2ind(shape(1:2),x(~L0),i0(~L0));
% these are current best parabolas for starting points
ik=DK(idx);
% these are new values from parabola from line #i
dtmp=d0(~L0)+aspect(2)^2*(i0(~L0)-i).^2;
dtmp(dtmp>maxval2)=Inf;
% these starting points are OK - below the envelop
L=D1(idx)>dtmp; D1(idx(L))=dtmp(L);
% points which are still above the envelop but ik==i0,
% will not get any better, so fix them as well
L=isinf(dtmp) | L | (ik==i0(~L0));
% all other points are not OK, need new starting point:
% starting point should be at least below parabola
% beating us at current choice of i0
% solve quadratic equation to find where this happens
ik=(ik-i);
di=(D1(idx(~L))-dtmp(~L))./ik(~L)/2/aspect(2)^2;
% should select next highest index to the equality
di=fix(di)+sign(di);
% the new starting points
idx=find(~L0);
i0(idx(~L))=i0(idx(~L))+di;
% update L0 to indicate which points we've fixed
L0(~L0)=L; L0(idx(~L))=(di==0);
% points that went out can't get better;
% fix them as well
L=(i0<1) | (i0>shape(2)); i0(L)=i;
L0(L)=1;
end
% will keep track along which X should keep updating distance
map_lower=true(shape(1),1);
map_upper=true(shape(1),1);
% scan from starting points for each X i0 in increments of 1
di=0; % distance from current y-line
eols=2; % end-of-line-scan flag
while(eols)
eols=2;
di=di+1;
dtmp=repmat(Inf,shape(1),1);
% select X which can be updated for di<0;
% i.e. X which had been below envelop all way till now
x=find(map_lower);
if(~isempty(x))
% prevent index dropping below 1st
L=i0(map_lower)-di>=1;
map_lower(map_lower)=L;
% select pixels (X,i0(X)-di)
idx=sub2ind(shape(1:2),x(L),i0(map_lower)-di);
if(~isempty(idx))
dtmp=d0(map_lower)+...
aspect(2)^2*(i0(map_lower)-di-i).^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with i0-di
L=D1(idx)>dtmp;
map_lower(map_lower)=L;
D1(idx(L))=dtmp(L);
DK(idx(L))=i;
end
else % if this is empty, get ready to quit
eols=eols-1;
end
% select X which can be updated for di>0;
% i.e. X which had been below envelop all way till now
x=find(map_upper);
if(~isempty(x))
% prevent index from going over array limits
L=i0(map_upper)+di<=shape(2);
map_upper(map_upper)=L;
% select pixels (X,i0(X)+di)
idx=sub2ind(shape(1:2),x(L),i0(map_upper)+di);
if(~isempty(idx))
dtmp=d0(map_upper)+...
aspect(2)^2*(i0(map_upper)+di-i).^2;
dtmp(dtmp>maxval2)=Inf;
% check which pixels are to be updated with i0+di
L=D1(idx)>dtmp;
map_upper(map_upper)=L;
D1(idx(L))=dtmp(L);
DK(idx(L))=i;
end
else % if this is empty, get ready to quit
eols=eols-1;
end
end
end
DXY=D1;
end
D{k}=DXY;
end
%%%%%%%%%%%%% scan along Z %%%%%%%%%%%%%%%%
% this will be the envelop of the parabolas centered on different Z points
D1=cell(size(D));
for k=1:shape(3) D1{k}=repmat(Inf,shape(1:2)); end
% these will be the Z-references for the parabolas forming the envelop
DK=cell(size(D));
for k=1:shape(3) DK{k}=repmat(Inf,shape(1:2)); end
% start building the envelope
for k=1:shape(3)
% need to select starting point for each XY:
% * starting point should be below already existing current envelop
% * k0==k is not necessarily a starting point
% * there may be no starting point
% j0 is the starting points for each XY: k0(XY) is the first
% z-index such that the parabola from slice k gets below the envelop
% for initial starting point, guess the current slice k
k0=repmat(k,shape(1:2));
% L0 indicates which starting points had been found so far
L0=isinf(D{k});
while(~isempty(find(~L0,1)))
% because of using cells, need to explicitly scan in Z
% to avoid repetitious searches in k0, parse first
ss = getregions(k0, UseRegionProps);
for kk=1:shape(3)
% these are starting points @kk which had not been set yet
if(kk<=length(ss)) idx=ss(kk).PixelIdxList; else idx=[]; end
idx=idx(~L0(idx));
if(isempty(idx)) continue; end
% these are currently the best parabolas for slice kk
ik=DK{kk}(idx);
% these are new distances for points in kk from parabolas in k
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these points are below current envelop, OK starting points
L=D1{kk}(idx)>dtmp; D1{kk}(idx(L))=dtmp(L);
% these points are not OK, but since ik==k0
% can't get any better, so remove them as well from search
L=L | (ik==kk) | isinf(dtmp);
% all other points are not OK, need new starting point:
% starting point should be at least below the parabola
% beating us at current choice of k0, thus make new guess for k
ik=(ik-k);
dk=(D1{kk}(idx(~L))-dtmp(~L))./ik(~L)/2/aspect(3)^2;
dk=fix(dk)+sign(dk);
k0(idx(~L))=k0(idx(~L))+dk;
% update starting points that had been fixed in this pass
L0(idx)=L;
L0(idx(~L))=(dk==0);
% points that went out of boundaries can't get better, fix them
L=(k0<1) | (k0>shape(3));
L0(L)=1;
k0(L)=k;
end
end
% map_lower/map_upper keeps track of which pixels yet can be updated
% with new distances, i.e., all such XY that had been below envelop
% for all dk up to now, for dk<0/dk>0 respectively
map_lower=true(shape(1:2));
map_upper=true(shape(1:2));
% parse different values in k0 to avoid repetitious searching below
ss = getregions(k0, UseRegionProps);
% scan away from starting points in increments of 1
dk=0; % distance from current xy-slice
eols=2; % end-of-scan flag
while(eols)
eols=2;
dk=dk+1;
dtmp=repmat(Inf,shape(1:2));
if(~isempty(find(map_lower,1)))
% prevent index from going over the boundaries
L=k0(map_lower)-dk>=1;
map_lower(map_lower)=L;
% need to explicitly scan in Z because of using cell-arrays
for kk=1:shape(3)
% get all XY such that k0-dk==kk
if(kk+dk<=length(ss) & kk+dk>=1)
idx=ss(kk+dk).PixelIdxList;
else
idx=[];
end
idx=idx(map_lower(idx));
if(~isempty(idx))
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with new
% distances at k0-dk
L=D1{kk}(idx)>dtmp;
map_lower(idx)=L;
D1{kk}(idx(L))=dtmp(L);
DK{kk}(idx(L))=k;
end
end
else
eols=eols-1;
end
if(~isempty(find(map_upper,1)))
% prevent index from going over the boundaries
L=k0(map_upper)+dk<=shape(3);
map_upper(map_upper)=L;
% need to explicitly scan in Z because of using cell-arrays
for kk=1:shape(3)
% get all XY such that k0+dk==kk
if(kk-dk<=length(ss) && kk-dk>=1)
idx=ss(kk-dk).PixelIdxList;
else
idx=[];
end
idx=idx(map_upper(idx));
if(~isempty(idx))
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with new
% distances at k0+dk
L=D1{kk}(idx)>dtmp;
map_upper(idx)=L;
D1{kk}(idx(L))=dtmp(L);
DK{kk}(idx(L))=k;
end
end
else
eols=eols-1;
end
end
end
% prepare the answer, limit distances to MAXVAL
for k=1:shape(3)
D1{k}(D1{k}>maxval2)=maxval2;
end
% prepare the answer, convert to output format matching the input
if(iscell(bw))
D=cell(size(bw));
for k=1:shape(3) D{k}=sqrt(D1{k}); end
else
D=zeros(shape);
for k=1:shape(3) D(:,:,k)=sqrt(D1{k}); end
end
end
function s=getregions(map, UseRegionProps)
% this function is replacer for regionprops(map,'PixelIdxList);
% it produces the list of different values along with the list of
% indexes of the pixels in the map with these values; s is struct-array
% such that s(i).PixelIdxList contains list of pixels in map
% with value i.
% enable using regionprops if available on Matlab versions 7.3 and later,
% regionprops is faster than this code at these versions
% version control for using regionprops is now outside (Turod Dima)
if UseRegionProps
s=regionprops(map,'PixelIdxList');
return
end
idx=(1:prod(size(map)))';
dtmp=double(map(:));
[dtmp,ind]=sort(dtmp);
idx=idx(ind);
ind=[0;find([diff(dtmp(:));1])];
s=[];
for i=2:length(ind)
if(dtmp(ind(i)))==0 continue; end
s(dtmp(ind(i))).PixelIdxList=idx(ind(i-1)+1:ind(i));
end
end
% --- VersionNewerThan and str2numarray added lower ---
function vn = VersionNewerThan(v_ref, AllowEqual)
% V_isNewer = VersionNewerThan(V_REF, AllowEqual)
%
% compare current Matlab version V_CURR with V_REF
% returns TRUE when current version is newer than V_REF (or as new when AllowEqual)
%
% V_REF - string or number
% AllowEqual- boolean (dafault TRUE)
%
% V_CURR vs. V_REF | AllowEqual | V_isNewer
% newer | any | true
% same | true | true
% same | false | false
% older | any | false
%
% 26.12.2011 - new, Tudor for Yuriy > bwdistsc1
if nargin < 2, AllowEqual = true; end
if nargin < 1, v_ref = 7.3; end
if isnumeric(v_ref)
v_ref = num2str(v_ref);
end
v = version;
% compare version numbers group-by-group
% i.e. 7.11.0.584 later than 7.3.1, etc
% this works when v and v_ref are strings of unequal lengths
% containing any number of dots
% split version strings into numerical arrays
VerSeparator = '.';
vd = str2numarray(v, VerSeparator); % installed
vrd = str2numarray(v_ref, VerSeparator); % reference
nG = min(numel(vd),numel(vrd));
% start comparison at most significant group
iG = 1;
while (iG <= nG)
vn = sign(vd(iG) - vrd(iG)); % -1 0 1
iG = iG+1;
if vn ~= 0
break
end
end
if vn == 0 % set the longer of {vd, vrd} as 'the latest
vn = numel(vd) -numel(vrd);
end
vn = vn > 0 || (AllowEqual && vn == 0); % was hard '>='
end
function vd = str2numarray(vs, VerSeparator)
% > split version string into array of double
% > also strip chars trailing 1st ' ' or '('
% i.e. both '7.11.0.584' and '7.11.0.584 (R2010b)'
% will be converted to [7 11 0 584]
iC = 0;
iPrev = 0;
iS = 0;
sL = numel(vs);
vd = zeros(1,sL);
while iS < sL
iS = iS+1;
if vs(iS) == VerSeparator
iC = iC + 1;
vd(iC) = str2double(vs(iPrev+1:iS-1));
iPrev = iS;
elseif (vs(iS) == ' ') || (vs(iS) == '(')
sL = iS-1;
break
end
end
% also store the last section, '.' to end
% (or the only section when no VerSeparator is present)
iC = iC + 1;
vd(iC) = str2double(vs(iPrev+1:sL));
vd = vd(1:iC);
end
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
classRF_predict.m
|
.m
|
vesicle-cnn-2-master/Prior_art/vesicle/packages/vesiclerf/tools/Random Forest/classRF_predict.m
| 2,166 |
utf_8
|
7e026fb9b31f99feae58d36b9cf6c2e0
|
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( [email protected] )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does prediction given the data and the model file
% Options depicted in predict function in http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
%**************************************************************
%function [Y_hat votes] = classRF_predict(X,model, extra_options)
% requires 2 arguments
% X: data matrix
% model: generated via classRF_train function
% extra_options.predict_all = predict_all if set will send all the prediction.
%
%
% Returns
% Y_hat - prediction for the data
% votes - unnormalized weights for the model
% prediction_per_tree - per tree prediction. the returned object .
% If predict.all=TRUE, then the individual component of the returned object is a character
% matrix where each column contains the predicted class by a tree in the forest.
%
%
% Not yet implemented
% proximity
function [Y_new, votes, prediction_per_tree] = classRF_predict(X,model, extra_options)
if nargin<2
error('need atleast 2 parameters,X matrix and model');
end
if exist('extra_options','var')
if isfield(extra_options,'predict_all')
predict_all = extra_options.predict_all;
end
end
if ~exist('predict_all','var'); predict_all=0;end
[Y_hat,prediction_per_tree,votes] = mexClassRF_predict(X',model.nrnodes,model.ntree,model.xbestsplit,model.classwt,model.cutoff,model.treemap,model.nodestatus,model.nodeclass,model.bestvar,model.ndbigtree,model.nclass, predict_all);
%keyboard
votes = votes';
clear mexClassRF_predict
Y_new = double(Y_hat);
new_labels = model.new_labels;
orig_labels = model.orig_labels;
for i=1:length(orig_labels)
Y_new(find(Y_hat==new_labels(i)))=Inf;
Y_new(isinf(Y_new))=orig_labels(i);
end
1;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
classRF_train.m
|
.m
|
vesicle-cnn-2-master/Prior_art/vesicle/packages/vesiclerf/tools/Random Forest/classRF_train.m
| 14,829 |
utf_8
|
82a321d0a7c77f33b104acec4394c6ee
|
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( [email protected] )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does training given the data and labels
% Documentation copied from R-packages pdf
% http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
% Tutorial on getting this working in tutorial_ClassRF.m
%**************************************************************
% function model = classRF_train(X,Y,ntree,mtry, extra_options)
%
%___Options
% requires 2 arguments and the rest 3 are optional
% X: data matrix
% Y: target values
% ntree (optional): number of trees (default is 500). also if set to 0
% will default to 500
% mtry (default is floor(sqrt(size(X,2))) D=number of features in X). also if set to 0
% will default to 500
%
%
% Note: TRUE = 1 and FALSE = 0 below
% extra_options represent a structure containing various misc. options to
% control the RF
% extra_options.replace = 0 or 1 (default is 1) sampling with or without
% replacement
% extra_options.classwt = priors of classes. Here the function first gets
% the labels in ascending order and assumes the
% priors are given in the same order. So if the class
% labels are [-1 1 2] and classwt is [0.1 2 3] then
% there is a 1-1 correspondence. (ascending order of
% class labels). Once this is set the freq of labels in
% train data also affects.
% extra_options.cutoff (Classification only) = A vector of length equal to number of classes. The ?winning?
% class for an observation is the one with the maximum ratio of proportion
% of votes to cutoff. Default is 1/k where k is the number of classes (i.e., majority
% vote wins).
% extra_options.strata = (not yet stable in code) variable that is used for stratified
% sampling. I don't yet know how this works. Disabled
% by default
% extra_options.sampsize = Size(s) of sample to draw. For classification,
% if sampsize is a vector of the length the number of strata, then sampling is stratified by strata,
% and the elements of sampsize indicate the numbers to be
% drawn from the strata.
% extra_options.nodesize = Minimum size of terminal nodes. Setting this number larger causes smaller trees
% to be grown (and thus take less time). Note that the default values are different
% for classification (1) and regression (5).
% extra_options.importance = Should importance of predictors be assessed?
% extra_options.localImp = Should casewise importance measure be computed? (Setting this to TRUE will
% override importance.)
% extra_options.proximity = Should proximity measure among the rows be calculated?
% extra_options.oob_prox = Should proximity be calculated only on 'out-of-bag' data?
% extra_options.do_trace = If set to TRUE, give a more verbose output as randomForest is run. If set to
% some integer, then running output is printed for every
% do_trace trees.
% extra_options.keep_inbag Should an n by ntree matrix be returned that keeps track of which samples are
% 'in-bag' in which trees (but not how many times, if sampling with replacement)
%
% Options eliminated
% corr_bias which happens only for regression ommitted
% norm_votes - always set to return total votes for each class.
%
%___Returns model which has
% importance = a matrix with nclass + 2 (for classification) or two (for regression) columns.
% For classification, the first nclass columns are the class-specific measures
% computed as mean decrease in accuracy. The nclass + 1st column is the
% mean decrease in accuracy over all classes. The last column is the mean decrease
% in Gini index. For Regression, the first column is the mean decrease in
% accuracy and the second the mean decrease in MSE. If importance=FALSE,
% the last measure is still returned as a vector.
% importanceSD = The ?standard errors? of the permutation-based importance measure. For classification,
% a p by nclass + 1 matrix corresponding to the first nclass + 1
% columns of the importance matrix. For regression, a length p vector.
% localImp = a p by n matrix containing the casewise importance measures, the [i,j] element
% of which is the importance of i-th variable on the j-th case. NULL if
% localImp=FALSE.
% ntree = number of trees grown.
% mtry = number of predictors sampled for spliting at each node.
% votes (classification only) a matrix with one row for each input data point and one
% column for each class, giving the fraction or number of ?votes? from the random
% forest.
% oob_times number of times cases are 'out-of-bag' (and thus used in computing OOB error
% estimate)
% proximity if proximity=TRUE when randomForest is called, a matrix of proximity
% measures among the input (based on the frequency that pairs of data points are
% in the same terminal nodes).
% errtr = first column is OOB Err rate, second is for class 1 and so on
function model=classRF_train(X,Y,ntree,mtry, extra_options)
DEFAULTS_ON =0;
%DEBUG_ON=0;
TRUE=1;
FALSE=0;
orig_labels = sort(unique(Y));
Y_new = Y;
new_labels = 1:length(orig_labels);
for i=1:length(orig_labels)
Y_new(find(Y==orig_labels(i)))=Inf;
Y_new(isinf(Y_new))=new_labels(i);
end
Y = Y_new;
if exist('extra_options','var')
if isfield(extra_options,'DEBUG_ON'); DEBUG_ON = extra_options.DEBUG_ON; end
if isfield(extra_options,'replace'); replace = extra_options.replace; end
if isfield(extra_options,'classwt'); classwt = extra_options.classwt; end
if isfield(extra_options,'cutoff'); cutoff = extra_options.cutoff; end
if isfield(extra_options,'strata'); strata = extra_options.strata; end
if isfield(extra_options,'sampsize'); sampsize = extra_options.sampsize; end
if isfield(extra_options,'nodesize'); nodesize = extra_options.nodesize; end
if isfield(extra_options,'importance'); importance = extra_options.importance; end
if isfield(extra_options,'localImp'); localImp = extra_options.localImp; end
if isfield(extra_options,'nPerm'); nPerm = extra_options.nPerm; end
if isfield(extra_options,'proximity'); proximity = extra_options.proximity; end
if isfield(extra_options,'oob_prox'); oob_prox = extra_options.oob_prox; end
%if isfield(extra_options,'norm_votes'); norm_votes = extra_options.norm_votes; end
if isfield(extra_options,'do_trace'); do_trace = extra_options.do_trace; end
%if isfield(extra_options,'corr_bias'); corr_bias = extra_options.corr_bias; end
if isfield(extra_options,'keep_inbag'); keep_inbag = extra_options.keep_inbag; end
end
keep_forest=1; %always save the trees :)
%set defaults if not already set
if ~exist('DEBUG_ON','var') DEBUG_ON=FALSE; end
if ~exist('replace','var'); replace = TRUE; end
%if ~exist('classwt','var'); classwt = []; end %will handle these three later
%if ~exist('cutoff','var'); cutoff = 1; end
%if ~exist('strata','var'); strata = 1; end
if ~exist('sampsize','var');
if (replace)
sampsize = size(X,1);
else
sampsize = ceil(0.632*size(X,1));
end;
end
if ~exist('nodesize','var'); nodesize = 1; end %classification=1, regression=5
if ~exist('importance','var'); importance = FALSE; end
if ~exist('localImp','var'); localImp = FALSE; end
if ~exist('nPerm','var'); nPerm = 1; end
%if ~exist('proximity','var'); proximity = 1; end %will handle these two later
%if ~exist('oob_prox','var'); oob_prox = 1; end
%if ~exist('norm_votes','var'); norm_votes = TRUE; end
if ~exist('do_trace','var'); do_trace = FALSE; end
%if ~exist('corr_bias','var'); corr_bias = FALSE; end
if ~exist('keep_inbag','var'); keep_inbag = FALSE; end
if ~exist('ntree','var') | ntree<=0
ntree=500;
DEFAULTS_ON=1;
end
if ~exist('mtry','var') | mtry<=0 | mtry>size(X,2)
mtry =floor(sqrt(size(X,2)));
end
addclass =isempty(Y);
if (~addclass && length(unique(Y))<2)
error('need atleast two classes for classification');
end
[N D] = size(X);
if N==0; error(' data (X) has 0 rows');end
if (mtry <1 || mtry > D)
DEFAULTS_ON=1;
end
mtry = max(1,min(D,round(mtry)));
if DEFAULTS_ON
fprintf('\tSetting to defaults %d trees and mtry=%d\n',ntree,mtry);
end
if ~isempty(Y)
if length(Y)~=N,
error('Y size is not the same as X size');
end
addclass = FALSE;
else
if ~addclass,
addclass=TRUE;
end
error('have to fill stuff here')
end
if ~isempty(find(isnan(X))); error('NaNs in X'); end
if ~isempty(find(isnan(Y))); error('NaNs in Y'); end
%now handle categories. Problem is that categories in R are more
%enhanced. In this i ask the user to specify the column/features to
%consider as categories, 1 if all the values are real values else
%specify the number of categories here
if exist ('extra_options','var') && isfield(extra_options,'categories')
ncat = extra_options.categories;
else
ncat = ones(1,D);
end
maxcat = max(ncat);
if maxcat>32
error('Can not handle categorical predictors with more than 32 categories');
end
%classRF - line 88 in randomForest.default.R
nclass = length(unique(Y));
if ~exist('cutoff','var')
cutoff = ones(1,nclass)* (1/nclass);
else
if sum(cutoff)>1 || sum(cutoff)<0 || length(find(cutoff<=0))>0 || length(cutoff)~=nclass
error('Incorrect cutoff specified');
end
end
if ~exist('classwt','var')
classwt = ones(1,nclass);
ipi=0;
else
if length(classwt)~=nclass
error('Length of classwt not equal to the number of classes')
end
if ~isempty(find(classwt<=0))
error('classwt must be positive');
end
ipi=1;
end
if ~exist('proximity','var')
proximity = addclass;
oob_prox = proximity;
end
if ~exist('oob_prox','var')
oob_prox = proximity;
end
%i handle the below in the mex file
% if proximity
% prox = zeros(N,N);
% proxts = 1;
% else
% prox = 1;
% proxts = 1;
% end
%i handle the below in the mex file
if localImp
importance = TRUE;
% impmat = zeors(D,N);
else
% impmat = 1;
end
if importance
if (nPerm<1)
nPerm = int32(1);
else
nPerm = int32(nPerm);
end
%classRF
% impout = zeros(D,nclass+2);
% impSD = zeros(D,nclass+1);
else
% impout = zeros(D,1);
% impSD = 1;
end
%i handle the below in the mex file
%somewhere near line 157 in randomForest.default.R
if addclass
% nsample = 2*n;
else
% nsample = n;
end
Stratify = (length(sampsize)>1);
if (~Stratify && sampsize>N)
error('Sampsize too large')
end
if Stratify
if ~exist('strata','var')
strata = Y;
end
nsum = sum(sampsize);
if ( ~isempty(find(sampsize<=0)) || nsum==0)
error('Bad sampsize specification');
end
else
nsum = sampsize;
end
%i handle the below in the mex file
%nrnodes = 2*floor(nsum/nodesize)+1;
%xtest = 1;
%ytest = 1;
%ntest = 1;
%labelts = FALSE;
%nt = ntree;
%[ldau,rdau,nodestatus,nrnodes,upper,avnode,mbest,ndtree]=
%keyboard
if Stratify
strata = int32(strata);
else
strata = int32(1);
end
Options = int32([addclass, importance, localImp, proximity, oob_prox, do_trace, keep_forest, replace, Stratify, keep_inbag]);
if DEBUG_ON
%print the parameters that i am sending in
fprintf('size(x) %d\n',size(X));
fprintf('size(y) %d\n',size(Y));
fprintf('nclass %d\n',nclass);
fprintf('size(ncat) %d\n',size(ncat));
fprintf('maxcat %d\n',maxcat);
fprintf('size(sampsize) %d\n',size(sampsize));
fprintf('sampsize[0] %d\n',sampsize(1));
fprintf('Stratify %d\n',Stratify);
fprintf('Proximity %d\n',proximity);
fprintf('oob_prox %d\n',oob_prox);
fprintf('strata %d\n',strata);
fprintf('ntree %d\n',ntree);
fprintf('mtry %d\n',mtry);
fprintf('ipi %d\n',ipi);
fprintf('classwt %f\n',classwt);
fprintf('cutoff %f\n',cutoff);
fprintf('nodesize %f\n',nodesize);
end
[nrnodes,ntree,xbestsplit,classwt,cutoff,treemap,nodestatus,nodeclass,bestvar,ndbigtree,mtry ...
outcl, counttr, prox, impmat, impout, impSD, errtr, inbag] ...
= mexClassRF_train(X',int32(Y_new),length(unique(Y)),ntree,mtry,int32(ncat), ...
int32(maxcat), int32(sampsize), strata, Options, int32(ipi), ...
classwt, cutoff, int32(nodesize),int32(nsum));
model.nrnodes=nrnodes;
model.ntree=ntree;
model.xbestsplit=xbestsplit;
model.classwt=classwt;
model.cutoff=cutoff;
model.treemap=treemap;
model.nodestatus=nodestatus;
model.nodeclass=nodeclass;
model.bestvar = bestvar;
model.ndbigtree = ndbigtree;
model.mtry = mtry;
model.orig_labels=orig_labels;
model.new_labels=new_labels;
model.nclass = length(unique(Y));
model.outcl = outcl;
model.counttr = counttr;
if proximity
model.proximity = prox;
else
model.proximity = [];
end
model.localImp = impmat;
model.importance = impout;
model.importanceSD = impSD;
model.errtr = errtr';
model.inbag = inbag;
model.votes = counttr';
model.oob_times = sum(counttr)';
clear mexClassRF_train
%keyboard
1;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
structureTensorImage2.m
|
.m
|
vesicle-cnn-2-master/Prior_art/vesicle/packages/vesiclerf/tools/structure_tensor/structureTensorImage2.m
| 2,078 |
utf_8
|
a9f4eb4f44095b9695bc66b79eca3cbd
|
%[eig1, eig2, cw] = structureTensorImage2(im, s, sg)
%s: smoothing sigma
%sg: sigma gaussian for summation weights
%window size is adapted
function [eig1, eig2, cw] = structureTensorImage2(im, s, sg)
w = 2*sg;
[gx,gy,mag] = gradientImg(double(im),s);
clear mag;
S_0_x = gx.*gx;
S_0_xy = gx.*gy;
S_0_y = gy.*gy;
clear gx
clear gy
sum_x = 1/(2*pi*sg^2) * S_0_x;
sum_y = 1/(2*pi*sg^2) *S_0_y;
sum_xy = 1/(2*pi*sg^2) *S_0_xy;
%sum_x
sl = sum_x;
sr = sum_x;
su = sum_x;
sd = sum_x;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_x = sum_x + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
%sum_y
sl = sum_y;
sr = sum_y;
su = sum_y;
sd = sum_y;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_y = sum_y + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
%sum_xy
sl = sum_xy;
sr = sum_xy;
su = sum_xy;
sd = sum_xy;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_xy = sum_xy + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
clear sl
clear sr
clear su
clear sd
eig1 = zeros(size(im));
eig2 = zeros(size(im));
for i=1:length(im(:))
e2 = (sum_x(i) + sum_y(i))/2 + sqrt(4*sum_xy(i)*sum_xy(i)+(sum_x(i)-sum_y(i))^2)/2;
e1 = (sum_x(i) + sum_y(i))/2 - sqrt(4*sum_xy(i)*sum_xy(i)+(sum_x(i)-sum_y(i))^2)/2;
eig1(i) = e1;
eig2(i) = e2;
end
cw = ((eig1-eig2)./(eig1+eig2)).^2;
cw(isnan(cw)) = 0;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
gradientImg.m
|
.m
|
vesicle-cnn-2-master/Prior_art/vesicle/packages/vesiclerf/tools/structure_tensor/gradientImg.m
| 413 |
utf_8
|
caa4df879004f65177163e8185112940
|
%function [gx, gy, mag] = gradientImg(im, s)
function [gx, gy, mag] = gradientImg(im, s)
% $$$ fg = fspecial('gaussian',4*s,s);
% $$$ fs = fspecial('sobel');
% $$$
% $$$ fgy = filter2(fs,fg);
% $$$ fgx = filter2(fs',fg);
% $$$
% $$$ fgm = sqrt(fgx.^2 + fgy.^2);
% $$$
% $$$ gy = filter2(fgy,im);
% $$$ gx = filter2(fgx,im);
im = imsmooth_st(double(im),s);
[gx,gy] = gradient(im);
mag = sqrt(gx.^2 + gy.^2);
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
bwdistsc1.m
|
.m
|
vesicle-cnn-2-master/vesiclerf-2/tools/bwdistsc/bwdistsc1.m
| 19,630 |
utf_8
|
003a8729f0ccdb35a49d8429ea605c64
|
function D=bwdistsc1(bw,aspect,maxval)
% D=BWDISTSC1(BW,ASPECT,MAXVAL)
% BWDISTSC1 computes Euclidean distance transform of a binary 3D image
% BW out to a specified value MAXVAL. This allows accelerating the
% calculations in some cases with strongly nonconvex geometries, if the
% distance transform only needs to be calculated out to a specific value.
% The distance transform assigns to each pixel in BW a number that is
% the distance from that pixel to the nearest nonzero pixel in BW. BW may
% be a 3D array or a cell array of 2D slices. BWDISTSC1 can also accept
% regular 2D images. ASPECT is a 3-component vector defining the aspect
% ratios to use when calculating the distances in BW. If ASPECT is not set,
% isotropic aspect ratio [1 1 1] is used. If MAXVAL is specified, the
% distance transform will be only calculated out to the value MAXVAL.
%
% BWDISTSC1 uses the same algorithm as BWDISTSC but without forward-
% backward scan.
%
% BWDISTSC1 tries to use MATLAB's bwdist for 2D scans if possible, which
% is faster. Otherwise BWDISTSC1 will use its own algorithm for 2D scans.
% Also incorporates the fix for Matlab version detection bug in the
% original BWDISTSC contributed by Tudor Dima.
%
%(c) Yuriy Mishchenko HHMI JFRC Chklovskii Lab JUL 2007
% This function written Yuriy Mishchenko JUL 2011
% This function updated Yuriy Mishchenko SEP 2013
% This code is free for use or modifications, just please give credit where
% appropriate. If you modify the code or fix bugs, please drop me a message
% at [email protected].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Scan algorithms below use the following Lema: %
% LEMA: let F(X,z) be lower envelope of a family of parabola: %
% F(X,z)=min_{k} [G(X)+(z-k)^2]; %
% and let H_k(X,z)=A(X)+(z-k)^2 be a parabola. %
% Then for H_k(X,z)==F(X,z) at each X there exist at most %
% two solutions k1<k2 such that H_k12(X,z)=F(X,z), and %
% H_k(X,z)<F(X,z) is restricted to at most k1<k2. %
% Here X is any-dimensional coordinate. %
% %
% Thus, simply scan away from any z such that H_k(X,z)<F(X,z) %
% in either direction as long as H_k(X,z)<F(X,z) and update %
% F(X,z). Note that need to properly choose starting point; %
% starting point is any z such that H_k(X,z)<F(X,z); z==k is %
% usually, but not always the starting point! %
% %
% Citation: %
% Mishchenko Y. (2013) A function for fastcomputation of large %
% discrete Euclidean distance transforms in three or more %
% dimensions in Matlab. Signal, Image and Video Processing %
% DOI: 10.1007/s11760-012-0419-9. %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parse inputs
if(nargin<2 || isempty(aspect)) aspect=[1 1 1]; end
if(nargin<3 || isempty(maxval)) maxval=Inf; end
% establish (once) whether we will use the "regionprops";
% on Matlab versions earlier than 7.3 regionprops is too slow for simply
% collecting regions, as we want, and internal algorithm will be faster
UseRegionProps = exist('regionprops', 'file') && VersionNewerThan(7.3);
% need this to remove pixels from consideration in the scan if current
% distance becomes greater than MAXVAL
maxval2=maxval^2;
% determine geometry of the data
if(iscell(bw)) shape=[size(bw{1}),length(bw)]; else shape=size(bw); end
% correct this for 2D data
if(length(shape)==2) shape=[shape,1]; end
if(length(aspect)==2) aspect=[aspect,1]; end
% allocate internal memory
D=cell(1,shape(3)); for k=1:shape(3) D{k}=zeros(shape(1:2)); end
%%%%%%%%%%%%% scan along XY %%%%%%%%%%%%%%%%
for k=1:shape(3)
if(iscell(bw)) bwXY=bw{k}; else bwXY=bw(:,:,k); end
DXY=zeros(shape(1:2));
% if can, use 2D bwdist from image processing toolbox
if(exist('bwdist') && aspect(1)==aspect(2))
DXY=aspect(1)^2*bwdist(bwXY).^2;
DXY(DXY>maxval2)=Inf;
else % if not, use full XY-scan
%%%%%%%%%%%%%%% X-SCAN %%%%%%%%%%%%%%%
% reference nearest bwXY "on"-pixel in x direction downward:
% scan bottow-up, copy x-reference from previous row unless
% there is bwXY "on"-pixel in that point in current row
xlower=repmat(Inf,shape(1:2));
xlower(1,find(bwXY(1,:)))=1; % fill in first row
for i=2:shape(1)
xlower(i,:)=xlower(i-1,:); % copy previous row
xlower(i,find(bwXY(i,:)))=i;% unless there is pixel
end
% reference nearest bwXY "on"-pixel in x direction upward:
xupper=repmat(Inf,shape(1:2));
xupper(end,find(bwXY(end,:)))=shape(1);
for i=shape(1)-1:-1:1
xupper(i,:)=xupper(i+1,:);
xupper(i,find(bwXY(i,:)))=i;
end
% find pixels for which distance needs to be updated
idx=find(~bwXY); [x,y]=ind2sub(shape(1:2),idx);
% set distance as the shortest to upward or to downward
DXY(idx)=aspect(1)^2*min((x-xlower(idx)).^2,(x-xupper(idx)).^2);
DXY(DXY>maxval2)=Inf;
%%%%%%%%%%%%%%% Y-SCAN %%%%%%%%%%%%%%%
% this will be the envelop
D1=repmat(Inf,shape(1:2));
% these will be the references to parabolas defining the envelop
DK=repmat(Inf,shape(1:2));
for i=1:shape(2)
% need to select starting point for each X:
% * starting point should be below current envelop
% * i0==i is not necessarily a starting point
% * there is at most one starting point
% * there may be no starting point
% i0 is the starting points for each X: i0(X) is the first
% y-index such that parabola from line i is below the envelop
% first guess is the current y-line
i0=repmat(i,shape(1),1);
% some auxiliary datasets
d0=DXY(:,i);
x=(1:shape(1))';
% L0 indicates for which X starting point had been fixed
L0=isinf(d0);
while(~isempty(find(~L0,1)))
% reference starting points in DXY
idx=sub2ind(shape(1:2),x(~L0),i0(~L0));
% these are current best parabolas for starting points
ik=DK(idx);
% these are new values from parabola from line #i
dtmp=d0(~L0)+aspect(2)^2*(i0(~L0)-i).^2;
dtmp(dtmp>maxval2)=Inf;
% these starting points are OK - below the envelop
L=D1(idx)>dtmp; D1(idx(L))=dtmp(L);
% points which are still above the envelop but ik==i0,
% will not get any better, so fix them as well
L=isinf(dtmp) | L | (ik==i0(~L0));
% all other points are not OK, need new starting point:
% starting point should be at least below parabola
% beating us at current choice of i0
% solve quadratic equation to find where this happens
ik=(ik-i);
di=(D1(idx(~L))-dtmp(~L))./ik(~L)/2/aspect(2)^2;
% should select next highest index to the equality
di=fix(di)+sign(di);
% the new starting points
idx=find(~L0);
i0(idx(~L))=i0(idx(~L))+di;
% update L0 to indicate which points we've fixed
L0(~L0)=L; L0(idx(~L))=(di==0);
% points that went out can't get better;
% fix them as well
L=(i0<1) | (i0>shape(2)); i0(L)=i;
L0(L)=1;
end
% will keep track along which X should keep updating distance
map_lower=true(shape(1),1);
map_upper=true(shape(1),1);
% scan from starting points for each X i0 in increments of 1
di=0; % distance from current y-line
eols=2; % end-of-line-scan flag
while(eols)
eols=2;
di=di+1;
dtmp=repmat(Inf,shape(1),1);
% select X which can be updated for di<0;
% i.e. X which had been below envelop all way till now
x=find(map_lower);
if(~isempty(x))
% prevent index dropping below 1st
L=i0(map_lower)-di>=1;
map_lower(map_lower)=L;
% select pixels (X,i0(X)-di)
idx=sub2ind(shape(1:2),x(L),i0(map_lower)-di);
if(~isempty(idx))
dtmp=d0(map_lower)+...
aspect(2)^2*(i0(map_lower)-di-i).^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with i0-di
L=D1(idx)>dtmp;
map_lower(map_lower)=L;
D1(idx(L))=dtmp(L);
DK(idx(L))=i;
end
else % if this is empty, get ready to quit
eols=eols-1;
end
% select X which can be updated for di>0;
% i.e. X which had been below envelop all way till now
x=find(map_upper);
if(~isempty(x))
% prevent index from going over array limits
L=i0(map_upper)+di<=shape(2);
map_upper(map_upper)=L;
% select pixels (X,i0(X)+di)
idx=sub2ind(shape(1:2),x(L),i0(map_upper)+di);
if(~isempty(idx))
dtmp=d0(map_upper)+...
aspect(2)^2*(i0(map_upper)+di-i).^2;
dtmp(dtmp>maxval2)=Inf;
% check which pixels are to be updated with i0+di
L=D1(idx)>dtmp;
map_upper(map_upper)=L;
D1(idx(L))=dtmp(L);
DK(idx(L))=i;
end
else % if this is empty, get ready to quit
eols=eols-1;
end
end
end
DXY=D1;
end
D{k}=DXY;
end
%%%%%%%%%%%%% scan along Z %%%%%%%%%%%%%%%%
% this will be the envelop of the parabolas centered on different Z points
D1=cell(size(D));
for k=1:shape(3) D1{k}=repmat(Inf,shape(1:2)); end
% these will be the Z-references for the parabolas forming the envelop
DK=cell(size(D));
for k=1:shape(3) DK{k}=repmat(Inf,shape(1:2)); end
% start building the envelope
for k=1:shape(3)
% need to select starting point for each XY:
% * starting point should be below already existing current envelop
% * k0==k is not necessarily a starting point
% * there may be no starting point
% j0 is the starting points for each XY: k0(XY) is the first
% z-index such that the parabola from slice k gets below the envelop
% for initial starting point, guess the current slice k
k0=repmat(k,shape(1:2));
% L0 indicates which starting points had been found so far
L0=isinf(D{k});
while(~isempty(find(~L0,1)))
% because of using cells, need to explicitly scan in Z
% to avoid repetitious searches in k0, parse first
ss = getregions(k0, UseRegionProps);
for kk=1:shape(3)
% these are starting points @kk which had not been set yet
if(kk<=length(ss)) idx=ss(kk).PixelIdxList; else idx=[]; end
idx=idx(~L0(idx));
if(isempty(idx)) continue; end
% these are currently the best parabolas for slice kk
ik=DK{kk}(idx);
% these are new distances for points in kk from parabolas in k
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these points are below current envelop, OK starting points
L=D1{kk}(idx)>dtmp; D1{kk}(idx(L))=dtmp(L);
% these points are not OK, but since ik==k0
% can't get any better, so remove them as well from search
L=L | (ik==kk) | isinf(dtmp);
% all other points are not OK, need new starting point:
% starting point should be at least below the parabola
% beating us at current choice of k0, thus make new guess for k
ik=(ik-k);
dk=(D1{kk}(idx(~L))-dtmp(~L))./ik(~L)/2/aspect(3)^2;
dk=fix(dk)+sign(dk);
k0(idx(~L))=k0(idx(~L))+dk;
% update starting points that had been fixed in this pass
L0(idx)=L;
L0(idx(~L))=(dk==0);
% points that went out of boundaries can't get better, fix them
L=(k0<1) | (k0>shape(3));
L0(L)=1;
k0(L)=k;
end
end
% map_lower/map_upper keeps track of which pixels yet can be updated
% with new distances, i.e., all such XY that had been below envelop
% for all dk up to now, for dk<0/dk>0 respectively
map_lower=true(shape(1:2));
map_upper=true(shape(1:2));
% parse different values in k0 to avoid repetitious searching below
ss = getregions(k0, UseRegionProps);
% scan away from starting points in increments of 1
dk=0; % distance from current xy-slice
eols=2; % end-of-scan flag
while(eols)
eols=2;
dk=dk+1;
dtmp=repmat(Inf,shape(1:2));
if(~isempty(find(map_lower,1)))
% prevent index from going over the boundaries
L=k0(map_lower)-dk>=1;
map_lower(map_lower)=L;
% need to explicitly scan in Z because of using cell-arrays
for kk=1:shape(3)
% get all XY such that k0-dk==kk
if(kk+dk<=length(ss) & kk+dk>=1)
idx=ss(kk+dk).PixelIdxList;
else
idx=[];
end
idx=idx(map_lower(idx));
if(~isempty(idx))
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with new
% distances at k0-dk
L=D1{kk}(idx)>dtmp;
map_lower(idx)=L;
D1{kk}(idx(L))=dtmp(L);
DK{kk}(idx(L))=k;
end
end
else
eols=eols-1;
end
if(~isempty(find(map_upper,1)))
% prevent index from going over the boundaries
L=k0(map_upper)+dk<=shape(3);
map_upper(map_upper)=L;
% need to explicitly scan in Z because of using cell-arrays
for kk=1:shape(3)
% get all XY such that k0+dk==kk
if(kk-dk<=length(ss) && kk-dk>=1)
idx=ss(kk-dk).PixelIdxList;
else
idx=[];
end
idx=idx(map_upper(idx));
if(~isempty(idx))
dtmp=D{k}(idx)+aspect(3)^2*(kk-k)^2;
dtmp(dtmp>maxval2)=Inf;
% these pixels are to be updated with new
% distances at k0+dk
L=D1{kk}(idx)>dtmp;
map_upper(idx)=L;
D1{kk}(idx(L))=dtmp(L);
DK{kk}(idx(L))=k;
end
end
else
eols=eols-1;
end
end
end
% prepare the answer, limit distances to MAXVAL
for k=1:shape(3)
D1{k}(D1{k}>maxval2)=maxval2;
end
% prepare the answer, convert to output format matching the input
if(iscell(bw))
D=cell(size(bw));
for k=1:shape(3) D{k}=sqrt(D1{k}); end
else
D=zeros(shape);
for k=1:shape(3) D(:,:,k)=sqrt(D1{k}); end
end
end
function s=getregions(map, UseRegionProps)
% this function is replacer for regionprops(map,'PixelIdxList);
% it produces the list of different values along with the list of
% indexes of the pixels in the map with these values; s is struct-array
% such that s(i).PixelIdxList contains list of pixels in map
% with value i.
% enable using regionprops if available on Matlab versions 7.3 and later,
% regionprops is faster than this code at these versions
% version control for using regionprops is now outside (Turod Dima)
if UseRegionProps
s=regionprops(map,'PixelIdxList');
return
end
idx=(1:prod(size(map)))';
dtmp=double(map(:));
[dtmp,ind]=sort(dtmp);
idx=idx(ind);
ind=[0;find([diff(dtmp(:));1])];
s=[];
for i=2:length(ind)
if(dtmp(ind(i)))==0 continue; end
s(dtmp(ind(i))).PixelIdxList=idx(ind(i-1)+1:ind(i));
end
end
% --- VersionNewerThan and str2numarray added lower ---
function vn = VersionNewerThan(v_ref, AllowEqual)
% V_isNewer = VersionNewerThan(V_REF, AllowEqual)
%
% compare current Matlab version V_CURR with V_REF
% returns TRUE when current version is newer than V_REF (or as new when AllowEqual)
%
% V_REF - string or number
% AllowEqual- boolean (dafault TRUE)
%
% V_CURR vs. V_REF | AllowEqual | V_isNewer
% newer | any | true
% same | true | true
% same | false | false
% older | any | false
%
% 26.12.2011 - new, Tudor for Yuriy > bwdistsc1
if nargin < 2, AllowEqual = true; end
if nargin < 1, v_ref = 7.3; end
if isnumeric(v_ref)
v_ref = num2str(v_ref);
end
v = version;
% compare version numbers group-by-group
% i.e. 7.11.0.584 later than 7.3.1, etc
% this works when v and v_ref are strings of unequal lengths
% containing any number of dots
% split version strings into numerical arrays
VerSeparator = '.';
vd = str2numarray(v, VerSeparator); % installed
vrd = str2numarray(v_ref, VerSeparator); % reference
nG = min(numel(vd),numel(vrd));
% start comparison at most significant group
iG = 1;
while (iG <= nG)
vn = sign(vd(iG) - vrd(iG)); % -1 0 1
iG = iG+1;
if vn ~= 0
break
end
end
if vn == 0 % set the longer of {vd, vrd} as 'the latest
vn = numel(vd) -numel(vrd);
end
vn = vn > 0 || (AllowEqual && vn == 0); % was hard '>='
end
function vd = str2numarray(vs, VerSeparator)
% > split version string into array of double
% > also strip chars trailing 1st ' ' or '('
% i.e. both '7.11.0.584' and '7.11.0.584 (R2010b)'
% will be converted to [7 11 0 584]
iC = 0;
iPrev = 0;
iS = 0;
sL = numel(vs);
vd = zeros(1,sL);
while iS < sL
iS = iS+1;
if vs(iS) == VerSeparator
iC = iC + 1;
vd(iC) = str2double(vs(iPrev+1:iS-1));
iPrev = iS;
elseif (vs(iS) == ' ') || (vs(iS) == '(')
sL = iS-1;
break
end
end
% also store the last section, '.' to end
% (or the only section when no VerSeparator is present)
iC = iC + 1;
vd(iC) = str2double(vs(iPrev+1:sL));
vd = vd(1:iC);
end
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
classRF_predict.m
|
.m
|
vesicle-cnn-2-master/vesiclerf-2/tools/Random Forest/classRF_predict.m
| 2,166 |
utf_8
|
7e026fb9b31f99feae58d36b9cf6c2e0
|
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( [email protected] )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does prediction given the data and the model file
% Options depicted in predict function in http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
%**************************************************************
%function [Y_hat votes] = classRF_predict(X,model, extra_options)
% requires 2 arguments
% X: data matrix
% model: generated via classRF_train function
% extra_options.predict_all = predict_all if set will send all the prediction.
%
%
% Returns
% Y_hat - prediction for the data
% votes - unnormalized weights for the model
% prediction_per_tree - per tree prediction. the returned object .
% If predict.all=TRUE, then the individual component of the returned object is a character
% matrix where each column contains the predicted class by a tree in the forest.
%
%
% Not yet implemented
% proximity
function [Y_new, votes, prediction_per_tree] = classRF_predict(X,model, extra_options)
if nargin<2
error('need atleast 2 parameters,X matrix and model');
end
if exist('extra_options','var')
if isfield(extra_options,'predict_all')
predict_all = extra_options.predict_all;
end
end
if ~exist('predict_all','var'); predict_all=0;end
[Y_hat,prediction_per_tree,votes] = mexClassRF_predict(X',model.nrnodes,model.ntree,model.xbestsplit,model.classwt,model.cutoff,model.treemap,model.nodestatus,model.nodeclass,model.bestvar,model.ndbigtree,model.nclass, predict_all);
%keyboard
votes = votes';
clear mexClassRF_predict
Y_new = double(Y_hat);
new_labels = model.new_labels;
orig_labels = model.orig_labels;
for i=1:length(orig_labels)
Y_new(find(Y_hat==new_labels(i)))=Inf;
Y_new(isinf(Y_new))=orig_labels(i);
end
1;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
classRF_train.m
|
.m
|
vesicle-cnn-2-master/vesiclerf-2/tools/Random Forest/classRF_train.m
| 14,829 |
utf_8
|
82a321d0a7c77f33b104acec4394c6ee
|
%**************************************************************
%* mex interface to Andy Liaw et al.'s C code (used in R package randomForest)
%* Added by Abhishek Jaiantilal ( [email protected] )
%* License: GPLv2
%* Version: 0.02
%
% Calls Classification Random Forest
% A wrapper matlab file that calls the mex file
% This does training given the data and labels
% Documentation copied from R-packages pdf
% http://cran.r-project.org/web/packages/randomForest/randomForest.pdf
% Tutorial on getting this working in tutorial_ClassRF.m
%**************************************************************
% function model = classRF_train(X,Y,ntree,mtry, extra_options)
%
%___Options
% requires 2 arguments and the rest 3 are optional
% X: data matrix
% Y: target values
% ntree (optional): number of trees (default is 500). also if set to 0
% will default to 500
% mtry (default is floor(sqrt(size(X,2))) D=number of features in X). also if set to 0
% will default to 500
%
%
% Note: TRUE = 1 and FALSE = 0 below
% extra_options represent a structure containing various misc. options to
% control the RF
% extra_options.replace = 0 or 1 (default is 1) sampling with or without
% replacement
% extra_options.classwt = priors of classes. Here the function first gets
% the labels in ascending order and assumes the
% priors are given in the same order. So if the class
% labels are [-1 1 2] and classwt is [0.1 2 3] then
% there is a 1-1 correspondence. (ascending order of
% class labels). Once this is set the freq of labels in
% train data also affects.
% extra_options.cutoff (Classification only) = A vector of length equal to number of classes. The ?winning?
% class for an observation is the one with the maximum ratio of proportion
% of votes to cutoff. Default is 1/k where k is the number of classes (i.e., majority
% vote wins).
% extra_options.strata = (not yet stable in code) variable that is used for stratified
% sampling. I don't yet know how this works. Disabled
% by default
% extra_options.sampsize = Size(s) of sample to draw. For classification,
% if sampsize is a vector of the length the number of strata, then sampling is stratified by strata,
% and the elements of sampsize indicate the numbers to be
% drawn from the strata.
% extra_options.nodesize = Minimum size of terminal nodes. Setting this number larger causes smaller trees
% to be grown (and thus take less time). Note that the default values are different
% for classification (1) and regression (5).
% extra_options.importance = Should importance of predictors be assessed?
% extra_options.localImp = Should casewise importance measure be computed? (Setting this to TRUE will
% override importance.)
% extra_options.proximity = Should proximity measure among the rows be calculated?
% extra_options.oob_prox = Should proximity be calculated only on 'out-of-bag' data?
% extra_options.do_trace = If set to TRUE, give a more verbose output as randomForest is run. If set to
% some integer, then running output is printed for every
% do_trace trees.
% extra_options.keep_inbag Should an n by ntree matrix be returned that keeps track of which samples are
% 'in-bag' in which trees (but not how many times, if sampling with replacement)
%
% Options eliminated
% corr_bias which happens only for regression ommitted
% norm_votes - always set to return total votes for each class.
%
%___Returns model which has
% importance = a matrix with nclass + 2 (for classification) or two (for regression) columns.
% For classification, the first nclass columns are the class-specific measures
% computed as mean decrease in accuracy. The nclass + 1st column is the
% mean decrease in accuracy over all classes. The last column is the mean decrease
% in Gini index. For Regression, the first column is the mean decrease in
% accuracy and the second the mean decrease in MSE. If importance=FALSE,
% the last measure is still returned as a vector.
% importanceSD = The ?standard errors? of the permutation-based importance measure. For classification,
% a p by nclass + 1 matrix corresponding to the first nclass + 1
% columns of the importance matrix. For regression, a length p vector.
% localImp = a p by n matrix containing the casewise importance measures, the [i,j] element
% of which is the importance of i-th variable on the j-th case. NULL if
% localImp=FALSE.
% ntree = number of trees grown.
% mtry = number of predictors sampled for spliting at each node.
% votes (classification only) a matrix with one row for each input data point and one
% column for each class, giving the fraction or number of ?votes? from the random
% forest.
% oob_times number of times cases are 'out-of-bag' (and thus used in computing OOB error
% estimate)
% proximity if proximity=TRUE when randomForest is called, a matrix of proximity
% measures among the input (based on the frequency that pairs of data points are
% in the same terminal nodes).
% errtr = first column is OOB Err rate, second is for class 1 and so on
function model=classRF_train(X,Y,ntree,mtry, extra_options)
DEFAULTS_ON =0;
%DEBUG_ON=0;
TRUE=1;
FALSE=0;
orig_labels = sort(unique(Y));
Y_new = Y;
new_labels = 1:length(orig_labels);
for i=1:length(orig_labels)
Y_new(find(Y==orig_labels(i)))=Inf;
Y_new(isinf(Y_new))=new_labels(i);
end
Y = Y_new;
if exist('extra_options','var')
if isfield(extra_options,'DEBUG_ON'); DEBUG_ON = extra_options.DEBUG_ON; end
if isfield(extra_options,'replace'); replace = extra_options.replace; end
if isfield(extra_options,'classwt'); classwt = extra_options.classwt; end
if isfield(extra_options,'cutoff'); cutoff = extra_options.cutoff; end
if isfield(extra_options,'strata'); strata = extra_options.strata; end
if isfield(extra_options,'sampsize'); sampsize = extra_options.sampsize; end
if isfield(extra_options,'nodesize'); nodesize = extra_options.nodesize; end
if isfield(extra_options,'importance'); importance = extra_options.importance; end
if isfield(extra_options,'localImp'); localImp = extra_options.localImp; end
if isfield(extra_options,'nPerm'); nPerm = extra_options.nPerm; end
if isfield(extra_options,'proximity'); proximity = extra_options.proximity; end
if isfield(extra_options,'oob_prox'); oob_prox = extra_options.oob_prox; end
%if isfield(extra_options,'norm_votes'); norm_votes = extra_options.norm_votes; end
if isfield(extra_options,'do_trace'); do_trace = extra_options.do_trace; end
%if isfield(extra_options,'corr_bias'); corr_bias = extra_options.corr_bias; end
if isfield(extra_options,'keep_inbag'); keep_inbag = extra_options.keep_inbag; end
end
keep_forest=1; %always save the trees :)
%set defaults if not already set
if ~exist('DEBUG_ON','var') DEBUG_ON=FALSE; end
if ~exist('replace','var'); replace = TRUE; end
%if ~exist('classwt','var'); classwt = []; end %will handle these three later
%if ~exist('cutoff','var'); cutoff = 1; end
%if ~exist('strata','var'); strata = 1; end
if ~exist('sampsize','var');
if (replace)
sampsize = size(X,1);
else
sampsize = ceil(0.632*size(X,1));
end;
end
if ~exist('nodesize','var'); nodesize = 1; end %classification=1, regression=5
if ~exist('importance','var'); importance = FALSE; end
if ~exist('localImp','var'); localImp = FALSE; end
if ~exist('nPerm','var'); nPerm = 1; end
%if ~exist('proximity','var'); proximity = 1; end %will handle these two later
%if ~exist('oob_prox','var'); oob_prox = 1; end
%if ~exist('norm_votes','var'); norm_votes = TRUE; end
if ~exist('do_trace','var'); do_trace = FALSE; end
%if ~exist('corr_bias','var'); corr_bias = FALSE; end
if ~exist('keep_inbag','var'); keep_inbag = FALSE; end
if ~exist('ntree','var') | ntree<=0
ntree=500;
DEFAULTS_ON=1;
end
if ~exist('mtry','var') | mtry<=0 | mtry>size(X,2)
mtry =floor(sqrt(size(X,2)));
end
addclass =isempty(Y);
if (~addclass && length(unique(Y))<2)
error('need atleast two classes for classification');
end
[N D] = size(X);
if N==0; error(' data (X) has 0 rows');end
if (mtry <1 || mtry > D)
DEFAULTS_ON=1;
end
mtry = max(1,min(D,round(mtry)));
if DEFAULTS_ON
fprintf('\tSetting to defaults %d trees and mtry=%d\n',ntree,mtry);
end
if ~isempty(Y)
if length(Y)~=N,
error('Y size is not the same as X size');
end
addclass = FALSE;
else
if ~addclass,
addclass=TRUE;
end
error('have to fill stuff here')
end
if ~isempty(find(isnan(X))); error('NaNs in X'); end
if ~isempty(find(isnan(Y))); error('NaNs in Y'); end
%now handle categories. Problem is that categories in R are more
%enhanced. In this i ask the user to specify the column/features to
%consider as categories, 1 if all the values are real values else
%specify the number of categories here
if exist ('extra_options','var') && isfield(extra_options,'categories')
ncat = extra_options.categories;
else
ncat = ones(1,D);
end
maxcat = max(ncat);
if maxcat>32
error('Can not handle categorical predictors with more than 32 categories');
end
%classRF - line 88 in randomForest.default.R
nclass = length(unique(Y));
if ~exist('cutoff','var')
cutoff = ones(1,nclass)* (1/nclass);
else
if sum(cutoff)>1 || sum(cutoff)<0 || length(find(cutoff<=0))>0 || length(cutoff)~=nclass
error('Incorrect cutoff specified');
end
end
if ~exist('classwt','var')
classwt = ones(1,nclass);
ipi=0;
else
if length(classwt)~=nclass
error('Length of classwt not equal to the number of classes')
end
if ~isempty(find(classwt<=0))
error('classwt must be positive');
end
ipi=1;
end
if ~exist('proximity','var')
proximity = addclass;
oob_prox = proximity;
end
if ~exist('oob_prox','var')
oob_prox = proximity;
end
%i handle the below in the mex file
% if proximity
% prox = zeros(N,N);
% proxts = 1;
% else
% prox = 1;
% proxts = 1;
% end
%i handle the below in the mex file
if localImp
importance = TRUE;
% impmat = zeors(D,N);
else
% impmat = 1;
end
if importance
if (nPerm<1)
nPerm = int32(1);
else
nPerm = int32(nPerm);
end
%classRF
% impout = zeros(D,nclass+2);
% impSD = zeros(D,nclass+1);
else
% impout = zeros(D,1);
% impSD = 1;
end
%i handle the below in the mex file
%somewhere near line 157 in randomForest.default.R
if addclass
% nsample = 2*n;
else
% nsample = n;
end
Stratify = (length(sampsize)>1);
if (~Stratify && sampsize>N)
error('Sampsize too large')
end
if Stratify
if ~exist('strata','var')
strata = Y;
end
nsum = sum(sampsize);
if ( ~isempty(find(sampsize<=0)) || nsum==0)
error('Bad sampsize specification');
end
else
nsum = sampsize;
end
%i handle the below in the mex file
%nrnodes = 2*floor(nsum/nodesize)+1;
%xtest = 1;
%ytest = 1;
%ntest = 1;
%labelts = FALSE;
%nt = ntree;
%[ldau,rdau,nodestatus,nrnodes,upper,avnode,mbest,ndtree]=
%keyboard
if Stratify
strata = int32(strata);
else
strata = int32(1);
end
Options = int32([addclass, importance, localImp, proximity, oob_prox, do_trace, keep_forest, replace, Stratify, keep_inbag]);
if DEBUG_ON
%print the parameters that i am sending in
fprintf('size(x) %d\n',size(X));
fprintf('size(y) %d\n',size(Y));
fprintf('nclass %d\n',nclass);
fprintf('size(ncat) %d\n',size(ncat));
fprintf('maxcat %d\n',maxcat);
fprintf('size(sampsize) %d\n',size(sampsize));
fprintf('sampsize[0] %d\n',sampsize(1));
fprintf('Stratify %d\n',Stratify);
fprintf('Proximity %d\n',proximity);
fprintf('oob_prox %d\n',oob_prox);
fprintf('strata %d\n',strata);
fprintf('ntree %d\n',ntree);
fprintf('mtry %d\n',mtry);
fprintf('ipi %d\n',ipi);
fprintf('classwt %f\n',classwt);
fprintf('cutoff %f\n',cutoff);
fprintf('nodesize %f\n',nodesize);
end
[nrnodes,ntree,xbestsplit,classwt,cutoff,treemap,nodestatus,nodeclass,bestvar,ndbigtree,mtry ...
outcl, counttr, prox, impmat, impout, impSD, errtr, inbag] ...
= mexClassRF_train(X',int32(Y_new),length(unique(Y)),ntree,mtry,int32(ncat), ...
int32(maxcat), int32(sampsize), strata, Options, int32(ipi), ...
classwt, cutoff, int32(nodesize),int32(nsum));
model.nrnodes=nrnodes;
model.ntree=ntree;
model.xbestsplit=xbestsplit;
model.classwt=classwt;
model.cutoff=cutoff;
model.treemap=treemap;
model.nodestatus=nodestatus;
model.nodeclass=nodeclass;
model.bestvar = bestvar;
model.ndbigtree = ndbigtree;
model.mtry = mtry;
model.orig_labels=orig_labels;
model.new_labels=new_labels;
model.nclass = length(unique(Y));
model.outcl = outcl;
model.counttr = counttr;
if proximity
model.proximity = prox;
else
model.proximity = [];
end
model.localImp = impmat;
model.importance = impout;
model.importanceSD = impSD;
model.errtr = errtr';
model.inbag = inbag;
model.votes = counttr';
model.oob_times = sum(counttr)';
clear mexClassRF_train
%keyboard
1;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
structureTensorImage2.m
|
.m
|
vesicle-cnn-2-master/vesiclerf-2/tools/structure_tensor/structureTensorImage2.m
| 2,078 |
utf_8
|
a9f4eb4f44095b9695bc66b79eca3cbd
|
%[eig1, eig2, cw] = structureTensorImage2(im, s, sg)
%s: smoothing sigma
%sg: sigma gaussian for summation weights
%window size is adapted
function [eig1, eig2, cw] = structureTensorImage2(im, s, sg)
w = 2*sg;
[gx,gy,mag] = gradientImg(double(im),s);
clear mag;
S_0_x = gx.*gx;
S_0_xy = gx.*gy;
S_0_y = gy.*gy;
clear gx
clear gy
sum_x = 1/(2*pi*sg^2) * S_0_x;
sum_y = 1/(2*pi*sg^2) *S_0_y;
sum_xy = 1/(2*pi*sg^2) *S_0_xy;
%sum_x
sl = sum_x;
sr = sum_x;
su = sum_x;
sd = sum_x;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_x = sum_x + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
%sum_y
sl = sum_y;
sr = sum_y;
su = sum_y;
sd = sum_y;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_y = sum_y + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
%sum_xy
sl = sum_xy;
sr = sum_xy;
su = sum_xy;
sd = sum_xy;
for m = 1:w
mdiag = sqrt(2*m^2);
sl = shiftLeft(sl);
sr = shiftRight(sr);
su = shiftUp(su);
sd = shiftDown(sd);
sum_xy = sum_xy + 1/(2*pi*sg^2)*exp(-(-m^2)/(2*sg^2))*(sl + sr + su + sd) + 1/(2*pi*sg^2)*exp(-(mdiag^2+mdiag^2)/(2*sg^2))*(shiftLeft(su) + shiftRight(su) + shiftLeft(sd) + shiftRight(sd));
end
clear sl
clear sr
clear su
clear sd
eig1 = zeros(size(im));
eig2 = zeros(size(im));
for i=1:length(im(:))
e2 = (sum_x(i) + sum_y(i))/2 + sqrt(4*sum_xy(i)*sum_xy(i)+(sum_x(i)-sum_y(i))^2)/2;
e1 = (sum_x(i) + sum_y(i))/2 - sqrt(4*sum_xy(i)*sum_xy(i)+(sum_x(i)-sum_y(i))^2)/2;
eig1(i) = e1;
eig2(i) = e2;
end
cw = ((eig1-eig2)./(eig1+eig2)).^2;
cw(isnan(cw)) = 0;
|
github
|
andrewwarrington/vesicle-cnn-2-master
|
gradientImg.m
|
.m
|
vesicle-cnn-2-master/vesiclerf-2/tools/structure_tensor/gradientImg.m
| 413 |
utf_8
|
caa4df879004f65177163e8185112940
|
%function [gx, gy, mag] = gradientImg(im, s)
function [gx, gy, mag] = gradientImg(im, s)
% $$$ fg = fspecial('gaussian',4*s,s);
% $$$ fs = fspecial('sobel');
% $$$
% $$$ fgy = filter2(fs,fg);
% $$$ fgx = filter2(fs',fg);
% $$$
% $$$ fgm = sqrt(fgx.^2 + fgy.^2);
% $$$
% $$$ gy = filter2(fgy,im);
% $$$ gx = filter2(fgx,im);
im = imsmooth_st(double(im),s);
[gx,gy] = gradient(im);
mag = sqrt(gx.^2 + gy.^2);
|
github
|
mariajantz/kalmanGUI-master
|
test_dist_plot.m
|
.m
|
kalmanGUI-master/test_dist_plot.m
| 2,536 |
utf_8
|
caffe3cf8576dac3aef5983900c6bae9
|
close all;
mcell = {[1 0] [0 0] [5 .5]};
pcell = {[1 .1; .1 1], [.5 0; 0 1], [1 .1; .1 .5]}; %MUST BE SQUARE POSITIVE MATRIX
plot_dist(mcell, pcell);
function plot_dist(mu_cell, phi_cell)
%define colors for the signal, model, and combined distributions
redcolors = [184 6 0; 229 136 125]/255; %dark, then light
bluecolors = [12 48 181; 134 154 219]/255;
greencolors = [35 97 15; 112 176 83]/255;
colors = {redcolors, bluecolors, greencolors};
for i=1:3
mu = mu_cell{i};
phi = phi_cell{i};
ell_cell = calc_ellpr(mu, phi);
figure(10); hold on;
plot(ell_cell{1}(:, 1), ell_cell{1}(:, 2), 'Linewidth', 2, 'Color', colors{i}(1, :));
plot(ell_cell{2}(:, 1), ell_cell{2}(:, 2), 'Linewidth', 2, 'Color', colors{i}(2, :));
axis equal;
end
end
function ellipse_pr = calc_ellpr(mu, phi)
%calculate F, midpt, sd, inds for sd1 and sd2
%call function to return ellipse array
%TODO: set this according to actual values
%should use mu + 2* sqrt of variance to determine limits
%choose the range of the plot
varmat = sqrt(phi)*2.5; %calculate the std dev matrix
nsamples = 200;
x = (mu(1)-varmat(1, 1)):(2*varmat(1, 1)/nsamples):(mu(1)+varmat(1, 1));
y = (mu(2)-varmat(2, 2)):(2*varmat(2, 2)/nsamples):(mu(2)+varmat(2, 2));
[X,Y] = meshgrid(x,y);
%calculate multivariate normal distribution
F = mvnpdf([X(:) Y(:)],mu,phi);
F = reshape(F,length(y),length(x));
%find high middle point
[midpt, idx] = max(F(:));
[row, col] = ind2sub(size(F), idx);
%find 1, 2 std dev
sdev = std(F(:, col));
%discrimination value = how selectively it finds circle
discval = .01;
sd1inds = not(abs(sign(sign(midpt-sdev-discval - F) + sign(midpt-sdev+discval - F))));
sd2inds = not(abs(sign(sign(midpt-2*sdev-discval - F) + sign(midpt-2*sdev+discval - F))));
%assign values and center on zero
%and normalize back to mu location
ell_vals1 = (calc_ell(sd1inds)-[row,col]).*([range(x) range(y)]/nsamples) + mu;
ell_vals2 = (calc_ell(sd2inds)-[row,col]).*([range(x) range(y)]/nsamples) + mu;
ellipse_pr = {ell_vals1, ell_vals2};
end
function ellipse_arr = calc_ell(inds)
%switch these values to the correct coordinate system for normal plotting
%and normalize to the correct scale
[row, col]=find(inds>0);
%for each row, find the extreme columns
vals1 = []; vals2 = [];
for x=1:length(col)
xidx = find(col==col(x));
vals1(end+1, :) = [row(min(xidx)), col(x)];
vals2(end+1, :) = [row(max(xidx)), col(x)];
end
ellipse_arr = [[vals1(:, 1); flipud(vals2(:, 1)); vals1(1, 1)], ...
[vals1(:, 2); flipud(vals2(:, 2)); vals1(1, 2)]];
end
|
github
|
acados/qpOASES-master
|
make.m
|
.m
|
qpOASES-master/interfaces/simulink/make.m
| 8,234 |
utf_8
|
38b8382423ef0ca7023a8d6912f0416b
|
function [] = make( varargin )
%MAKE Compiles the Simulink interface of qpOASES_e.
%
%Type make to compile all interfaces that
% have been modified,
%type make clean to delete all compiled interfaces,
%type make clean all to first delete and then compile
% all interfaces,
%type make 'name' to compile only the interface with
% the given name (if it has been modified),
%type make 'opt' to compile all interfaces using the
% given compiler options
%
%Copyright (C) 2013-2015 by Hans Joachim Ferreau, Andreas Potschka,
%Christian Kirches et al. All rights reserved.
%%
%% This file is part of qpOASES.
%%
%% qpOASES -- An Implementation of the Online Active Set Strategy.
%% Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
%% Christian Kirches et al. All rights reserved.
%%
%% qpOASES is free software; you can redistribute it and/or
%% modify it under the terms of the GNU Lesser General Public
%% License as published by the Free Software Foundation; either
%% version 2.1 of the License, or (at your option) any later version.
%%
%% qpOASES is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
%% See the GNU Lesser General Public License for more details.
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with qpOASES; if not, write to the Free Software
%% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
%%
%%
%% Filename: interfaces/simulink/make.m
%% Author: Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
%% Version: 3.1embedded
%% Date: 2007-2015
%%
%% consistency check
if ( exist( [pwd, '/make.m'],'file' ) == 0 )
error( ['ERROR (',mfilename '.m): Run this make script directly within the directory', ...
'<qpOASES-inst-dir>/interfaces/simulink, please.'] );
end
if ( nargin > 2 )
error( ['ERROR (',mfilename '.m): At most two make arguments supported!'] );
else
[ doClean,fcnNames,userFlags ] = analyseMakeArguments( nargin,varargin );
end
%% define compiler settings
QPOASESPATH = '../../';
DEBUGFLAGS = ' ';
%DEBUGFLAGS = ' -g CXXDEBUGFLAGS=''$CXXDEBUGFLAGS -Wall -pedantic -Wshadow'' ';
IFLAGS = [ '-I. -I',QPOASESPATH,'include',' -I',QPOASESPATH,'src',' ' ];
CFLAGS = [ IFLAGS, DEBUGFLAGS, '-largeArrayDims -D__MATLAB__ -D__SINGLE_OBJECT__ -Dinline="" -Dsnprintf="_snprintf"',' ' ];
defaultFlags = '-O -D__NO_COPYRIGHT__ '; %% -D__NO_COPYRIGHT__ -D__SUPPRESSANYOUTPUT__ -D__MANY_CONSTRAINTS__
if ( ispc == 0 )
CFLAGS = [ CFLAGS, '-DLINUX ',' ' ];
else
CFLAGS = [ CFLAGS, '-DWIN32 ',' ' ];
end
if ( isempty(userFlags) > 0 )
CFLAGS = [ CFLAGS, defaultFlags,' ' ];
else
CFLAGS = [ CFLAGS, userFlags,' ' ];
end
mexExt = eval('mexext');
%% ensure copyright notice is displayed
if ~isempty( strfind( CFLAGS,'-D__NO_COPYRIGHT__' ) )
printCopyrightNotice( );
end
%% clean if desired
if ( doClean > 0 )
eval( 'delete *.o;' );
eval( ['delete *.',mexExt,'*;'] );
disp( [ 'INFO (',mfilename '.m): Cleaned all compiled files.'] );
pause( 0.2 );
end
if ( ~isempty(userFlags) )
disp( [ 'INFO (',mfilename '.m): Compiling all files with user-defined compiler flags (''',userFlags,''')...'] );
end
%% call mex compiler
for ii=1:length(fcnNames)
cmd = [ 'mex -output ', fcnNames{ii}, ' ', CFLAGS, [fcnNames{ii},'.c'] ];
if ( exist( [fcnNames{ii},'.',mexExt],'file' ) == 0 )
eval( cmd );
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] );
else
% check modification time of source/Make files and compiled mex file
cppFile = dir( [pwd,'/',fcnNames{ii},'.c'] );
cppFileTimestamp = getTimestamp( cppFile );
makeFile = dir( [pwd,'/make.m'] );
makeFileTimestamp = getTimestamp( makeFile );
mexFile = dir( [pwd,'/',fcnNames{ii},'.',mexExt] );
if ( isempty(mexFile) == 0 )
mexFileTimestamp = getTimestamp( mexFile );
else
mexFileTimestamp = 0;
end
if ( ( cppFileTimestamp >= mexFileTimestamp ) || ...
( makeFileTimestamp >= mexFileTimestamp ) )
eval( cmd );
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] );
else
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' already exists.'] );
end
end
end
%% add qpOASES directory to path
path( path,pwd );
end
function [ doClean,fcnNames,userIFlags ] = analyseMakeArguments( nArgs,args )
doClean = 0;
fcnNames = [];
userIFlags = [];
switch ( nArgs )
case 1
if ( strcmp( args{1},'all' ) > 0 )
fcnNames = { 'qpOASES_e_QProblemB','qpOASES_e_QProblem' };
elseif ( strcmp( args{1},'qpOASES_e_QProblemB' ) > 0 )
fcnNames = { 'qpOASES_e_QProblemB' };
elseif ( strcmp( args{1},'qpOASES_e_QProblem' ) > 0 )
fcnNames = { 'qpOASES_e_QProblem' };
elseif ( strcmp( args{1},'clean' ) > 0 )
doClean = 1;
elseif ( strcmp( args{1}(1),'-' ) > 0 )
% make clean all with user-specified compiler flags
userIFlags = args{1};
doClean = 1;
fcnNames = { 'qpOASES_e_QProblemB','qpOASES_e_QProblem' };
else
error( ['ERROR (',mfilename '.m): Invalid first argument (''',args{1},''')!'] );
end
case 2
if ( strcmp( args{1},'clean' ) > 0 )
doClean = 1;
else
error( ['ERROR (',mfilename '.m): First argument must be ''clean'' if two arguments are provided!'] );
end
if ( strcmp( args{2},'all' ) > 0 )
fcnNames = { 'qpOASES_e_QProblemB','qpOASES_e_QProblem' };
elseif ( strcmp( args{2},'qpOASES_e_QProblemB' ) > 0 )
fcnNames = { 'qpOASES_e_QProblemB' };
elseif ( strcmp( args{2},'qpOASES_e_QProblem' ) > 0 )
fcnNames = { 'qpOASES_e_QProblem' };
else
error( ['ERROR (',mfilename '.m): Invalid second argument (''',args{2},''')!'] );
end
otherwise
doClean = 0;
fcnNames = { 'qpOASES_e_QProblemB','qpOASES_e_QProblem' };
userIFlags = [];
end
end
function [ timestamp ] = getTimestamp( dateString )
try
timestamp = dateString.datenum;
catch
timestamp = Inf;
end
end
function [ ] = printCopyrightNotice( )
disp( ' ' );
disp( 'qpOASES -- An Implementation of the Online Active Set Strategy.' );
disp( 'Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,' );
disp( 'Christian Kirches et al. All rights reserved.' );
disp( ' ' );
disp( 'qpOASES is distributed under the terms of the' );
disp( 'GNU Lesser General Public License 2.1 in the hope that it will be' );
disp( 'useful, but WITHOUT ANY WARRANTY; without even the implied warranty' );
disp( 'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.' );
disp( 'See the GNU Lesser General Public License for more details.' );
disp( ' ' );
disp( ' ' );
end
%%
%% end of file
%%
|
github
|
acados/qpOASES-master
|
qpOASES_e_auxInput.m
|
.m
|
qpOASES-master/interfaces/matlab/qpOASES_e_auxInput.m
| 4,464 |
utf_8
|
3cda1474246b8abd61a797cea451dbd1
|
%qpOASES -- An Implementation of the Online Active Set Strategy.
%Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
%Christian Kirches et al. All rights reserved.
%
%qpOASES is distributed under the terms of the
%GNU Lesser General Public License 2.1 in the hope that it will be
%useful, but WITHOUT ANY WARRANTY; without even the implied warranty
%of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
%See the GNU Lesser General Public License for more details.
%
%---------------------------------------------------------------------------------
%
%Returns a struct containing all possible auxiliary inputs to be passed
%to qpOASES_e.
%
%Call
% auxInput = qpOASES_e_auxInput();
%to obtain a struct with all auxiliary inputs empty.
%
%Call
% auxInput = qpOASES_e_auxInput( 'input1',value1,'input2',value2,... )
%to obtain a struct with 'input1' set to value1 etc. and all remaining
%auxiliary inputs empty.
%
%Call
% auxInput = qpOASES_e_auxInput( oldInputs,'input1',value1,... )
%to obtain a copy of the options struct oldInputs but with 'input1' set to
%value1 etc.
%
%
%qpOASES_e features the following auxiliary inputs:
% hessianType - Provide information on Hessian matrix:
% 0: Hessian is zero matrix (i.e. LP formulation)
% 1: Hessian is identity matrix
% 2: Hessian is (strictly) positive definite
% 3: Hessian is positive definite on null space
% of active bounds/constraints
% 4: Hessian is positive semi-definite.
% 5: Hessian is indefinite
% Leave hessianType empty if Hessian type is unknown.
% x0 - Initial guess for optimal primal solution.
% guessedWorkingSetB - Initial guess for working set of bounds at
% optimal solution (nV elements or empty).
% guessedWorkingSetC - Initial guess for working set of constraints at
% optimal solution (nC elements or empty).
% The working sets needs to be encoded as follows:
% 1: bound/constraint at its upper bound
% 0: bound/constraint not at any bound
% -1: bound/constraint at its lower bound
% R - Cholesky factor of Hessian matrix (upper-triangular);
% only used if both guessedWorkingSets are empty
% and option initialStatusBounds is set to 0.
%
%
%See also QPOASES, QPOASES_SEQUENCE, QPOASES_OPTIONS
%
%
%For additional information see the qpOASES User's Manual or
%visit http://www.qpOASES.org/.
%
%Please send remarks and questions to [email protected]!
function [ auxInput ] = qpOASES_e_auxInput( varargin )
firstIsStruct = 0;
if ( nargin == 0 )
auxInput = qpOASES_e_emptyAuxInput();
else
if ( isstruct( varargin{1} ) )
if ( mod( nargin,2 ) ~= 1 )
error('ERROR (qpOASES_e_auxInput): Auxiliary inputs must be specified in pairs!');
end
auxInput = varargin{1};
firstIsStruct = 1;
else
if ( mod( nargin,2 ) ~= 0 )
error('ERROR (qpOASES_e_auxInput): Auxiliary inputs must be specified in pairs!');
end
auxInput = qpOASES_e_emptyAuxInput();
end
end
% set options to user-defined values
for i=(1+firstIsStruct):2:nargin
argName = varargin{i};
argValue = varargin{i+1};
if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) )
error('ERROR (qpOASES_e_auxInput): Argmument no. %d has to be a non-empty string!',i );
end
if ( ( ischar(argValue) ) || ( ~isnumeric( argValue ) ) )
error('ERROR (qpOASES_e_auxInput): Argmument no. %d has to be a numerical constant!',i+1 );
end
if ( ~isfield( auxInput,argName ) )
error('ERROR (qpOASES_e_auxInput): Argmument no. %d is not a valid auxiliary input!',i );
end
eval( ['auxInput.',argName,' = argValue;'] );
end
end
function [ auxInput ] = qpOASES_e_emptyAuxInput( )
% setup auxiliary input struct with all entries empty
auxInput = struct( 'hessianType', [], ...
'x0', [], ...
'guessedWorkingSetB', [], ...
'guessedWorkingSetC', [], ...
'R', [] ...
);
end
|
github
|
acados/qpOASES-master
|
make.m
|
.m
|
qpOASES-master/interfaces/matlab/make.m
| 8,288 |
utf_8
|
3f51786f16fadf166e502ca7a1ea2538
|
function [] = make( varargin )
%MAKE Compiles the Matlab interface of qpOASES_e.
%
%Type make to compile all interfaces that
% have been modified,
%type make clean to delete all compiled interfaces,
%type make clean all to first delete and then compile
% all interfaces,
%type make 'name' to compile only the interface with
% the given name (if it has been modified),
%type make 'opt' to compile all interfaces using the
% given compiler options
%
%Copyright (C) 2013-2015 by Hans Joachim Ferreau, Andreas Potschka,
%Christian Kirches et al. All rights reserved.
%%
%% This file is part of qpOASES.
%%
%% qpOASES -- An Implementation of the Online Active Set Strategy.
%% Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
%% Christian Kirches et al. All rights reserved.
%%
%% qpOASES is free software; you can redistribute it and/or
%% modify it under the terms of the GNU Lesser General Public
%% License as published by the Free Software Foundation; either
%% version 2.1 of the License, or (at your option) any later version.
%%
%% qpOASES is distributed in the hope that it will be useful,
%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
%% See the GNU Lesser General Public License for more details.
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with qpOASES; if not, write to the Free Software
%% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
%%
%%
%% Filename: interfaces/matlab/make.m
%% Author: Hans Joachim Ferreau, Andreas Potschka, Christian Kirches
%% Version: 3.1embedded
%% Date: 2007-2015
%%
%% consistency check
if ( exist( [pwd, '/make.m'],'file' ) == 0 )
error( ['ERROR (',mfilename '.m): Run this make script directly within the directory', ...
'<qpOASES-inst-dir>/interfaces/matlab, please.'] );
end
if ( nargin > 2 )
error( ['ERROR (',mfilename '.m): At most two make arguments supported!'] );
else
[ doClean,fcnNames,userFlags ] = analyseMakeArguments( nargin,varargin );
end
%% define compiler settings
QPOASESPATH = '../../';
DEBUGFLAGS = ' ';
%DEBUGFLAGS = ' -g CXXDEBUGFLAGS=''$CXXDEBUGFLAGS -Wall -pedantic -Wshadow'' ';
IFLAGS = [ '-I. -I',QPOASESPATH,'include',' -I',QPOASESPATH,'src',' ' ];
CFLAGS = [ IFLAGS, DEBUGFLAGS, '-largeArrayDims -D__MATLAB__ -D__SINGLE_OBJECT__ -Dinline="" -Dsnprintf="_snprintf"',' ' ];
defaultFlags = '-O -D__NO_COPYRIGHT__ '; %% -D__NO_COPYRIGHT__ -D__SUPPRESSANYOUTPUT__ -D__DEBUG__
if ( ispc == 0 )
CFLAGS = [ CFLAGS, '-DLINUX ',' ' ];
else
CFLAGS = [ CFLAGS, '-DWIN32 ',' ' ];
end
if ( isempty(userFlags) > 0 )
CFLAGS = [ CFLAGS, defaultFlags,' ' ];
else
CFLAGS = [ CFLAGS, userFlags,' ' ];
end
mexExt = eval('mexext');
%% ensure copyright notice is displayed
if ~isempty( strfind( CFLAGS,'-D__NO_COPYRIGHT__' ) )
printCopyrightNotice( );
end
%% clean if desired
if ( doClean > 0 )
eval( 'delete *.o;' );
eval( ['delete *.',mexExt,'*;'] );
disp( [ 'INFO (',mfilename '.m): Cleaned all compiled files.'] );
pause( 0.2 );
end
if ( ~isempty(userFlags) )
disp( [ 'INFO (',mfilename '.m): Compiling all files with user-defined compiler flags (''',userFlags,''')...'] );
end
%% call mex compiler
for ii=1:length(fcnNames)
cmd = [ 'mex -output ', fcnNames{ii}, ' ', CFLAGS, [fcnNames{ii},'.c'] ];
if ( exist( [fcnNames{ii},'.',mexExt],'file' ) == 0 )
eval( cmd );
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] );
else
% check modification time of source/Make files and compiled mex file
cppFile = dir( [pwd,'/',fcnNames{ii},'.c'] );
cppFileTimestamp = getTimestamp( cppFile );
utilsFile = dir( [pwd,'/qpOASES_matlab_utils.c'] );
utilsFileTimestamp = getTimestamp( utilsFile );
makeFile = dir( [pwd,'/make.m'] );
makeFileTimestamp = getTimestamp( makeFile );
mexFile = dir( [pwd,'/',fcnNames{ii},'.',mexExt] );
if ( isempty(mexFile) == 0 )
mexFileTimestamp = getTimestamp( mexFile );
else
mexFileTimestamp = 0;
end
if ( ( cppFileTimestamp >= mexFileTimestamp ) || ...
( utilsFileTimestamp >= mexFileTimestamp ) || ...
( makeFileTimestamp >= mexFileTimestamp ) )
eval( cmd );
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' successfully created.'] );
else
disp( [ 'INFO (',mfilename '.m): ', fcnNames{ii},'.',mexExt, ' already exists.'] );
end
end
end
%% add qpOASES directory to path
path( path,pwd );
end
function [ doClean,fcnNames,userIFlags ] = analyseMakeArguments( nArgs,args )
doClean = 0;
fcnNames = [];
userIFlags = [];
switch ( nArgs )
case 1
if ( strcmp( args{1},'all' ) > 0 )
fcnNames = { 'qpOASES_e','qpOASES_e_sequence' };
elseif ( strcmp( args{1},'qpOASES_e' ) > 0 )
fcnNames = { 'qpOASES_e' };
elseif ( strcmp( args{1},'qpOASES_e_sequence' ) > 0 )
fcnNames = { 'qpOASES_e_sequence' };
elseif ( strcmp( args{1},'clean' ) > 0 )
doClean = 1;
elseif ( strcmp( args{1}(1),'-' ) > 0 )
% make clean all with user-specified compiler flags
userIFlags = args{1};
doClean = 1;
fcnNames = { 'qpOASES_e','qpOASES_e_sequence' };
else
error( ['ERROR (',mfilename '.m): Invalid first argument (''',args{1},''')!'] );
end
case 2
if ( strcmp( args{1},'clean' ) > 0 )
doClean = 1;
else
error( ['ERROR (',mfilename '.m): First argument must be ''clean'' if two arguments are provided!'] );
end
if ( strcmp( args{2},'all' ) > 0 )
fcnNames = { 'qpOASES_e','qpOASES_e_sequence' };
elseif ( strcmp( args{2},'qpOASES_e' ) > 0 )
fcnNames = { 'qpOASES_e' };
elseif ( strcmp( args{2},'qpOASES_e_sequence' ) > 0 )
fcnNames = { 'qpOASES_e_sequence' };
else
error( ['ERROR (',mfilename '.m): Invalid second argument (''',args{2},''')!'] );
end
otherwise
fcnNames = { 'qpOASES_e','qpOASES_e_sequence' };
end
end
function [ timestamp ] = getTimestamp( dateString )
try
timestamp = dateString.datenum;
catch
timestamp = Inf;
end
end
function [ ] = printCopyrightNotice( )
disp( ' ' );
disp( 'qpOASES -- An Implementation of the Online Active Set Strategy.' );
disp( 'Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,' );
disp( 'Christian Kirches et al. All rights reserved.' );
disp( ' ' );
disp( 'qpOASES is distributed under the terms of the' );
disp( 'GNU Lesser General Public License 2.1 in the hope that it will be' );
disp( 'useful, but WITHOUT ANY WARRANTY; without even the implied warranty' );
disp( 'of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.' );
disp( 'See the GNU Lesser General Public License for more details.' );
disp( ' ' );
disp( ' ' );
end
%%
%% end of file
%%
|
github
|
acados/qpOASES-master
|
qpOASES_e_options.m
|
.m
|
qpOASES-master/interfaces/matlab/qpOASES_e_options.m
| 10,413 |
utf_8
|
7094632bf1ee692f7c7d22ac38754401
|
%qpOASES -- An Implementation of the Online Active Set Strategy.
%Copyright (C) 2007-2015 by Hans Joachim Ferreau, Andreas Potschka,
%Christian Kirches et al. All rights reserved.
%
%qpOASES is distributed under the terms of the
%GNU Lesser General Public License 2.1 in the hope that it will be
%useful, but WITHOUT ANY WARRANTY; without even the implied warranty
%of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
%See the GNU Lesser General Public License for more details.
%
%---------------------------------------------------------------------------------
%
%Returns a struct containing values for all options to be used within qpOASES_e.
%
%Call
% options = qpOASES_e_options( 'default' );
% options = qpOASES_e_options( 'reliable' );
% options = qpOASES_e_options( 'MPC' );
%to obtain a set of default options or a pre-defined set of options tuned
%for reliable or fast QP solution, respectively.
%
%Call
% options = qpOASES_e_options( 'option1',value1,'option2',value2,... )
%to obtain a set of default options but with 'option1' set to value1 etc.
%
%Call
% options = qpOASES_e_options( oldOptions,'option1',value1,... )
%to obtain a copy of the options struct oldOptions but with 'option1' set
%to value1 etc.
%
%Call
% options = qpOASES_e_options( 'default', 'option1',value1,... )
% options = qpOASES_e_options( 'reliable','option1',value1,... )
% options = qpOASES_e_options( 'MPC', 'option1',value1,... )
%to obtain a set of default options or a pre-defined set of options tuned
%for reliable or fast QP solution, respectively, but with 'option1' set to
%value1 etc.
%
%
%qpOASES_e features the following options:
% maxIter - Maximum number of iterations (if set
% to -1, a value is chosen heuristically)
% maxCpuTime - Maximum CPU time in seconds (if set
% to -1, only iteration limit is used)
% printLevel - 0: no printed output,
% 1: only error messages are printed,
% 2: iterations and error messages are printed,
% 3: all available messages are printed.
%
% enableRamping - Enables (1) or disables (0) ramping.
% enableFarBounds - Enables (1) or disables (0) the use of
% far bounds.
% enableFlippingBounds - Enables (1) or disables (0) the use of
% flipping bounds.
% enableRegularisation - Enables (1) or disables (0) automatic
% Hessian regularisation.
% enableFullLITests - Enables (1) or disables (0) condition-hardened
% (but more expensive) LI test.
% enableNZCTests - Enables (1) or disables (0) nonzero curvature
% tests.
% enableDriftCorrection - Specifies the frequency of drift corrections:
% 0: turns them off,
% 1: uses them at each iteration etc.
% enableCholeskyRefactorisation - Specifies the frequency of a full re-
% factorisation of projected Hessian matrix:
% 0: turns them off,
% 1: uses them at each iteration etc.
% enableEqualities - Specifies whether equalities should be treated
% as always active (1) or not (0)
%
% terminationTolerance - Relative termination tolerance to stop homotopy.
% boundTolerance - If upper and lower bounds differ less than this
% tolerance, they are regarded equal, i.e. as
% equality constraint.
% boundRelaxation - Initial relaxation of bounds to start homotopy
% and initial value for far bounds.
% epsNum - Numerator tolerance for ratio tests.
% epsDen - Denominator tolerance for ratio tests.
% maxPrimalJump - Maximum allowed jump in primal variables in
% nonzero curvature tests.
% maxDualJump - Maximum allowed jump in dual variables in
% linear independence tests.
%
% initialRamping - Start value for ramping strategy.
% finalRamping - Final value for ramping strategy.
% initialFarBounds - Initial size for far bounds.
% growFarBounds - Factor to grow far bounds.
% initialStatusBounds - Initial status of bounds at first iteration:
% 0: all bounds inactive,
% -1: all bounds active at their lower bound,
% +1: all bounds active at their upper bound.
% epsFlipping - Tolerance of squared Cholesky diagonal factor
% which triggers flipping bound.
% numRegularisationSteps - Maximum number of successive regularisation steps.
% epsRegularisation - Scaling factor of identity matrix used for
% Hessian regularisation.
% numRefinementSteps - Maximum number of iterative refinement steps.
% epsIterRef - Early termination tolerance for iterative
% refinement.
% epsLITests - Tolerance for linear independence tests.
% epsNZCTests - Tolerance for nonzero curvature tests.
%
%
%See also QPOASES, QPOASES_SEQUENCE, QPOASES_AUXINPUT
%
%
%For additional information see the qpOASES User's Manual or
%visit http://www.qpOASES.org/.
%
%Please send remarks and questions to [email protected]!
function [ options ] = qpOASES_e_options( varargin )
firstIsStructOrScheme = 0;
if ( nargin == 0 )
options = qpOASES_e_default_options();
else
if ( isstruct( varargin{1} ) )
if ( mod( nargin,2 ) ~= 1 )
error('ERROR (qpOASES_e_options): Options must be specified in pairs!');
end
options = varargin{1};
firstIsStructOrScheme = 1;
else
if ( ischar( varargin{1} ) )
if ( mod( nargin,2 ) == 0 )
options = qpOASES_e_default_options();
else
if ( ( nargin > 1 ) && ( ischar( varargin{nargin} ) ) )
error('ERROR (qpOASES_e_options): Options must be specified in pairs!');
end
switch ( varargin{1} )
case 'default'
options = qpOASES_e_default_options();
case 'reliable'
options = qpOASES_e_reliable_options();
case {'MPC','mpc','fast'}
options = qpOASES_e_MPC_options();
otherwise
error( ['ERROR (qpOASES_e_options): Only the following option schemes are defined: ''default'', ''reliable'', ''MPC''!'] );
end
firstIsStructOrScheme = 1;
end
else
error('ERROR (qpOASES_e_options): First argument needs to be a string or an options struct!');
end
end
end
% set options to user-defined values
for i=(1+firstIsStructOrScheme):2:nargin
argName = varargin{i};
argValue = varargin{i+1};
if ( ( isempty( argName ) ) || ( ~ischar( argName ) ) )
error('ERROR (qpOASES_e_options): Argmument no. %d has to be a non-empty string!',i );
end
if ( ( ischar(argValue) ) || ( ~isscalar( argValue ) ) )
error('ERROR (qpOASES_e_options): Argmument no. %d has to be a scalar constant!',i+1 );
end
if ( ~isfield( options,argName ) )
error('ERROR (qpOASES_e_options): Argmument no. %d is an invalid option!',i );
end
eval( ['options.',argName,' = ',num2str(argValue),';'] );
end
end
function [ options ] = qpOASES_e_default_options( )
% setup options struct with default values
options = struct( 'maxIter', -1, ...
'maxCpuTime', -1, ...
'printLevel', 1, ...
...
'enableRamping', 1, ...
'enableFarBounds', 1, ...
'enableFlippingBounds', 1, ...
'enableRegularisation', 0, ...
'enableFullLITests', 0, ...
'enableNZCTests', 1, ...
'enableDriftCorrection', 1, ...
'enableCholeskyRefactorisation', 0, ...
'enableEqualities', 0, ...
...
'terminationTolerance', 5.0e6*eps, ...
'boundTolerance', 1.0e6*eps, ...
'boundRelaxation', 1.0e4, ...
'epsNum', -1.0e3*eps, ...
'epsDen', 1.0e3*eps, ...
'maxPrimalJump', 1.0e8, ...
'maxDualJump', 1.0e8, ...
...
'initialRamping', 0.5, ...
'finalRamping', 1.0, ...
'initialFarBounds', 1.0e6, ...
'growFarBounds', 1.0e3, ...
'initialStatusBounds', -1, ...
'epsFlipping', 1.0e3*eps, ...
'numRegularisationSteps', 0, ...
'epsRegularisation', 1.0e3*eps, ...
'numRefinementSteps', 1, ...
'epsIterRef', 1.0e2*eps, ...
'epsLITests', 1.0e5*eps, ...
'epsNZCTests', 3.1e3*eps );
end
function [ options ] = qpOASES_e_reliable_options( )
% setup options struct with values for most reliable QP solution
options = qpOASES_e_default_options( );
options.enableFullLITests = 1;
options.enableCholeskyRefactorisation = 1;
options.numRefinementSteps = 2;
end
function [ options ] = qpOASES_e_MPC_options( )
% setup options struct with values for most reliable QP solution
options = qpOASES_e_default_options( );
options.enableRamping = 0;
options.enableFarBounds = 1;
options.enableFlippingBounds = 0;
options.enableRegularisation = 1;
options.enableNZCTests = 0;
options.enableDriftCorrection = 0;
options.enableEqualities = 1;
options.terminationTolerance = 1.0e9*eps;
options.initialStatusBounds = 0;
options.numRegularisationSteps = 1;
options.numRefinementSteps = 0;
end
|
github
|
joe-of-all-trades/OCT_Analysis-master
|
datainterp.m
|
.m
|
OCT_Analysis-master/datainterp.m
| 582 |
utf_8
|
bbf962dc7fa6305d14a041e5016ea8a5
|
% This script is written by Chao-yuan Yeh. All copyrights reserved.
function output = datainterp( input, varargin)
if strcmpi(varargin, '45')
temp = diff(round(input(:,1)/sin(pi/4)));
elseif strcmpi(varargin, 'x')
temp = diff(round(input(:,1)));
elseif strcmpi(varargin, 'y')
temp = diff(round(input(:,2)));
end
index = find(abs(temp)==2);
index = index + (1:length(index))';
temp2 = zeros(size(input,1)+length(index), size(input,2));
temp2(index,:) = nan;
temp2(~isnan(temp2)) = input;
temp2(index,:) = (temp2(index-1,:) + temp2(index+1,:))/2;
output = temp2;
end
|
github
|
joe-of-all-trades/OCT_Analysis-master
|
OCT_process_file.m
|
.m
|
OCT_Analysis-master/OCT_process_file.m
| 2,548 |
utf_8
|
40998a86705277ee1ce8757e6041a103
|
% This script is written by Chao-Yuan Yeh. All copyrights reserved.
function OCT_process_file_pub
root_folder = uigetdir('', 'select root folder containing all OCT data');
recur_proc(root_folder)
% Consider alternative implementation using built-in genpath function
matlab_path = strsplit(matlabpath, ';');
home_path = matlab_path{1};
cd(home_path)
disp('task completed')
end
function recur_proc(foldername)
% function that goes through folder structure resursively and process OCT
% files along the way
cd(foldername)
folderlist = dir;
sublist = folderlist([folderlist(:).isdir] &...
~strcmp({folderlist(:).name}, '.') &...
~strcmp({folderlist(:).name}, '..'));
if ~exist('filename_proccesed.log', 'file')
fID = fopen('filename_proccesed.log','w');
fclose(fID);
filelist = dir('*.OCT');
% Shorten file name(removing ID number) so filename can be handled by
% downstream process.
for jj = 1 : length(filelist)
movefile(filelist(jj).name,regexprep(filelist(jj).name,...
',\s[A-Z]\d{9}\s_\d*_','_'));
end
clear filelist
% Convert Cross Line OCT files into tif
filelist = dir('*Cross Line*.OCT');
for jj = 1:length(filelist)
tempstr = filelist(jj).name;
fID = fopen(fullfile(pwd,tempstr));
temp = fread(fID,'single');
% Image size is specified by "OCT Window Height=768" and "XY Scan Length= 1019"
temp = uint16(reshape(temp,768,1019,4));
img1 = flip(temp(:,:,1),1);
img2 = flip(temp(:,:,2),1);
imwrite(img1,[tempstr(1:end-4),'_1.tif']);
imwrite(img2,[tempstr(1:end-4),'_2.tif']);
fclose(fID);
clearvars tempstr fID temp img1 img2
end
clear filelist
% Convert Line OCT files into tif
filelist = dir('*_Line*.OCT');
for jj = 1:length(filelist)
tempstr = filelist(jj).name;
fID = fopen(fullfile(pwd,tempstr));
temp = fread(fID,'single');
% Image size is specified by "OCT Window Height=956" and "XY Scan Length= 1019"
temp = uint16(reshape(temp,956,1019,2));
img1 = flip(temp(:,:,1),1);
imwrite(img1,[tempstr(1:end-4),'.tif']);
fclose(fID);
clearvars tempstr fID temp img1
end
clear filelist
end
if ~isempty(sublist)
for ii = 1:length(sublist)
sublist(ii).abspath = fullfile(pwd,sublist(ii).name);
end
end
if ~isempty(sublist)
for ii = 1:length(sublist)
recur_proc(sublist(ii).abspath)
end
end
end
|
github
|
yasharhezaveh/Ensai-master
|
Lensing_TrainingImage_Generator.m
|
.m
|
Ensai-master/src/Lensing_TrainingImage_Generator.m
| 27,698 |
utf_8
|
480cbc2902655c7cbff9cd903edf1d2b
|
function [IMS,PARAMS,src_pars,log_kappa] = Lensing_TrainingImage_Generator(nsample,random_seed, WRITE , test_or_train)
%WRITE = 1
%test_or_train = 'test'
if ~exist('WRITE','var')
WRITE = 0;
end
rng(random_seed)
zLENS = 0.5;
zSOURCE = 2.00;
h=0.71;
OmegaC=0.222;
OmegaLambda=0.734;
sigNORM=0.801;
OmegaBaryon=0.0449;
OmegaM=OmegaC+OmegaBaryon;
c = 2.998E8; G = 6.67259E-11; Msun= 1.98892e30;
pc = 3.0857E16; kpc=1e3*pc; Mpc=1e6*pc;
H0=100*h*(1000/Mpc); %in units of 1/s
rhocrit=(3*H0^2)/(8*pi*G); %SI: kg/m^3
H=100*h;
Ds = (1e-6) * AngularDiameter(0,zSOURCE); %in Mpc
Dd = (1e-6) * AngularDiameter(0,zLENS); %in Mpc
Dds = (1e-6) * AngularDiameter(zLENS,zSOURCE); %in Mpc
extend_ratio = 1.6;
num_im_pix = 400;
num_im_output_pix = 192;
imside = extend_ratio * num_im_output_pix * 0.04;
imside_out = num_im_output_pix * 0.04;
[XIM , YIM]=meshgrid(linspace(-imside/2,imside/2,num_im_pix).*pi./180./3600,linspace(-imside/2,imside/2,num_im_pix).*pi./180./3600);
[X_out , Y_out]=meshgrid(linspace(-imside_out/2,imside_out/2,num_im_output_pix).*pi./180./3600,linspace(-imside_out/2,imside_out/2,num_im_output_pix).*pi./180./3600);
R_ein = zeros(nsample,1);
elp = zeros(nsample,1);
angle = zeros(nsample,1);
elp_x = zeros(nsample,1);
elp_y = zeros(nsample,1);
shear = zeros(nsample,1);
shear_angle = zeros(nsample,1);
xsource = zeros(nsample,1);
ysource = zeros(nsample,1);
XLENS = zeros(nsample,1);
YLENS = zeros(nsample,1);
src_pars = zeros(nsample,4);
magnification = zeros(nsample,1);
% datapath = getenv('Ensai_lens_training_dataset_path');
datapath = [getenv('LOCAL_SCRATCH') '/SAURON/ARCS_2/'];
galaxy_image_path = [getenv('LOCAL_SCRATCH') '/Small_Galaxy_Zoo/'];
mkdir(datapath)
file_list = ls(galaxy_image_path);
file_names = strsplit(file_list);
file_names = sortrows(file_names.',1);
file_names(1)=[];
n_GalZoo_sample = numel(file_names);
file_inds = 1:numel(file_names);
src_numpix = 212;
n_source_sample = n_GalZoo_sample;
%load([getenv('SCRATCH') '/GREAT_gal_ims.mat'],'gal_ims');
%n_source_sample = numel(gal_ims);
disp('loading...')
load([getenv('LOCAL_SCRATCH') '/GREAT_IMS30.mat'],'GREAT_IMS');
n_source_sample = size(GREAT_IMS,1)
disp('done')
[xsrc , ysrc] = meshgrid(linspace(-1,1,src_numpix).*pi./180./3600);
rfilt = sqrt(xsrc.^2+ysrc.^2);
taper = 1./(1+(rfilt./(0.6.*pi./180./3600)).^6); taper = taper./max(taper(:));
if random_seed==-1
rng('shuffle')
else
rng(random_seed)
end
max_R_ein = 3.0 * (num_im_output_pix/192);
max_elp = 0.9;
IMS = zeros(num_im_output_pix,num_im_output_pix);
log_kappa = zeros(num_im_output_pix,num_im_output_pix);
for i = 1:nsample
if mod(i,200)==0
disp(i./nsample)
end
newflux = 0;
oldflux = 1.0;
magnification(i) = 0;
SKY_IM = 0;
while newflux<(0.99 * oldflux) || (magnification(i)<2.0) || max(SKY_IM(:))==0
R_ein(i) = 0.1 + rand(1) .* (max_R_ein-0.1);
elp(i) = rand(1) * max_elp ;
angle(i) = rand(1).*360;
XLENS(i) = (rand(1)-0.5) .* 0.1;
YLENS(i) = (rand(1)-0.5) .* 0.1;
shear(i) = rand(1) .* 0.0 ;
shear_angle(i) = rand(1) .* 0.0;
image_ind = ceil(rand(1).*n_source_sample);
size_scale = rand(1).*0.8+0.2;
src_rad = 0.5.*size_scale;
[XS ,YS , ~ ,sigma_n ,MSIS] = SIE_RayTrace_fromRein(XIM,YIM,XIM,YIM,R_ein(i),elp(i),shear(i),shear_angle(i),zLENS,zSOURCE,angle(i),[XLENS(i) YLENS(i)]);
% kappa_map = get_SIE_kappa( XIM , YIM , sigma_n , elp(i) , angle(i) , XLENS(i) , YLENS(i) , zLENS , zSOURCE );
% kappa_map = imresize(kappa_map,[num_im_output_pix num_im_output_pix],'box');
% log_kappa(:,:,i) = log10(kappa_map);
[~,~,X1,Y1,X2,Y2] = Caustic_Analytical(MSIS,elp(i),'arcsec','r',0.5,2.0,angle(i),1,[XLENS(i) YLENS(i)]);
SKY_IM = 0;
xsource(i) = 10;
ysource(i) = 10;
if rand(1)<0.5
xCen = mean(X2(:));
yCen = mean(Y2(:));
[THET,RHO]=cart2pol(X2-xCen,Y2-yCen);
[X2_UP,Y2_UP]=pol2cart(THET,RHO+0.15);
X2_UP = X2_UP + xCen;
Y2_UP = Y2_UP + yCen;
max_source_xy_range = max(max(X2_UP(:))-min(X2_UP(:)) , max(Y2_UP(:))-min(Y2_UP(:))) .* 1;
while ~inpolygon(xsource(i),ysource(i),X2_UP,Y2_UP)
xsource(i) = (rand(1)-0.5).* max_source_xy_range + xCen;
ysource(i) = (rand(1)-0.5).* max_source_xy_range + yCen;
end
else
xCen = mean(X1(:));
yCen = mean(Y1(:));
X1 = (X1-xCen).*0.7 + xCen;
Y1 = (Y1-yCen).*0.7 + yCen;
max_source_xy_range = max(max(X1(:))-min(X1(:)) , max(Y1(:))-min(Y1(:))) .* 1;
while ~inpolygon(xsource(i),ysource(i),X1,Y1)
xsource(i) = random('norm',xCen,max_source_xy_range./5);
ysource(i) = random('norm',yCen,max_source_xy_range./5);
end
end
src_pars(i,:) = [image_ind xsource(i) ysource(i) size_scale];
%scurr = rng;
%Nclump=ceil(rand(1).*5);
%rndmat = rand(2);
%cov=rndmat.'*rndmat;
%cov = cov./((cov(1,1)+cov(2,2))./2) .* (src_rad./4)^2;
%COORDS = mvnrnd(zeros(Nclump,2),cov);
%temp_src_im = clumpy_source(COORDS(:,1),COORDS(:,2),0.01+rand(1,Nclump).*0.1,src_numpix,2.0,rand(1,Nclump));
%rng(scurr)
temp_src_im = GREAT_IMS{image_ind};
imindx = ceil( rand(1) * size(temp_src_im,3) );
temp_src_im = temp_src_im(:,:,imindx);
%temp_src_im = gal_ims{image_ind};
%temp_src_im = double(imread([galaxy_image_path file_names{file_inds(image_ind)}]))./255;
temp_src_im = imresize(temp_src_im,[src_numpix src_numpix]);
temp_src_im = temp_src_im./max(temp_src_im(:));
source_image = temp_src_im .* taper;
SKY_IM_L = interp2(xsrc.*size_scale+(xsource(i)).*pi./180./3600,ysrc.*size_scale+(ysource(i)).*pi./180./3600,source_image,XS,YS,'linear',0);
unlensed_flux = sum(source_image(:))./numel(source_image)./ (imside/(2*size_scale))^2 .* numel(SKY_IM_L);
magnification(i) = sum(SKY_IM_L(:)) ./ unlensed_flux;
SKY_IM = interp2(XIM,YIM,SKY_IM_L, X_out , Y_out , 'linear', 0);
newflux = sum(SKY_IM(:))./extend_ratio^2 .* (num_im_pix/num_im_output_pix)^2;
oldflux = sum(SKY_IM_L(:));
end
if max(SKY_IM(:))~=0
SKY_IM = SKY_IM./max(SKY_IM(:));
end
IMS = SKY_IM;
% imshow(SKY_IM,[],'xdata',[-3 3],'ydata',[-3 3]);
% pause;
if WRITE==1
imwrite(SKY_IM,[datapath test_or_train '_' num2str(i,'%.7d') '.png'],'bitdepth',16);
end
end
Q = [R_ein elp angle XLENS YLENS shear shear_angle];
PARAMS = [map_parameters(Q,'code') magnification];
if WRITE==1
dlmwrite([datapath 'parameters_' test_or_train '.txt'],PARAMS,' ')
dlmwrite([datapath 'parameters_source_' test_or_train '.txt'],src_pars,' ')
end
end
function p = map_parameters(q,code_or_decode)
SCALE_SHEAR = 5;
if strcmp(code_or_decode,'code')
Rein = q(:,1);
elp_x = q(:,2).* cos(q(:,3).*pi./180);
elp_y = q(:,2).* sin(q(:,3).*pi./180);
xlens = q(:,4);
ylens = q(:,5);
shear_x = SCALE_SHEAR .* q(:,6).* cos(q(:,7).*pi./180);
shear_y = SCALE_SHEAR .* q(:,6).* sin(q(:,7).*pi./180);
p = [Rein elp_x elp_y xlens ylens shear_x shear_y];
elseif strcmp(code_or_decode,'decode')
Rein = q(:,1);
elp = sqrt(q(:,2).^2+q(:,3).^2) ;
angle = atan2(q(:,3),q(:,2)) .* 180./pi;
xlens = q(:,4);
ylens = q(:,5);
shear = sqrt(q(:,6).^2+q(:,7).^2) ./ SCALE_SHEAR;
shear_angle = atan2(q(:,7),q(:,6)).* 180./pi;
p = [Rein elp angle xlens ylens shear shear_angle];
end
end
function [xsource ysource R_ein sigma_cent Minterior]=SIE_RayTrace_fromRein(ximage,yimage,xsource0,ysource0,REIN,elpSIS,Ext_Shear,Shear_angle,zLENS,zSOURCE,theta,offsets)
h=0.71;
OmegaC=0.222;
OmegaLambda=0.734;
sigNORM=0.801;
OmegaBaryon=0.0449;
OmegaM=OmegaC+OmegaBaryon;
c = 2.998E8; G = 6.67259E-11; Msun= 1.98892e30;
pc = 3.0857E16; kpc=1e3*pc; Mpc=1e6*pc;
H0=100*h*(1000/Mpc); %in units of 1/s
rhocrit=(3*H0^2)/(8*pi*G); %SI: kg/m^3
H=100*h;
Ds = (1e-6) * AngularDiameter(0,zSOURCE); %in Mpc
Dd = (1e-6) * AngularDiameter(0,zLENS); %in Mpc
Dds = (1e-6) * AngularDiameter(zLENS,zSOURCE); %in Mpc
sigma_cent = sqrt(299800000^2/(4*pi).* REIN .*pi./180./3600 .* AngularDiameter(0,zSOURCE)/AngularDiameter(zLENS,zSOURCE));
MSIS = (pi*(sigma_cent^2)*(REIN.*pi./180./3600)*Dd*Mpc)/G/Msun;
if isempty(xsource0) || isempty(ysource0)
xsource0=ximage;
ysource0=yimage;
end
if Ext_Shear==0
Ext_Shear=1e-15;
end
% xoffset=-offsets(1); yoffset=-offsets(2);
xoffset=-offsets(1)*(pi/3600/180); yoffset=-offsets(2)*(pi/3600/180);
COX=xsource0-ximage;
COY=ysource0-yimage;
% A=0; B=0; C=0; D=0;
%Ray trace an SIE based on analytical deflection. field: in arcsec
theta=theta*(pi/180);
Shear_angle=Shear_angle*(pi/180);
xsource=zeros(size(ximage));
ysource=zeros(size(yimage));
% Potential=zeros(size(yimage));
f=1-elpSIS;
fp=sqrt(1-f^2);
% sigma_cent=sigma(MSIS,zLENS);
sigma_cent = ((MSIS*G*Msun*Ds)/(4*pi^2*Dd*Dds*Mpc))^(1/4)*sqrt(c);
% sigma_cent = MSIS;
R_ein = 4 * pi * (sigma_cent/c)^2 *(Dds/Ds);
% Minterior=(pi*(sigma_cent^2)*R_ein*Dd*Mpc)/G/Msun;
ZXI_0 = 4 * pi * (sigma_cent/c)^2 *(Dd*Dds/Ds);
% R_ein=4 * pi * (sigma_cent/c)^2 *(Dds/Ds);
% R_ein*(60*60*180/pi)
% return
ximage=ximage+xoffset;
yimage=yimage+yoffset;
if theta~=0
[TH RHO]=cart2pol(ximage,yimage);
[ximage,yimage] = pol2cart(TH-theta,RHO);
end
Shear_angle=Shear_angle-theta;
g1=Ext_Shear*(-cos(2*Shear_angle));
g2=Ext_Shear*(-sin(2*Shear_angle));
g3=Ext_Shear*(-sin(2*Shear_angle));
g4=Ext_Shear*( cos(2*Shear_angle));
par=atan2(yimage,ximage);
xsource=((Dd.*ximage./ZXI_0-(sqrt(f)/fp).*asinh(cos(par).*fp./f)).*ZXI_0./Dd)-((g1.*ximage)+(g2.*yimage));
ysource=((Dd.*yimage./ZXI_0-(sqrt(f)/fp).*asin(fp.*sin(par))).*ZXI_0./Dd)-((g3.*ximage)+(g4.*yimage));
% subplot(2,2,1)
% imshow(abs((sqrt(f)/fp).*asinh(cos(par).*fp./f)).*ZXI_0./Dd,[]);colormap(jet);colorbar
% subplot(2,2,2)
% imshow(abs((sqrt(f)/fp).*asin(fp.*sin(par))).*ZXI_0./Dd,[]);colormap(jet);colorbar
% parfor i=1:numel(ximage)
% par=atan2(yimage(i),ximage(i));
% xsource(i)=((Dd.*ximage(i)./ZXI_0-(sqrt(f)/fp)*asinh(cos(par)*fp/f))*ZXI_0/Dd)-((g1.*ximage(i))+(g2.*yimage(i)));
% ysource(i)=((Dd.*yimage(i)./ZXI_0-(sqrt(f)/fp)*asin(fp*sin(par)))*ZXI_0/Dd)-((g3.*ximage(i))+(g4.*yimage(i)));
% xsource(i)=((Dd.*ximage(i)./ZXI_0-(sqrt(f)/fp)*asinh(cos(par)*fp/f))*ZXI_0/Dd);
% ysource(i)=((Dd.*yimage(i)./ZXI_0-(sqrt(f)/fp)*asin(fp*sin(par)))*ZXI_0/Dd);
% xalpha(i)=((sqrt(f)/fp)*asinh(cos(par)*fp/f))*ZXI_0/Dd;
% yalpha(i)=((sqrt(f)/fp)*asin(fp*sin(par)))*ZXI_0/Dd;
% DeltA=sqrt(cos(par)^2+(f^2*sin(par)^2));
% x1=(Dd.*ximage(i)./ZXI_0); x2=(Dd.*yimage(i)./ZXI_0);
% x=sqrt(x1^2+(f^2*x2^2))/DeltA;
% Potential(i)=(sqrt(f)/fp)*x*((abs(sin(par))*acos(DeltA))+(abs(cos(par))*acosh(DeltA/f)));
% end;
if theta~=0
[TH RHO]=cart2pol(ximage,yimage);
[ximage,yimage] = pol2cart(TH+theta,RHO);
[TH RHO]=cart2pol(xsource,ysource);
[xsource,ysource] = pol2cart(TH+theta,RHO);
end
ximage=ximage-xoffset;
yimage=yimage-yoffset;
xsource=xsource-xoffset+COX;
ysource=ysource-yoffset+COY;
% if strcmp(action,'plot')
% [xsource ysource]=TrianGulate(xsource,ysource);
% [ximage yimage]=TrianGulate(ximage,yimage);
% hold on
% plot(ximage,yimage,'color',[0.3 0.3 0.3]);
% plot(xsource,ysource,'b')
% axis equal
% elseif strcmp(action,'save')
% if strcmp(Del,'delaunay')
% [xsource ysource]=TrianGulate(xsource,ysource);
% [ximage yimage]=TrianGulate(ximage,yimage);
% end
% % save([SavePath '/SIE_RayTracedXY.mat'],'ximage','yimage','xsource','ysource','Nmat','MSIS','elpSIS','R_ein');
% save(SavePath,'ximage','yimage','xsource','ysource','Nmat','MSIS','elpSIS','R_ein','zLENS','zSOURCE','theta');
% elseif strcmp(action,'pass')
% if strcmp(Del,'delaunay')
% [xsource ysource]=TrianGulate(xsource,ysource);
% [ximage yimage]=TrianGulate(ximage,yimage);
% end
%
% % A=xsource; B=ysource;
% end
Minterior=(pi*(sigma_cent^2)*R_ein*Dd*Mpc)/G/Msun;
% if nargin==16
% if strcmp(displ,'display')
% disp(['Einstein Radius = ' num2str(R_ein*(180/pi)*3600,'%3.2f') ' [arcsec]']);
% disp(['Mass inside the Einstein Radius = ' num2str(Minterior,'%3.2e') ' [M_sun]']);
% end
% end
R_ein=R_ein.*3600*180/pi;
end
function I = LumProfile(xsource,ysource,prof_type,SourcePars)
if strcmpi(prof_type,'disk')
FLUX=SourcePars(1);
B=SourcePars(2).*(pi/180/3600);
xsr=SourcePars(3).*(pi/180/3600);
ysr=SourcePars(4).*(pi/180/3600);
srelp=1e-8;
r=sqrt(((xsource-xsr).^2./(1-srelp))+((ysource-ysr).^2).*(1-srelp));
% A=FLUX/(2*pi*B^2);
I= (r<=B);
elseif strcmpi(prof_type,'sersic')
if numel(SourcePars)==5
xsource=xsource./(pi/180/3600);
ysource=ysource./(pi/180/3600);
I0=SourcePars(1);
n=SourcePars(2);
Reff=SourcePars(3);
k = 2.*n-1./3+4./(405.*n)+46/(25515.*n^2);
% srelp=SourcePars(4);
% theta=SourcePars(5);
theta=0;
srelp=0.000001;
% xsr=SourcePars(6).*(pi/180/3600);
% ysr=SourcePars(7).*(pi/180/3600);
xsr=SourcePars(4);
ysr=SourcePars(5);
theta=theta.*(pi/180);
[TH RHO]=cart2pol(xsource,ysource);
[xsource,ysource] = pol2cart(TH-theta,RHO);
[TH RHO]=cart2pol(xsr,ysr);
[xsr,ysr] = pol2cart(TH-theta,RHO);
r=sqrt(((xsource-xsr).^2./(1-srelp))+((ysource-ysr).^2).*(1-srelp));
r = r./Reff;
I= I0 .* exp(-k.* (r.^(1./n)) );
elseif numel(SourcePars)==7
xsource=xsource./(pi/180/3600);
ysource=ysource./(pi/180/3600);
I0=SourcePars(1);
n=SourcePars(2);
Reff=SourcePars(3);
k = 2.*n-1./3+4./(405.*n)+46/(25515.*n^2);
srelp=SourcePars(4);
theta=SourcePars(5);
xsr=SourcePars(6);
ysr=SourcePars(7);
theta=theta.*(pi/180);
[TH RHO]=cart2pol(xsource,ysource);
[xsource,ysource] = pol2cart(TH-theta,RHO);
[TH RHO]=cart2pol(xsr,ysr);
[xsr,ysr] = pol2cart(TH-theta,RHO);
r=sqrt(((xsource-xsr).^2./(1-srelp))+((ysource-ysr).^2).*(1-srelp));
r = r./Reff;
I= I0 .* exp(-k.* (r.^(1./n)) );
end
elseif strcmpi(prof_type,'gaussian')
if numel(SourcePars)==4
FLUX=SourcePars(1);
B=SourcePars(2).*(pi/180/3600);
theta=0;
srelp=1e-9;
xsr=SourcePars(3).*(pi/180/3600);
ysr=SourcePars(4).*(pi/180/3600);
r=sqrt(((xsource-xsr).^2./(1-srelp))+((ysource-ysr).^2).*(1-srelp));
A=FLUX/(2*pi*B^2);
I=A.*exp(-0.5.*(r./B).^2);
elseif numel(SourcePars)==6
FLUX=SourcePars(1);
B=SourcePars(2).*(pi/180/3600);
srelp=SourcePars(3);
theta=SourcePars(4);
xsr=SourcePars(5).*(pi/180/3600);
ysr=SourcePars(6).*(pi/180/3600);
theta=theta.*(pi/180);
[TH RHO]=cart2pol(xsource,ysource);
[xsource,ysource] = pol2cart(TH-theta,RHO);
[TH RHO]=cart2pol(xsr,ysr);
[xsr,ysr] = pol2cart(TH-theta,RHO);
r=sqrt(((xsource-xsr).^2./(1-srelp))+((ysource-ysr).^2).*(1-srelp));
A=FLUX/(2*pi*B^2);
I=A.*exp(-0.5.*(r./B).^2);
end
end
end
function out_vec = AngularDiameter(Zd,z)
%Return the angular diameter distance in parsecs
NLENGTH = max(length(Zd),length(z));
out_vec = zeros(NLENGTH,1);
if length(Zd)==1 & length(z)~=1
Zd = ones(size(z)).*Zd;
elseif length(Zd)~=1 & length(z)==1
z = ones(size(Zd)).*z;
end
h=0.71;
OmegaC=0.222;
OmegaLambda=0.734;
sigNORM=0.801;
OmegaBaryon=0.0449;
OmegaM=OmegaC+OmegaBaryon;
c = 2.998E8; G = 6.67259E-11; Msun= 1.98892e30;
pc = 3.0857E16; kpc=1e3*pc; Mpc=1e6*pc;
H0=100*h*(1000/Mpc); %in units of 1/s
rhocrit=(3*H0^2)/(8*pi*G); %SI: kg/m^3
H=100*h;
H0 = 100*h; % Hubble constant
WM = OmegaM; % Omega(matter)
WV = OmegaLambda; % Omega(vacuum) or lambda
% initialize constants
c = 299792.458; % velocity of light in km/sec
DTT = 0.5; % time from z to now in units of 1/H0
DCMR = 0.0; % comoving radial distance in units of c/H0
for iJ=1:NLENGTH
h = H0/100.;
WR = 4.165E-5/(h*h); % # includes 3 massless neutrino species, T0 = 2.72528
WK = 1-WM-WR-WV;
az = 1.0/(1+1.0*z(iJ));
aZd = 1.0/(1+1.0*Zd(iJ));
n=2e4; % # number of points in integrals
%# do integral over a=1/(1+z) from az to 1 in n steps, midpoint rule
for a=az:(1-az)/n:aZd,
adot = sqrt(WK+(WM/a)+(WR/(a*a))+(WV*a*a));
DTT = DTT + 1./adot;
DCMR = DCMR + 1./(a*adot);
end;
DCMR = (1.-az)*DCMR/n;
x = sqrt(abs(WK))*DCMR;
if x > 0.1
if WK > 0
ratio = 0.5*(exp(x)-exp(-x))/x;
else
ratio = sin(x)/x;
end;
else
y = x*x;
if WK < 0
y = -y;
end;
ratio = 1. + y/6. + y*y/120.;
end;
DCMT = ratio*DCMR;
DA = az*DCMT;
DA_Mpc = (c/H0)*DA;
DA = DA_Mpc * 1e6;
out = DA; %in Parsecs
if (Zd(iJ)==z(iJ))
out=0;
end;
out_vec(iJ) = out;
end
end
function kappa = get_SIE_kappa( XIM , YIM , sigma_n , elp , angle , XLENS , YLENS , zLENS , zSOURCE )
h=0.71;
OmegaC=0.222;
OmegaLambda=0.734;
sigNORM=0.801;
OmegaBaryon=0.0449;
OmegaM=OmegaC+OmegaBaryon;
c = 2.998E8; G = 6.67259E-11; Msun= 1.98892e30;
pc = 3.0857E16; kpc=1e3*pc; Mpc=1e6*pc;
H0=100*h*(1000/Mpc); %in units of 1/s
rhocrit=(3*H0^2)/(8*pi*G); %SI: kg/m^3
H=100*h;
Ds = AngularDiameter(0,zSOURCE);
Dds = AngularDiameter(zLENS,zSOURCE);
theta = angle.*pi./180;
[TH , RHO]=cart2pol(XIM,YIM);
[XIM,YIM] = pol2cart(TH-theta,RHO);
[TH , RHO]=cart2pol(XLENS,YLENS);
[XLENS,YLENS] = pol2cart(TH-theta,RHO);
r = sqrt((XIM-XLENS.*pi./180./3600).^2+((YIM-YLENS.*pi./180./3600).*(1-elp)).^2) ;
R_ein = 4.*pi .* (sigma_n/c).^2 * Dds./Ds;
kappa = sqrt(1-elp) .* R_ein./(2.*r);
end
function [alphaX , alphaY]=RayTraceMap(kappa,ximage,yimage)
h = waitbar(0,'Ray tracing...');
dx = yimage(2) - yimage(1);
alphaX=zeros(size(ximage));
alphaY=zeros(size(ximage));
% smoothing_length = 1e-14 .* pi./180./3600;
% inds=find(mask==1).';
n=0;
% for i=inds
for i=1:numel(ximage)
n=n+1;
n
% i
if mod(i,200)==0
waitbar(i./numel(ximage),h,sprintf('%4.0f %% Completed',i./numel(ximage)*100))
end
xp=ximage-ximage(i);
yp=yimage-yimage(i);
% rp=sqrt((xp+smoothing_length).^2+(yp+smoothing_length).^2);
rp=sqrt((xp).^2+(yp).^2);
AX = -(1./pi) .* kappa .* (xp)./(rp.^2) .*dx^2 ;
AY = -(1./pi) .* kappa .* (yp)./(rp.^2) .*dx^2 ;
AX(rp==0)=0;
AY(rp==0)=0;
alphaX(i) = sum( AX(:) );
alphaY(i) = sum( AY(:) );
% alphaX(i) = -(1./pi) .* sum(sum( kappa .* (xp)./(rp.^2) .*dx^2 ));
% alphaY(i) = -(1./pi) .* sum(sum( kappa .* (yp)./(rp.^2) .*dx^2 ));
end
close(h)
xsource = ximage - alphaX;
ysource = yimage - alphaY;
end
function [ h1 , h2 , X1 , Y1 , X2 , Y2 ]=Caustic_Analytical(LensM,elp,units,CoL,zLENS,zSOURCE,theta,scale_me,offsets)
h1=0; h2=0;
X1 = 0;
Y1 = 0;
X2 = 0;
Y2 = 0;
theta=-theta+90;
h=0.71;
OmegaC=0.222;
OmegaLambda=0.734;
sigNORM=0.801;
OmegaBaryon=0.0449;
OmegaM=OmegaC+OmegaBaryon;
c = 2.998E8; G = 6.67259E-11; Msun= 1.98892e30;
pc = 3.0857E16; kpc=1e3*pc; Mpc=1e6*pc;
H0=100*h*(1000/Mpc); %in units of 1/s
rhocrit=(3*H0^2)/(8*pi*G); %SI: kg/m^3
H=100*h;
Dd =AngularDiameter(0,zLENS)*1e-6;
Dds=AngularDiameter(zLENS,zSOURCE)*1e-6;
Ds =AngularDiameter(0,zSOURCE)*1e-6;
% sig=sigma(LensM,zLENS);
sig=((LensM*G*Msun*Ds)/(4*pi^2*Dd*Dds*Mpc))^(1/4)*sqrt(c);
xoff=offsets(1);
yoff=offsets(2);
ZXI_0 = 4 * pi * (sig/c)^2 *(Dd*Dds/Ds);
f=1-elp;
fp=sqrt(1-f^2);
par=linspace(0,2*pi,200);
x=(-sqrt(f)/fp).*asinh(cos(par).*fp./f);
y=(-sqrt(f)/fp).*asin(sin(par).*fp);
delta=sqrt(cos(par).^2+f^2.*sin(par).^2);
x1=((sqrt(f)./delta).*cos(par))-((sqrt(f)/fp).*asinh(cos(par).*fp./f));
y1=((sqrt(f)./delta).*sin(par))-((sqrt(f)/fp).*asin(sin(par).*fp));
% xCrit1=((sqrt(f)./delta).*cos(par))-((sqrt(f)/fp).*asinh(cos(par).*fp./f));
% yCrit1=((sqrt(f)./delta).*sin(par))-((sqrt(f)/fp).*asin(sin(par).*fp));
% cr=(4*pi/(mu^2))+((16*sqrt(6)/15)*((1+f)/fp)*(1/(mu^(5/2))));
% cr=cr*((ZXI_0*Ds/Dd)^2); %cross section in physical units in the source plane
% disp(['Cross-section on steradians: ' num2str(cr/(Ds^2))]);
% con=180*3600/pi;
% con=1;
if nargin<8
scale_me=1;
end
x=x*ZXI_0;
y=y*ZXI_0;
x1=x1*ZXI_0;
y1=y1*ZXI_0;
% clf
% hold on
if strcmpi(units,'kpc')
plot(1e3*y,1e3*x,'m','LineWidth',2);
plot(1e3*y1,1e3*x1,'m','LineWidth',2);
elseif strcmpi(units,'pc')
plot(1e6*y,1e6*x,'m','LineWidth',2);
plot(1e6*y1,1e6*x1,'m','LineWidth',2);
elseif strcmpi(units,'rad')
% plot(y/Ds,x/Ds,'--y','LineWidth',2);
% plot(y1/Ds,x1/Ds,'--y','LineWidth',2);
% plot(y/Dd,x/Dd,CoL,'LineWidth',2);
% plot(y1/Dd,x1/Dd,CoL,'LineWidth',2);
% plot(y/Dd,x/Dd,CoL,'LineWidth',1);
% plot(y1/Dd,x1/Dd,CoL,'LineWidth',1);
if nargin>7
theta=theta*(pi/180);
[t r]=cart2pol(x,y);
[x,y] = pol2cart(t+theta,r);
[t r]=cart2pol(x1,y1);
[x1,y1] = pol2cart(t+theta,r);
x=scale_me.*x;
y=scale_me.*y;
x1=scale_me.*x1;
y1=scale_me.*y1;
X1 = ((y/Dd)+xoff);
Y1 = ((x/Dd)+yoff);
X2 = ((y1/Dd)+xoff);
Y2 = ((x1/Dd)+yoff);
h1=plot(y/Dd+xoff,x/Dd+yoff,'Color',CoL,'LineWidth',3,'linestyle','-');
hold on
h2=plot(y1/Dd+xoff,x1/Dd+yoff,'Color',CoL,'LineWidth',3,'linestyle','-');
else
x=scale_me.*x;
y=scale_me.*y;
x1=scale_me.*x1;
y1=scale_me.*y1;
h1=plot(y/Dd,x/Dd,'Color',CoL,'LineWidth',1.5,'linestyle','-');
hold on
h2=plot(y1/Dd,x1/Dd,'Color',CoL,'LineWidth',1.5,'linestyle','-');
end
elseif strcmpi(units,'arcsec')
theta=theta*(pi/180);
[t , r]=cart2pol(x,y);
[x,y] = pol2cart(t+theta,r);
[t , r]=cart2pol(x1,y1);
[x1,y1] = pol2cart(t+theta,r);
scale_me=(3600*180/pi);
x=scale_me.*x;
y=scale_me.*y;
x1=scale_me.*x1;
y1=scale_me.*y1;
X1 = ((y/Dd)+xoff);
Y1 = ((x/Dd)+yoff);
X2 = ((y1/Dd)+xoff);
Y2 = ((x1/Dd)+yoff);
% h1=plot(((y/Dd)+xoff),((x/Dd)+yoff),'Color',CoL,'LineWidth',1,'linestyle','--');
% h2=plot(((y1/Dd)+xoff),((x1/Dd)+yoff),'Color',CoL,'LineWidth',1,'linestyle','--');
end
% axis equal
end
% %%
% disp('Simulating data ...')
% rng(1)
% nsample = 9999;
% logM = zeros(nsample,1);
% elp = zeros(nsample,1);
% angle = zeros(nsample,1);
% xsource = zeros(nsample,1);
% ysource = zeros(nsample,1);
% for i=1:nsample
% i
% logM(i) = rand(1).*(11.8-10.5)+10.5;
% elp(i) = rand(1).*0.6;
% angle(i) = rand(1).*90;
% % XY = datasample([0.1 0.1; -0.1 0.1 ; 0.1 -0.1; -0.1 -0.1],1);
% % [XY(1),XY(2)] = pol2cart(rand(1).*2*pi,0.1.*sqrt(2));
% xsource(i) = (rand(1)-0.5).*0.4;
% ysource(i) = (rand(1)-0.5).*0.4; %datasample([-0.1 0.1],1); %(rand(1)-0.5).*0.1;
%
%
%
% [XS ,YS ,R_ein ,sigma_cent ,Minterior]=SIE_SUB_RayTrace(XIM,YIM,XIM,YIM,10^logM(i),elp(i),1e-20,0,zLENS,zSOURCE,angle(i),[0 0]);
% SKY_IM = LumProfile(XS,YS,'gaussian',[1 0.05 xsource(i) ysource(i)]);
% SKY_IM = SKY_IM./max(SKY_IM(:));
%
% % FFT_IM = fftshift(fft2(fftshift(SKY_IM)));
% % mAx = max([real(FFT_IM(:)); imag(FFT_IM(:))]);
% % imwrite(real(FFT_IM)./mAx,[datapath 'FFT_real_lens_im96__' num2str(i,'%.4d') '.png']);
% % imwrite(imag(FFT_IM)./mAx,[datapath 'FFT_imag_lens_im96__' num2str(i,'%.4d') '.png']);
%
% % imshow(SKY_IM,[],'xdata',[min(XIM(:)) max(XIM(:))].*3600.*180./pi,'ydata',[min(YIM(:)) max(YIM(:))].*3600.*180./pi); colormap(jet)
% % pause(0.05)
%
% imwrite(SKY_IM,[datapath 'lens_im96__' num2str(i,'%.4d') '.png']);
% end
% dlmwrite([datapath 'logM96.txt'],(logM-10.5)./1.3,' ')
% dlmwrite([datapath 'elp96.txt'],elp./0.6,' ')
% dlmwrite([datapath 'angle96.txt'],angle.*0.01./0.9,' ')
% % hold on
% % plot(subhalo_pars(3),subhalo_pars(4),' +r','markersize',10)
%
%
% %%
%
% disp('Simulating data ...')
% rng(2)
% nsample = 999;
% logM = zeros(nsample,1);
% elp = zeros(nsample,1);
% angle = zeros(nsample,1);
% xsource = zeros(nsample,1);
% ysource = zeros(nsample,1);
%
% for i=1:nsample
% i
% logM(i) = rand(1).*(11.8-10.5)+10.5;
% elp(i) = rand(1).*0.6;
% angle(i) = rand(1).*90;
% % XY = datasample([0.1 0.1; -0.1 0.1 ; 0.1 -0.1; -0.1 -0.1],1);
% % [XY(1),XY(2)] = pol2cart(rand(1).*2*pi,0.1.*sqrt(2));
% xsource(i) = (rand(1)-0.5).*0.4;
% ysource(i) = (rand(1)-0.5).*0.4; %datasample([-0.1 0.1],1); %(rand(1)-0.5).*0.1;
%
%
%
% [XS ,YS ,R_ein ,sigma_cent ,Minterior]=SIE_SUB_RayTrace(XIM,YIM,XIM,YIM,10^logM(i),elp(i),1e-20,0,zLENS,zSOURCE,angle(i),[0 0]);
% SKY_IM1 = LumProfile(XS,YS,'gaussian',[1 0.02 xsource(i) ysource(i)]);
% SKY_IM2 = LumProfile(XS,YS,'gaussian',[1 0.02 xsource(i)+0.06 ysource(i)+0.06]);
% SKY_IM3 = LumProfile(XS,YS,'gaussian',[1 0.02 xsource(i)+0.06 ysource(i)-0.06]);
% SKY_IM = SKY_IM1 + SKY_IM2 + SKY_IM3;
% SKY_IM = SKY_IM./max(SKY_IM(:));
%
% % FFT_IM = fftshift(fft2(fftshift(SKY_IM)));
% % mAx = max([real(FFT_IM(:)); imag(FFT_IM(:))]);
% % imwrite(real(FFT_IM)./mAx,[datapath 'FFT_test_lens_im96__' num2str(i,'%.4d') '.png']);
% % imwrite(imag(FFT_IM)./mAx,[datapath 'FFT_test_lens_im96__' num2str(i,'%.4d') '.png']);
%
% imshow(SKY_IM,[],'xdata',[min(XIM(:)) max(XIM(:))].*3600.*180./pi,'ydata',[min(YIM(:)) max(YIM(:))].*3600.*180./pi); colormap(jet)
% pause;
%
% % imwrite(SKY_IM,[datapath 'test_lens_im96__' num2str(i,'%.4d') '.png']);
% end
% % dlmwrite([datapath 'test_logM96.txt'],(logM-10.5)./1.3,' ')
% % dlmwrite([datapath 'test_elp96.txt'],elp./0.6,' ')
% % dlmwrite([datapath 'test_angle96.txt'],angle.*0.01./0.9,' ')
% % hold on
% % plot(subhalo_pars(3),subhalo_pars(4),' +r','markersize',10)
%
%
% %%
% figure
% logM = load([datapath 'logM96.txt']);
% elp = load([datapath 'elp96.txt']);
% angle = load([datapath 'angle96.txt']);
% predict=load([datapath 'predict_mea.txt']);
% clf
% s(1) = subplot(3,1,1);
% plot(predict(:,1))
% hold on
% plot(logM,'--')
%
% s(2) = subplot(3,1,2);
% plot(predict(:,2))
% hold on
% plot(elp,'--')
%
% s(3) = subplot(3,1,3);
% plot(predict(:,3))
% hold on
% plot(angle,'--')
%
% linkaxes(s,'x');
%
% %%
%
% figure
% logM=load([datapath 'test_logM96.txt']);
% elp=load([datapath 'test_elp96.txt']);
% angle=load([datapath 'test_angle96.txt']);
% predict=load([datapath 'test_predict_mea.txt']);
% clf
% s(1) = subplot(3,1,1);
% plot(predict(:,1))
% hold on
% plot(logM,'--')
%
% s(2) = subplot(3,1,2);
% plot(predict(:,2))
% hold on
% plot(elp,'--')
%
% s(3) = subplot(3,1,3);
% plot(predict(:,3))
% hold on
% plot(angle,'--')
%
% linkaxes(s,'x');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.