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
|
ZijingMao/baselineeegtest-master
|
hlp_flattensearch.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_flattensearch.m
| 4,984 |
utf_8
|
862f3f897f7991f789931d500395318c
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_tostring.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_tostring.m
| 9,007 |
utf_8
|
27a2805eb3c352fa66ade79a1bff3974
|
function str = hlp_tostring(v,stringcutoff,prec)
% Get an human-readable string representation of a data structure.
% String = hlp_tostring(Data,StringCutoff)
%
% 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
%
% StringCutoff : optional maximum string length for atomic fields (default: 0=off)
%
% Precision : maximum significant digits (default: 15)
%
% 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])
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
if nargin < 2
stringcutoff = 0; end
if nargin < 3
prec = 15; end
str = serializevalue(v);
function val = serializevalue(v)
% Main hub for serializing values
if isnumeric(v) || islogical(v)
val = serializematrix(v);
elseif ischar(v)
val = serializestring(v);
elseif isa(v,'function_handle')
val = serializefunction(v);
elseif is_impure_expression(v)
val = serializevalue(v.tracking.expression);
elseif has_canonical_representation(v)
val = serializeexpression(v);
elseif is_dataset(v)
val = serializedataset(v);
elseif isstruct(v)
val = serializestruct(v);
elseif iscell(v)
val = serializecell(v);
elseif isobject(v)
val = serializeobject(v);
else
try
val = serializeobject(v);
catch
error('Unhandled type %s', class(v));
end
end
end
function val = serializestring(v)
% Serialize a string
if any(v == '''')
val = ['''' strrep(v,'''','''''') ''''];
try
if ~isequal(eval(val),v)
val = ['char(' serializevalue(uint8(v)) ')']; end
catch
val = ['char(' serializevalue(uint8(v)) ')'];
end
else
val = ['''' v ''''];
end
val = trim_value(val,'''');
end
function val = serializematrix(v)
% Serialize a matrix and apply correct class and reshape if required
if ndims(v) < 3 %#ok<ISMAT>
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,prec);
end
else
val = mat2str(v,prec,'class');
end
val = trim_value(val,']');
else
if isa(v, 'double')
val = mat2str(v(:),prec);
else
val = mat2str(v(:),prec,'class');
end
val = trim_value(val,']');
val = sprintf('reshape(%s, %s)', val, mat2str(size(v)));
end
end
function val = serializecell(v)
% Serialize a cell
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) 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
end
function val = serializeexpression(v)
% Serialize an expression
if numel(v) > 1
val = ['['];
for k = 1:numel(v)
val = [val serializevalue(v(k)), ', ']; 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}), ', ']; end
val = [val(1:end-2) ')'];
else
val = char(v.head);
end
end
end
function val = serializedataset(v) %#ok<INUSD>
% Serialize a data set
val = '<EEGLAB data set>';
end
function val = serializestruct(v)
% Serialize a struct by converting the field values using struct2cell
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}) ', '];
val = [val serializevalue( permute(fieldValues(fieldNo, :,:,:,:,:,:), [2:ndims(fieldValues) 1]) ) ];
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
end
function val = serializeobject(v)
% Serialize an object by converting to struct and add a call to the copy constructor
val = sprintf('%s(%s)', class(v), serializevalue(struct(v)));
end
function val = serializefunction(v)
% Serialize a function handle
try
val = ['@' char(get_function_symbol(v))];
catch
val = char(v);
end
end
function v = trim_value(v,appendix)
if nargin < 2
appendix = ''; end
% Trim a serialized value to a certain length
if stringcutoff && length(v) > stringcutoff
v = [v(1:stringcutoff) '...' appendix]; end
end
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
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'));
end
|
github
|
ZijingMao/baselineeegtest-master
|
hlp_config.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_config.m
| 13,648 |
utf_8
|
63022cdbc72bbfdfcf73c317df53f400
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_deserialize.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_deserialize.m
| 13,494 |
utf_8
|
bb9c30239d4a0cee13a59fbc98798cd3
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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 = double(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 = double(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 = double(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.
try
next_v = arg_report('handle',v,parentage(k));
catch
warn_once('hlp_deserialize:lookup_failed',['Could not look report properties of scoped/nested function handle "' parentage{k} '" from enclosing function "' char(v) '".']);
v = @error_deserializing_function;
return
end
if isempty(next_v{1})
warn_once('hlp_deserialize:lookup_failed',['Could not look up scoped/nested function handle "' parentage{k} '" from enclosing function "' char(v) '".']);
end
v = next_v{1};
end
if ~isempty(v)
db_nested.(key) = v;
end
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
|
ZijingMao/baselineeegtest-master
|
hlp_aggregatestructs.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_aggregatestructs.m
| 8,572 |
utf_8
|
c7ca0758ab30ea7e668808cb89ef00a1
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_matlab_version.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_matlab_version.m
| 1,410 |
utf_8
|
ca4cb09e51849db00730a297a71d0869
|
function v = hlp_matlab_version()
% Get the MATLAB version in a numeric format that can be compared with <, >, etc.
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_diskcache.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_diskcache.m
| 21,219 |
utf_8
|
f71772574ae6ef73a7d234bf721dfe94
|
function varargout = hlp_diskcache(options, f, varargin)
% Cache results of function invocations.
% Results... = hlp_diskcache(Settings, Function, Arguments...)
%
% This function maintains a disk cache of function results in a user-specified folder and
% if a result had already been computed before, it will be immediately looked up instead of being
% computed again.
%
% This function should only be used for computations that take a long enough time to justify the
% overhead since disk I/O can be relatively slow, since results can fill up the disk quickly, and
% since there are important safety considerations (see below).
%
% In:
% Settings : settings that determine where and what to cache (either a cell array of name-value
% pairs or a struct). The most important options are:
% * folder: the folder relative to which the results are saved (default: '.')
% * freemem: the amount of memory that should remain free on the disk (in GB if > 1,
% otherwise a fraction of total space) (default: 80)
% * bypass: bypass caching system (default: false)
% See Advanced Options below for further options, and see Pre-defining and Recalling
% Settings for a way to separate the settings declaration from the call-site that
% invokes hlp_diskcache.
%
% Function : function handle to compute a result from some arguments
%
% Arguments... : arguments to pass to the function
%
% Out:
% Results... : return values of the function for the given arguments
%
%
% Safety Notes:
% 1) Only *referentially transparent* functions can be cached safely; if a function can give different
% outputs for the same arguments, this can lead to subtle bugs; examples include functions that
% refer to global state (global variables, files on disk). This can be fixed by turning all
% dependencies of the function into arguments. Also, if a function's desired behavior includes
% side effects (e.g., creating or updating files), it cannot be cached safely. This can be
% worked around by caching only the core function that performs the actual computation (if
% any). When applying functions to "smart" objects, make sure that the call does not
% inadvertently fall under these categories (e.g., reads, creates or updates files or global
% variables).
%
% 2) If the execution of a function changes, an obsolete result might be looked up from the cache.
% Therefore the code of the passed-in function is checksummed against the code that calculated
% the original result, however *none* of the functions called by that function will be checksummed
% since it cannot readily be made fast enough. Therefore, if a dependent function changes and
% that change affects results in the cache, you will want to delete or disable the cache. This is
% especially important during debugging sessions.
%
%
% Usability Notes:
% 1) If you are debugging a function whose results are being cached, *bypass* the cache temporarily
% (you can do this either below in the first code line, or at the call site by passing in 'bypass').
%
% 2) If you do not want the cache to be invalidated when you change a function and you know what
% you are doing, you can add a version line to your function that you increment whenever you
% make a change that renders previous results obsolete. This requires very serious programmer
% discipline and cannot possibly be enforced when multiple people edit the code at random.
%
% 3) Make sure that your disk is fast enough for the caching to make sense; ideally you want an SSD.
% Do not use hlp_diskcache for small jobs that are very fast to compute -- use hlp_microcache
% instead, which is in-memory (not persistent across MATLAB restarts) and extremely lightweight.
%
%
% Advanced Options:
% The following further settings can be passed for Settings:
% * maxsize: don't save result files that are larger than this in bytes (default: Inf)
% * minsize: don't save result files that are smaller than this in bytes (default: 0)
% * mintime: don't save results that took less than this time to compute, in seconds (default: 0)
% * versiontag: syntax of the optional version tag in your function's code (default: '$(funcname)_version<\S+>')
% code versioning can be disabled by setting the versiontag to false (discouraged)
% * subdir: the cache sub-directory relative to the folder; created if missing (default: 'diskcache')
% * exactmatch_cutoff: if the input is larger than this many bytes, it will not be stored with the result
% and will not be compared byte-for-byte during lookup, in bytes (default: 1000000)
% note that the hash is usually strong enough to make a byte-for-byte check unnecessary
% * cleanup: clean up old cache entries when running out of disk space (default: true)
% * serialize: use serialization for the result, faster than raw save/load for large files (default: true)
% * permissions: cell array of file permissions to use for created directories and files, as in fileattrib
% (default: {'+w','a'})
% * bypass_if_folder_missing: if the given folder does not exist, the cache will be bypassed;
% otherwise the folder will be created if missing (default: false)
% note: this can be useful to prevent inadvertent littering of directories
% with cache files when running from a different installation
% overwrite_files: overwrite existing files (can create broken files when multiple processes write
% to the same files in parallel) (default: false)
%
%
% Pre-defining and Recalling Settings:
% If Settings is passed in as a string instead of a cell array of name-value pairs or a struct,
% it is taken as the name of a settings profile (similar to a cache "domain" in hlp_microcache).
% Note that the profile name should be a valid MATLAB field name.
%
% Pre-defining settings for a profile:
% To assign settings for a named cache profile, call:
% > hlp_diskcache('myprofile','name',value,'name',value, ...)
% Where myprofile is the name of the profile for which settings shall be assigned
% and the names/values are the settings to assign to it (what would normally be passed as a
% cell array). Note that settings are not persistent across MATLAB runs, so you'd need to
% put them into an initializer or startup function. By default a "clear all" does not clear the
% settings (this can be disabled by setting clearable_settings to true in the code below).
%
% Recalling settings from a profile:
% To recall settings from a profile in a call of hlp_diskcache, just use the name of the
% profile instead of the Settings cell array. It is permitted to recall from a profile that
% has not been defined before (in this case, all defaults will be assumed).
%
%
% Examples:
% % if this line is executed for the first time, it is as slow as magic(2000)
% % the result will be written into a sub-directory of ~/myresults
% m = hlp_diskcache({'folder','./myresults'},@magic,2000);
%
% % if it is executed a second time, it is likely much faster than m=magic(2000)
% % if the result is found on disk
% m = hlp_diskcache({'folder','./myresults'},@magic,2000);
%
% % it is also possible to assign settings separately for a named 'profile', and then later recall
% % them:
% hlp_diskcache('myprofile','folder','./myresults','freemem',10);
% m = hlp_diskcache('myprofile',@magic,2000);
%
%
% See also:
% hlp_microcache
%
% Depends on:
% hlp_serialize, hlp_deserialize, hlp_cryptohash
%
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2013-04-15
% Copyright (C) Christian Kothe, SCCN, 2013, [email protected]
%
% 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
bypass = false; % whether to bypass caching (switch for debugging)
clearable_settings = false; % whether settings should be clearable by "clear all"
archive_version = 1.0; % version of the archive format
persistent settings;
persistent have_translatepath;
if isempty(have_translatepath)
have_translatepath = exist('env_translatepath','file'); end
% parse options
if iscell(options) || isstruct(options)
% options are directly given as cell array or struct
options = assign_defaults(options);
elseif ischar(options)
% options is referring to the name of a profile
profilename = options;
% make sure that it exists
if ~isfield(settings,profilename)
settings.(profilename) = assign_defaults({}); end
if isa(f,'function_handle')
% recall options from it
options = settings.(profilename);
elseif ischar(f)
% assign options to it
varargin = [{f} varargin];
for k=1:2:length(varargin)
settings.(profilename).(varargin{k}) = varargin{k+1}; end
if ~clearable_settings
mlock; end
return;
else
error('Unrecognized syntax.');
end
else
error('Unrecognized syntax.');
end
% make path platform-specific
if ~have_translatepath
options.folder = strrep(strrep(options.folder,'\',filesep),'/',filesep);
else
options.folder = env_translatepath(options.folder);
end
% optionally bypass the caching
if bypass || options.bypass || (options.bypass_if_folder_missing && ~exist(options.folder,'dir'))
[varargout{1:nargout}] = f(varargin{:});
return;
end
% get a unique identifier of the computation
uid = hlp_serialize(trim_expression({nargout,f,func_version(f,options.versiontag),varargin}));
% get a short hash value of that
hash = hlp_cryptohash(uid);
% get the file name under which this would be cached
cachedir = [options.folder filesep options.subdir];
filename = [cachedir filesep hash(1:2) filesep hash(3:end) '.mat'];
if exist(filename,'file')
try
% try to load from disk
result = load(filename);
% do some sanity checks
if floor(result.settings.archive_version) > floor(archive_version)
disp('Note: The file was saved with a newer major archive version. Performing a safe fallback...');
elseif ~all(isfield(result,{'settings','hash','uid','varargout'}))
disp('The cached file is apparently malformed (missing some required fields). Performing a safe fallback...');
elseif ~isequal(result.hash,hash)
disp('Note: the hash does not match that of the file on disk. Performing a safe fallback...');
elseif ~isempty(result.uid) && ~isequal(result.uid,uid)
disp('Note: two results yielded the same MD5 hash; this should be a very rare event. Performing a safe fallback...');
else
% deserialize data if necessary
if result.settings.is_serialized
result.varargout = hlp_deserialize(result.varargout); end
% all went well: return result
varargout = result.varargout;
return;
end
catch e
error_message('Could not look up result from disk',e);
disp('Performing a safe fallback...');
end
end
result.settings = options;
if numel(uid) <= result.settings.exactmatch_cutoff
result.uid = uid;
else
result.uid = [];
clear uid;
end
result.settings.is_serialized = result.settings.serialize;
result.settings.archive_version = archive_version;
result.hash = hash;
% (re)calculate the result
start_time = tic;
[varargout{1:nargout}] = f(varargin{:});
computation_time = toc(start_time);
% prepare result for writeback
if result.settings.is_serialized
try
result.varargout = hlp_serialize(varargout);
catch e
error_message('Could not serialize the result (try to disable the option serialize)',e);
disp('Saving result in unserialized form (can be slow).')
result.varargout = varargout;
end
else
result.varargout = varargout;
end
% do some size & time checks
stats = whos('result');
resultsize = stats.bytes;
if resultsize > options.maxsize
% result too big to store
return;
elseif resultsize < options.minsize
% result too small to store
return;
elseif computation_time < options.mintime
% computation too short to be worth it
return;
else
% ensure that we have enough space
total_space = disk_total_space(filename);
if options.freemem > 0 && total_space > 0
free_space = disk_free_space(filename);
if options.freemem < 1
ensured_space = total_space * options.freemem;
else
ensured_space = options.freemem*(2^9);
end
if total_space && free_space-resultsize < ensured_space
if ~options.cleanup
return; end
% generate a list of all result files
allfiles = struct();
records = dir(cachedir);
for d = 1:length(records)
record = records(d);
if record.isdir && length(record.name) == 2 && all(record.name~='.')
% get a list of all MATAB files in this subdir
files = dir([cachedir filesep record.name filesep '*.mat']);
for f=1:length(files)
files(f).path = [cachedir filesep record.name filesep files(f).name];
allfiles(end+1) = files(f); %#ok<AGROW>
end
% try to remove dirs that are empty
if isempty(files)
try rmdir([cachedir filesep record.name]); catch,end; end %#ok<CTCH>
end
end
% delete old files as long as ours doesn't yet fit into memory
[dummy,newest_to_oldest] = sort([allfiles.datenum],'descend'); %#ok<ASGLU>
while ~isempty(newest_to_oldest) && disk_free_space(filename) - resultsize < ensured_space
try delete(allfiles(newest_to_oldest(end)).path); catch,end %#ok<CTCH>
newest_to_oldest = newest_to_oldest(1:end-1);
end
end
else
persistent message_shown; %#ok<TLEV>
if isempty(message_shown)
disp('Note: cannot determine free disk space on your platform, trying to cache results anyway. This message will only be shown once.');
message_shown = true;
end
end
% save the result
try
% ensure that the target directory exists
make_directories(filename,options.permissions);
% save result file
fldnames = fieldnames(result);
if exist(filename,'file') && ~options.overwrite_files
return; end
if resultsize >= (2000*1024*1024)
save(filename,'-struct','result',fldnames{:},'-v7.3');
else
save(filename,'-struct','result',fldnames{:});
end
% finalize file permissions
if ~isempty(options.permissions)
warning off MATLAB:FILEATTRIB:SyntaxWarning
try
fileattrib(filename,options.permissions{:});
catch e
error_message('Note: could not set permissions for result file',e);
end
end
catch e
error_message('Could not cache result on disk',e);
end
end
function options = assign_defaults(options)
% Assign default settings to an options struct / name-value pair list
if iscell(options)
options = cell2struct(options(2:2:end),options(1:2:end),2); end
if ~isfield(options,'folder')
options.folder = '.'; end
if ~isfield(options,'maxsize')
options.maxsize = Inf; end
if ~isfield(options,'minsize')
options.minsize = 0; end
if ~isfield(options,'mintime')
options.mintime = 0; end
if ~isfield(options,'freemem')
options.freemem = 80; end
if ~isfield(options,'versiontag')
options.versiontag = '$(funcname)_version<\S+>'; end
if ~isfield(options,'serialize')
options.serialize = true; end
if ~isfield(options,'subdir')
options.subdir = 'diskcache'; end
if ~isfield(options,'exactmatch_cutoff')
options.exactmatch_cutoff = 1000000; end
if ~isfield(options,'cleanup')
options.cleanup = true; end
if ~isfield(options,'permissions')
options.permissions = {'+w','a'}; end
if ~isfield(options,'bypass')
options.bypass = false; end
if ~isfield(options,'bypass_if_folder_missing')
options.bypass_if_folder_missing = false; end
if ~isfield(options,'overwrite_files')
options.overwrite_files = false; end
function x = trim_expression(x)
% Recursively trim partially evaluated parts of a data structure containing expressions.
% In particular, x.tracking.expression is replaced by x.
if isfield(x,'tracking') && isfield(x.tracking,'expression')
x = trim_expression(x.tracking.expression);
elseif iscell(x)
x = cellfun(@trim_expression,x,'UniformOutput',false);
elseif isfield(x,{'head','parts'})
x.parts = trim_expression(x.parts);
end
function v = func_version(func,versiontag)
% Get a version identifier of a MATLAB function; can be any of the following
% * cell array of version strings of a MATLAB function, if present
% * MD5 hash of the file if unversioned.
% * string form of the input if there is no accessible file (e.g., anonymous function),
% or if the versiontag is passed in as false
try
if ischar(func)
filename = which(func);
else
filename = getfield(functions(func),'file');
end
catch
filename = '';
end
func = char(func);
if isequal(versiontag,false) || strncmp(char(func),'@',1)
v = char(func);
else
if ~isempty(filename)
% open the source file
f = fopen(filename,'r');
try
% read the code
code = fread(f,Inf,'uint8=>char')';
% check if it contains the version descriptor tag
v = regexp(code,strrep(versiontag,'$(funcname)',func),'match');
% otherwise we just hash the entire code
if isempty(versiontag) || isempty(v)
v = hlp_cryptohash(code); end
fclose(f);
catch %#ok<CTCH>
try
fclose(f);
catch %#ok<CTCH>
end
v = func;
end
else
% otherwise use the string representation as version
v = func;
end
end
function res = disk_total_space(path)
% Get the amount of total space on the disk (can be 0 if the check fails).
f = java.io.File(path);
res = f.getTotalSpace();
function res = disk_free_space(path)
% Get the amount of free space on the disk (can be 0 if the check fails).
f = java.io.File(path);
res = f.getFreeSpace();
function error_message(msg,e)
% Display a formatted error message with traceback.
if exist('hlp_handleerror','file')
disp([msg ': ']);
hlp_handleerror(e);
else
disp([msg ': ' e.message]);
end
function res = strsplit(str,delims)
% Split a string according to some delimiter(s).
pos = find(diff([0 ~sum(bsxfun(@eq,str(:)',delims(:)),1) 0]));
res = cell(~isempty(pos),length(pos)/2);
for k=1:length(res)
res{k} = str(pos(k*2-1):pos(k*2)-1); end
function make_directories(filepath,attribs)
% Create directories recursively for a given file path.
paths = strsplit(filepath,filesep);
% find the base directory where the directory creation begins
if filepath(1) == filesep
% Unix, absolute
curpath = filesep; first = 1;
elseif ~isempty(strfind(paths{1},':')) && ispc
% Windows, absolute
curpath = [paths{1} filesep]; first = 2;
else
% relative
curpath = [pwd filesep]; first = 1;
end
% determine where to stop
if filepath(end) == filesep
last = length(paths);
else
last = length(paths)-1;
end
% walk...
for i=first:last
if ~exist([curpath paths{i}],'dir')
if ~mkdir(curpath,paths{i})
error(['Unable to create directory ' filepath]);
else
% set attributes
if ~isempty(attribs)
warning off MATLAB:FILEATTRIB:SyntaxWarning
try
fileattrib([curpath paths{i}],attribs{:});
catch e
error_message(['Note: could not set permissions for created directory (' filepath ')'],e);
end
end
end
end
curpath = [curpath paths{i} filesep]; %#ok<AGROW>
end
|
github
|
ZijingMao/baselineeegtest-master
|
hlp_trycompile.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_trycompile.m
| 51,457 |
utf_8
|
23414826acf0e2e771679cbd7296fb01
|
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
% Copyright (C) Christian Kothe, SCCN, 2011, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_serialize.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_serialize.m
| 16,643 |
utf_8
|
3fb4a9c53a5cb6059f6ad2653c028e4b
|
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
% hlp_serialize_version<1.00>
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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 isa(v,'gpuArray')
m = serialize_numeric(gather(v));
elseif 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','classsimple'}
% 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: ' cls]);
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
|
ZijingMao/baselineeegtest-master
|
hlp_varargin2struct.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_varargin2struct.m
| 6,991 |
utf_8
|
c99a9bbc7d04cae15828bc517e8e27fe
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
hlp_superimposedata.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/helpers/hlp_superimposedata.m
| 6,265 |
utf_8
|
57e525f9b2247bd13dcfe2e4a88519fc
|
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
% Copyright (C) Christian Kothe, SCCN, 2011, [email protected]
%
% 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
% first, compactify the data by removing the empty items
compact = varargin(~cellfun('isempty',varargin));
if isempty(compact)
res = [];
else
% 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
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
|
ZijingMao/baselineeegtest-master
|
utl_check_fingerprint.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_check_fingerprint.m
| 1,935 |
utf_8
|
ec068f208d9bfb62e93003b17b4e37c4
|
function x = utl_check_fingerprint(x,opts,ctx,exp)
% Check whether the given argument is an inconsistent impure expression.
% Data = utl_check_fingerprint(Data,Options,Context,Expressions)
%
% The remaining arguments are used only when the function is used as an argstep in exp_beginfun.
% There, it serves as an argstep for 'filter'/'editing' functions, to check, fix up and warn about the value of
% inconsistent impure expressions (expressions referring to signals, in particular) and data set values
% (without any notion of expressions).
%
% See also:
% hlp_fingerprint, exp_beginfun, exp_endfun
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-15
if ~exist('opts','var')
opts.fingerprint_check = true;
exp = [];
ctx = [];
end
if isfield(x,'tracking') && all(isfield(x.tracking,{'expression','fingerprint'}))
% get the fingerprint checking expression (either from the options or from the dynamic context)
if isempty(opts.fingerprint_check)
opts.fingerprint_check = hlp_resolve('fingerprint_check',true,ctx); end
% this check can be selectively overridden with a block-scoped symbol 'fingerprint_check', which may be an expression that involves @expression
% (the expression for which we are about to execute the check)
if hlp_microcache('fprint_lookup',@is_enabled,opts.fingerprint_check,exp)
if ~isequal(hlp_fingerprint(rmfield(x,'tracking')),x.tracking.fingerprint)
error('expression is inconsistent with the attached value'); end
end
end
% find out whether a given reference expression yields true if @expression is substituted with some substitution expression
function res = is_enabled(ref_exp,subs_exp)
if exp_eval(utl_releasehold(utl_replacerepeated(ref_exp,{exp_rule(@expression,subs_exp)})),inf)
res = true;
else
res = false;
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_memoize_lookup.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_memoize_lookup.m
| 8,255 |
utf_8
|
d560d4554b490a97703199eacfbc418b
|
function [action,result] = utl_memoize_lookup(exp,memo_ctrl,ctx)
% Check for memoizability and/or availability of the given expression.
% [Action,Result] = utl_memoize_lookup(Key-Expression,Memo-Locations)
%
% In:
% Key-Expression : an expression that uniquely identifies the object to be looked up;
% this expression is also required to be identical to the one stored in the looked-up object's .tracking.expression field
%
% Memo-Locations : cell array of location specifiers, given as name-value pairs. possible names are currently 'disk' and 'memory', and the value
% is expected to be an expression that evaluates into 0 or 1, to indicate whether the given location is enabled for
% storage/retrieval or not. The expression may use the symbol @expression to refer to the Key-Expression. The locations
% are looked up in order, so the fastest locations should come first in the list.
%
% Out:
% Action : the action to be taken by the caller, one of:
% 'return' : result contains the object that shall be returned as first output argument
% 'memoize': result contains a cell array of store locations to be used for storing the result, when it is eventually computed
% - store locations begining with the fileep indicate disk locations, relative to the appropriate memoization domain
% - store locations beginning with a . indicate memory locations, relative to the in-memory cache data structure
% 'skip': do not memoize the result
%
% Result : the payload to which the action applies (either the successfully looked up result or the memoization
% locations for a subsequent commit)
%
% Notes:
% If a location further down in the list has the object in question but preceding ones do not, the object is implicitly commited
% (copied) to these locations.
%
% See also:
% utl_memoize_commit
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-05-23
global tracking;
if ~exist('memo_ctrl','var') || (isempty(memo_ctrl) && ~iscell(memo_ctrl))
memo_ctrl = hlp_resolve('memoize',[],ctx); end
action = 'skip';
result = {};
% first check whether the current expression is matched by anything in memoize
if iscell(memo_ctrl)
for i=1:2:length(memo_ctrl)
% evaluate whether memoization is enabled right now, and get a hash of exp, if so, and [] otherwise
exp_hash = hlp_microcache('cache_lookup',@hash_if_enabled,memo_ctrl{i+1},exp);
if exp_hash
% memoization is enabled for the following location
location = memo_ctrl{i};
if strcmp(location,'disk')
% DISK-BASED MEMOIZATION: compute the storage location according to some path schema
memo_path = [filesep exp_hash(1:2) filesep exp_hash(3:end) '.mat'];
if ~isfield(tracking,'cache')
% cache disabled...
return; end
% try all known disk paths for lookup
for p = fieldnames(tracking.cache.disk_paths)'
try
% try to load the file
location = tracking.cache.disk_paths.(p{1});
file_location = [location.dir memo_path];
t0 = tic;
load(file_location,'obj');
disp(['loaded ' file_location '.']);
% delete the file if it is invalid for some reason (e.g. the machine crashed during saving)
if ~exist('obj','var') && strcmp('.mat',file_location(end-3:end))
delete(file_location);
error('error');
end
% check whether the expression matches
if ~iscell(obj) || isempty(obj) || ~isfield(obj{1}, 'tracking') || ~isfield(obj{1}.tracking,'expression')
warning('BCILAB:exp_beginfun:memo_error','memoized object is not conformat; reverting...');
error('error');
end
if ~utl_same(obj{1}.tracking.expression,exp) && ~isequal_weak(obj{1}.tracking.expression,exp)
disp('exp_beginfun: hash conflict between ');
disp(['* retrieved: ' exp_fullform(obj{1}.tracking.expression)]);
disp(['* requested: ' exp_fullform(exp)]);
error('error');
end
% got the correct result: make the function return it
if ~isempty(result) && strcmp(action,'memoize')
% ... but first commit it to the other higher-priority memory locations that don't yet have it
for r=1:length(result)
utl_memoize_commit(obj,result{r}); end
end
result = obj;
action = 'return';
try
% ... and record some statistics on the read speed of this location...
objinfo = whos('obj');
location.readstats(end+1) = struct('size',{objinfo.bytes},'time',{toc(t0)});
% write back the updated location record
tracking.cache.disk_paths.(p{1}) = location;
catch,end
return;
catch,end
end
% value not yet stored: we want to memoize after the function's body has been evaluated, so remember the location data
action = 'memoize';
result{end+1} = memo_path;
elseif strcmp(location,'memory')
% MEMORY-BASED MEMOIZATION: compute the storage location according to a fieldname schema
memo_field = ['x' exp_hash];
% check if the requested object is present
try
% found: return
obj = tracking.cache.data.(memo_field);
% check whether the expression matches
if ~iscell(obj) || isempty(obj) || ~isfield(obj{1}, 'tracking') || ~isfield(obj{1}.tracking,'expression')
warning('BCILAB:exp_beginfun:memo_error','memoized object is not conformat; reverting...');
error('error');
end
if ~utl_same(obj{1}.tracking.expression,exp) && ~isequal_weak(obj{1}.tracking.expression,exp)
disp('exp_beginfun: hash conflict during lookup.');
error('error');
end
tracking.cache.times.(memo_field) = cputime; % for the least-recently used policy
% got the correct result: make the function return it
if ~isempty(result) && strcmp(action,'memoize')
% ... but first commit it to the other higher-priority memory locations that don't yet have it
for r=1:length(result)
utl_memoize_commit(obj,result{r}); end
end
result = obj;
action = 'return';
return;
catch,end
% not found: remember to memoize later
action = 'memoize';
result{end+1} = ['.' memo_field];
end
end
end
end
% find out whether a given memoization expression for some expression is enabled, and obtain the expression's hash if so...
function hash = hash_if_enabled(memo_exp,exp)
if exp_eval(utl_releasehold(utl_replacerepeated(memo_exp,{exp_rule(@expression,exp)})),inf)
hash = num2str(145342 + hlp_fingerprint(exp));
else
hash = [];
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_check_dataset.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_check_dataset.m
| 5,228 |
utf_8
|
9e99691540285666e5f5ec5dc35f01b4
|
function sig = utl_check_dataset(sig,opts,ctx,exp)
% Check whether the given argument is an imporperly tracked data set and fix.
% Data = utl_check_dataset(Data,Options,Context,Expressions)
%
% The remaining arguments are used only when the function is used as an argstep in exp_beginfun.
% There, it serves as an argstep for 'filter'/'editing' functions, to check, fix up and warn about
% the value of inconsistent impure expressions (expressions referring to signals, in particular) and
% data set values (without any notion of expressions).
%
% See also:
% exp_beginfun, exp_endfun
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-15
if ~exist('opts','var')
opts.fingerprint_check = true;
ctx = [];
exp = [];
end
% check if we have a data set
if isfield(sig,{'data','srate'})
if ~isfield(sig,'tracking') || ~isfield(sig.tracking,'expression')
% the data set was imported from EEGLAB or the tracking info was ruined
elseif isfield(sig.tracking,'fingerprint')
% get the fingerprint checking expression (either from the options or from the dynamic scope)
if isempty(opts.fingerprint_check)
opts.fingerprint_check = hlp_resolve('fingerprint_check',true,ctx); end
% check whether it is enabled
if ~opts.fingerprint_check
return; end
if isequal(opts.fingerprint_check,true) || hlp_microcache('fprint_lookup',@is_enabled,opts.fingerprint_check,exp)
fprint = hlp_fingerprint(rmfield(sig,'tracking'));
if fprint ~= sig.tracking.fingerprint
% the data set has been edited according to some fingerprint check
else
% no problem was spotted
return;
end
else
% fingerprinting disabled (nothing to check here...)
return;
end
else
return; % the data set does hot have a fingerprint
end
% --- the data set has been imported from EEGLAB or has been edited with it: do an implict flush-to-disk & re-import ---
if isfield(sig,'tracking')
if isfield(sig.tracking,'expression')
sig.tracking = rmfield(sig.tracking,'expression'); end
if isfield(sig.tracking,'online_expression')
sig.tracking = rmfield(sig.tracking,'online_expression'); end
if isfield(sig.tracking,'fingerprint')
sig.tracking = rmfield(sig.tracking,'fingerprint'); end
else
sig.tracking = struct();
end
% check for problems by scanning the history
found_problem = 0;
if isfield(sig,'history')
% catch a few known to be problematic operations in the imported data set
operations = { ...
{{'pop_epoch'}, ...
'Note: The BCILAB framework cannot operate on datasets that have been epoched using pop_epoch in EEGLAB.\n'}, ...
{{'pop_eegfilt','pop_runica'}, ...
'Note: The operation ''%s'' will neither allow to generate reliable predictions nor usable online models from the imported data set.\n'}, ...
{{'pop_averef','pop_interp','pop_reref','pop_resample','pop_rmbase','pop_subcomp'}, ...
'Note: The operation ''%s'' will not allow to generate online models from the imported data set.\n'}, ...
{{'pop_chansel','pop_rejchan','pop_rejchanspec','pop_select'}, ...
['Note: The operation ''%s'' requires that the channels supplied during online processing (and their order) match those' ...
' in the present data set.\n']}, ...
};
for l=1:length(operations)
for op=operations{l}{1}
if strfind(sig.history,[op{1} '('])
fprintf(operations{l}{2},op{1});
found_problem = 1;
end
end
end
if found_problem
fprintf(['\nIt is recommended that these operations be executed from BCILAB''s ' ...
'processing palette, since the operations implemented there are online-capable.\n']);
end
end
% (re-) create the fingerprint, if necessary
if ~exist('fprint','var')
fprint = hlp_fingerprint(rmfield(sig,'tracking')); end
% flush data to disk, if not already there...
filepath = ['temp:/flushedsets/' num2str(fprint) '.set'];
if ~exist(env_translatepath(filepath),'file')
disp('Flushing data set to disk...');
EEG = sig; %#ok<NASGU>
io_save(filepath,'EEG','-makedirs','-attributes','''+w'',''a''');
end
% change the expression into a re-loading
sig = io_loadset(filepath);
elseif isfield(sig,{'head','parts'})
% we have an expression: check parts recursively...
for p=1:length(sig.parts)
sig.parts{p} = utl_check_dataset(sig.parts{p},opts,ctx,exp); end
end
% find out whether a given reference expression yields true if @expression is substituted with some substitution expression
function res = is_enabled(ref_exp,subs_exp)
if exp_eval(utl_releasehold(utl_replacerepeated(ref_exp,{exp_rule(@expression,subs_exp)})),inf)
res = true;
else
res = false;
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_crossval.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_crossval.m
| 18,571 |
utf_8
|
62c4543edf1543c8940dfdd6fa1c3662
|
function [measure,stats] = utl_crossval(data, varargin)
% Run a generic cross-validation over indexable data.
% [Measure, Stats] = utl_crossval(Data, Arguments...)
%
% Cross-validation [1] is a data resampling technique in which per each iteration (or "fold"), a
% model is formed given a subset of the data (called the training set), and then its quality is
% tested on the remaining portion of the data (called the test set). Most applications of
% cross-validation ensure that each observation (or trial) in the data is used for testing in at
% least one fold. The most common version is k-fold cross-validation, where the data is split into k
% parts, and throughout k iterations of the algorithm, each of the parts is chosen as the test set
% exactly once, while the remaining k-1 parts are used jointly to train the model that shall be
% tested. Thus, each part of the data is used in k-1 training sets.
%
% The partitions of the data are traditionally chosen in a randomized fashion, under the assumption
% that each trial is identically and independently distributed w.r.t. the others. This assumption
% is wrong in time-series data (i.e. in almost all BCI cases). For this reason, the recommended
% cross-validation scheme in BCILAB is "chronological" (a.k.a. "block-wise") cross-validation, where
% the trials within the test set are taken from a compact interval of the underyling time series.
%
% In addition, it is recommended to exclude trials that are close to any of the test set trials
% from use in the respective training set (these excluded trials are called safety margins).
%
% The utl_crossval function is primarily used for testing predictive models, i.e., models which are
% learned to be able to estimate some "target" value for each data trial. Thus, the quality of a
% model given some test data is primarily assessed by letting it predict target values for each test
% trial, and comparing the outcomes with the known values for the given set of test trials.
%
% The data to be cross-validated can be in a variety of formats (as long as utl_crossval can
% determine how to partition it), and a custom partitioning function can be supplied for completely
% free-form data (such as EEGLAB data sets, which are handled by utl_dataset_partitioner). Aside
% from the data, usually two functions need to be passed - one to learn a model from some data
% portion (the 'trainer'), and one to test the learned model on some data portion (the 'tester'), by
% making predictions. Further customization options include choice of the comparison metric (or
% 'loss' function), choice of the function which extracts known target values from the data (as the
% ground truth used in the comparison), as well as cluster parallelization options.
%
% In:
% Data : some data that can be partitioned using index sets, such as, for example,
% {X,y} with X being the [NxF] training data and y being the [Nx1] labels
% (N=#trials, F=#features)
%
% Arguments : optional name-value pairs specifying the arguments:
% 'trainer': training function; receives a partition of the data (as produced by
% the specified partitioner), possibly some further arguments as
% specified in args, and returns a model (of any kind) (default:
% @ml_train; natively supports the {X,y} data format)
%
% 'tester' : testing function; receives a partition of the data (as produced by
% the partitioner) and a model (as produced by the trainer), and
% returns a prediction for every index of the input data, in one of the
% formats that can be produced by ml_predict (default: @ml_predict)
%
% 'scheme': cross-validation scheme, can be one of the following formats (default: 10)
% * 0: skip CV, return NaN and empty statistics
% * k: k-fold randomized CV (or, if 0<k<1, k-holdhout CV)
% * [r k]: r times repartitioned k-fold randomized CV (or, if 0<k<1, k-holdout CV
% (with k a fraction))
% * [r k m]: r times repartitioned k-fold randomized CV (or, if 0<k<1, k-holdout CV
% (with k a fraction)) with m indices margin width (between training and
% test set)
% * 'loo': leave-one-out CV
% * {'chron', k} or {'block', k}: k-fold chronological/blockwise CV
% * {'chron', k, m} or {'block', k, m}: k-fold chronological/blockwise CV with m
% indices margin width (between training and
% test set)
% * 'trainerr': This is the training-set error, i.e. it is a measure of the
% separability of the data (not of the generalization ability of the
% classifier); it is usually an error to report this number in a paper
%
% 'partitioner': partitioning function for the data, receives two parameters:
% (data, index vector)
% * if the index vector is empty, should return the highest index in
% the data OR a cell array of {training-partition,test-partition}
% for each fold (in the latter case, the partitioner fully controls
% the cross-validation scheme); for each fold, these two outputs
% will be fed into the partitioner as second argument to generate the
% training set and the test set, respectively
% * otherwise, it should return data subindexed by the index vector
% default: provides support for cell arrays, numeric arrays, struct
% arrays and {Data,Target} cell arrays
%
% 'target': a function to derive the target variable from a partition of the data
% (as produced by the partitioner), for evaluation; the allowed format is
% anything that may be output by ml_predict default: provides support for
% {Data,Target} cell arrays
%
% 'metric': metric to be employed, applied both to results of each fold and results
% aggregated over all folds
% * function handle: a custom, user-supplied loss function; receives target
% data in the first argument and prediction data in the second argument;
% each can be in any format that can be produced by ml_predict (but can be
% expected to be mutually consistent). shall return a real number
% indicating the summary metric over all data, and optionally additional
% statistics in a struct
% * string: use ml_calcloss, with 'metric' determining the loss type
% * default/empty: use 'mcr','mse','nll','kld' depending on supplied target
% and prediction data formats, via ml_calcloss
%
% 'args': optional arguments to the training function, packed in a cell array
% (default: empty)
% note: if using the default trainer/tester combination, args must at least
% specify the learning function to be used, e.g. {'lda'} for linear
% discriminant analysis (see ml_train* functions for options)
%
% 'repeatable': whether the randomization procedure shall give repeatable results
% (default: 1); different numbers (aside from 0) give different
% repeatable runs, i.e. the value determines the randseed
%
% 'return_models': whether to return models trained for each fold (default: false)
%
% 'engine_cv': parallelization engine to use (default: 'global'); see par_beginsschedule
%
% 'pool' : worker pool to use (default: 'global'); see par_beginsschedule
%
% 'policy': scheduling policy to use (default: 'global'); see par_beginschedule
%
% Out:
% Measure : a measure of the overall performance of the trainer/tester combination, w.r.t. to the
% target variable returned by the target function computed by the metric
%
% Stats : additional statistics, as produced by the metric
%
% Example:
% % assuming a feature matrix called trials and a label vector called targets, sized as:
% % trials: [NxF] array of training instances
% % targets: [Nx1] array of labels
%
% % cross-validate using (shrinkage) linear discriminant analysis
% [loss,stats] = utl_nested_crossval({trials,targets}, 'args',{'lda'})
%
% % cross-validate using hierarchical kernel learning with a specific kernel
% [loss,stats] = utl_nested_crossval({trials,targets}, 'args',{{'hkl' 'kernel' 'hermite'}})
%
% Configuration Examples:
% A simple training function would be:
% @ml_train, with args being {'lda'} -- for this case, the data X (size NxF) and labels y
% (size Nx1) should be supplied as {X,y} to utl_crossval
%
% A simple prediction function would be:
% @ml_predict
%
% A simple partitioner for epoched EEG data sets would be:
% function result = my_partitioner(data,indices,misc)
% if isempty(indices)
% result = data.trials;
% else
% result = exp_eval(set_selepos(data,indices));
% end
%
% A simple mean-square error loss metric would be:
% my_metric = @(target,predicted) mean((target-predicted).^2);
%
% A simple target extraction function for epoched EEG data sets would be (assuming that there is
% an epoch-associated target value):
% my_target = @(data) [data.epoch.target];
%
% References:
% [1] Richard O. Duda, Peter E. Hart, David G. Stork, "Pattern Classification"
% Wiley Interscience, 2000
%
% See also:
% utl_evaluate_fold, bci_train, utl_searchmodel, utl_nested_crossval
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-07
% read arguments
opts = hlp_varargin2struct(varargin, ...
'scheme',10, ...
'partitioner',@utl_default_partitioner, ...
'target',@utl_default_target, ...
'metric',@(T,P) ml_calcloss([],T,P), ...
'trainer',@ml_train, ...
'tester',@utl_default_predict, ...
'args',{}, ...
'repeatable',1, ...
'collect_models',false, ...
'engine_cv','global', ...
'pool','global', ...
'policy','global');
% string arguments are considered to be variants of the default metric
if isempty(opts.metric) || ischar(opts.metric) || (iscell(opts.metric) && all(cellfun(@ischar,opts.metric)))
opts.metric = @(T,P)ml_calcloss(opts.metric,T,P); end
if ~has_stats(opts.metric)
opts.metric = @(T,P)add_stats(opts.metric(T,P)); end
% derive indices from CV scheme & N
inds = make_indices(opts.scheme,opts.partitioner(data,[]),opts.repeatable);
if isempty(inds)
measure = NaN;
stats = struct();
else
time0 = tic;
% generate tasks for each fold
for p = 1:length(inds)
tasks{p} = {@utl_evaluate_fold,opts,data,inds{p}}; end
% schedule the tasks
results = par_schedule(tasks, 'engine',opts.engine_cv, 'pool',opts.pool, 'policy',opts.policy);
% collect results
for p=1:length(inds)
% collect results
targets{p} = results{p}{1};
predictions{p} = results{p}{2};
if opts.collect_models
models{p} = results{p}{3}; end
end
% compute aggregate metric
[dummy,stats] = opts.metric(utl_aggregate_results(targets{:}),utl_aggregate_results(predictions{:})); %#ok<ASGLU>
% add per-fold metric
for p=1:length(targets)
stats.per_fold(p) = hlp_getresult(2,opts.metric,targets{p},predictions{p}); end
% calculate basic cross-validation statistics
tmp = [stats.per_fold.(stats.measure)];
stats.(stats.measure) = mean(tmp);
stats.([stats.measure '_mu']) = mean(tmp);
stats.([stats.measure '_std']) = std(tmp);
stats.([stats.measure '_med']) = median(tmp);
stats.([stats.measure '_mad']) = median(abs(tmp-median(tmp)));
measure = mean(tmp);
% also add the original targets & predictions
for p=1:length(targets)
stats.per_fold(p).targ = targets{p};
stats.per_fold(p).pred = predictions{p};
end
% add original index sets
if all(cellfun(@(inds) length(inds{1}) < 10000 && length(inds{2}) < 10000,inds))
for p=1:length(targets)
stats.per_fold(p).indices = inds{p}; end
end
% add collected models, if any
if opts.collect_models
for p=1:length(models)
stats.per_fold(p).model = models{p}; end
end
% add additional stats
stats.time = toc(time0);
end
end
function inds = make_indices(S,N,repeatable)
% Inds = make_indices(Scheme,Index-Cardinality)
% make cross-validation indices for each fold, from the scheme and the index set cardinality
if iscell(N) && all(cellfun('isclass',N,'cell')) && all(cellfun('prodofsize',N)>=2)
% the partitioner returned the index sets already; pass them through
inds = N;
else
if strcmp(S,'trainerr')
% special case: index set for computing the training-set error
inds = {{1:N,1:N}};
else
% regular case: proper cross-validation
% set parameter defaults
k = 10; % foldness or fraction of holdout data
repeats = 1; % # of monte carlo repartitions
randomized = 1; % randomized indices or not
margin = 0; % width of the index margin between training and evaluation sets
subblocks = 1; % number of sub-blocks within which to cross-validate
% parse scheme grammar
if isnumeric(S) && length(S) == 3
% "[repeats, folds, margin]" format
repeats = S(1);
k = S(2);
margin = S(3);
elseif isnumeric(S) && length(S) == 2
% "[repeats, folds]" format
repeats = S(1);
k = S(2);
elseif iscell(S) && ~isempty(S) && ischar(S{1}) && ...
(strcmp('chron',S{1}) || strcmp('block',S{1}))
% "{'chron', k, m}" format
randomized = 0;
if length(S) > 1 && isscalar(S{2})
k = S{2}; end
if length(S) > 2 && isscalar(S{3})
margin = S{3}; end
elseif iscell(S) && ~isempty(S) && ischar(S{1}) && ...
(strcmp('subchron',S{1}) || strcmp('subblock',S{1}))
% "{'subchron', b, k, m}" format
randomized = 0;
if length(S) > 1 && isscalar(S{2})
subblocks = S{2}; end
if length(S) > 2 && isscalar(S{3})
k = S{3}; end
if length(S) > 3 && isscalar(S{4})
margin = S{4}; end
elseif isscalar(S)
% "k" format
k = S;
elseif ischar(S) && strcmp(S,'loo')
% "'loo'" format
k = N;
elseif iscell(S) && all(cellfun('isclass',S,'cell')) && all(cellfun('prodofsize',S)>=2)
% direct specification
inds = S;
return;
else
error('unknown cross-validation scheme format');
end
% check for skipped CV
inds = {};
if k <= 0
return; end
if randomized && repeatable
if hlp_matlab_version < 707
% save & override RNG state
randstate = rand('state'); %#ok<*RAND>
rand('state',5182+repeatable); %#ok<RAND>
else
% create a legacy-compatible RandStream
randstream = RandStream('swb2712','Seed',5182+repeatable);
end
end
% generate evaluation index sets from the parameters
try
if subblocks == 1
perm = 1:N;
else
Nblock = N + subblocks-mod(N,subblocks);
perm = reshape(1:Nblock,[],subblocks)';
perm = round(perm(:)*N/Nblock);
end
for r=1:repeats
if randomized
if hlp_matlab_version < 707
perm = randperm(N);
else
perm = randstream.randperm(N);
end
end
if k < 1
% p-holdout
inds{end+1} = {sort(perm(1+(0:(round(N*k)-1))))};
else
% k-fold
for i=0:k-1
inds{end+1} = sort(perm(1+floor(i*N/k) : min(N,floor((i+1)*N/k)))); end
end
end
catch err
% % this error is thrown only after the subsequent delicate RNG state restoration
indexgen_error = err;
end
if randomized && repeatable && hlp_matlab_version < 707
% restore saved RNG state
rand('state',randstate); %#ok<RAND>
end
if exist('indexgen_error','var')
rethrow(indexgen_error); end % throw the error that happened during previous index set creation
% add complementary training index sets
for i=1:length(inds)
tmpinds = true(1,N);
tmpinds(inds{i}) = 0;
for j=1:margin
tmpinds(max(1,inds{i}-j)) = 0;
tmpinds(min(N,inds{i}+j)) = 0;
end
inds{i} = {find(tmpinds),inds{i}};
end
end
end
end
% test whether the given metric supplies stats or not
function result = has_stats(metric)
try
[x,y] = metric([],[]); %#ok<NASGU,ASGLU>
result = true;
catch e
result = ~any(strcmp(e.identifier,{'MATLAB:TooManyOutputs','MATLAB:maxlhs','MATLAB:unassignedOutputs'}));
end
end
% add stats to the result of some metric
function [result,stats] = add_stats(result)
stats.value = result;
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_prune_handles.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_prune_handles.m
| 1,215 |
utf_8
|
693a58479eb9a012c85a785e96e5a1ff
|
function x = utl_prune_handles(x)
% Prune unreferenced workspace variables from anonymous functions in the given argument.
%
% In:
% Data : an arbitrary data structure
%
% Out:
% Data : the data structure with hidden references in anonymous functions removed
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-11-23
if iscell(x)
% recurse into cell arrays...
for k=1:numel(x)
x{k} = utl_prune_handles(x{k}); end
elseif isstruct(x)
% recurse into structs...
for f=fieldnames(x)'
if ~isempty(x)
[x.(f{1})] = celldeal(utl_prune_handles({x.(f{1})})); end
end
elseif isa(x,'function_handle')
% inspect function handles
f = char(x);
if f(1) == '@'
% anonymous function: take apart...
parts = functions(x);
% ... and put back together
x = make_function(f,parts.workspace{1});
end
end
% create a function handle
function f = make_function(decl__,workspace__)
% create workspace
for fn__=fieldnames(workspace__)'
eval([fn__{1} ' = workspace__.(fn__{1}) ;']); end
clear workspace__ fn__;
% evaluate declaration
f = eval(decl__);
|
github
|
ZijingMao/baselineeegtest-master
|
utl_resolve_streams.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_resolve_streams.m
| 16,798 |
utf_8
|
38280b0e6e9771ff30e132ca3877ac2d
|
function pip = utl_resolve_streams(pip,streams,chanlocs)
% resolve the stream that each rawdata node in the given filter chain requires, given a list
% of workspace stream names (or stream structs), and a subset of channels needed by above pipelines (where empty means 'all')
%
% In:
% Pipeline : a filter chain or filter graph (cell array of filter chains) with rawdata nodes to resolve
%
% Streams : a cell array of workspace stream names, or a cell array of stream/dataset structs,
% or a stream bundle (struct with .streams{} cell array); these are the candidates
% that shall be subsituted into the open rawdata nodes
%
% Chanlocs : optionally the chanlocs structure that is expected at the outlet of the filter
% chain, as cell array of chanlocs structs in case the pipeline is a filter graph; if
% known, it can help in situations where a candidate stream provides fewer channels than
% technically required by the filter chain -- but not effectively required as the chain
% prunes some of them further down the processing
%
% Out:
% Pipeline : the pipeline with matched streams filled in at the @rawdata nodes;
% if streams was a name array, then the rawdata nodes are augmented with the stream name
% (for online processing); otherwise, the expression of the respective stream is
% substituted in place of the respective rawdata node
%
% See also:
% bci_train, bci_predict, onl_newpredictor
%
% Notes:
% The matching is generally case insensitive (both for channel labels and channel types).
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-11-23
% turn streams into a cell array
if isstruct(streams) && isscalar(streams) && isfield(streams,'streams')
streams = streams.streams; end
if ~iscell(streams)
streams = {streams}; end
% resolve stream properties
for s = 1:length(streams)
if ischar(streams{s})
% stream given as a workspace variable name:
% - can read out the chanlocs.labels directly from it
% - we take the types as declared by the stream
% - we substitute the variable name into the rawdata node, as we will refer to this stream online
tmp = evalin('base',streams{s});
streams{s} = struct('labels',{{tmp.chanlocs.labels}},'types',{tmp.types},'substitute',streams{s});
elseif all(isfield(streams{s},{'chanlocs','tracking'}))
% stream is given as a full data set:
% - can read out the chanlocs & their types directly from it
% - we substitute the streams expression in there
streams{s} = struct('labels',{{streams{s}.chanlocs.labels}},'types',{unique({streams{s}.chanlocs.type})},'substitute',streams{s}.tracking.expression);
elseif all(isfield(streams{s},{'head','parts'}))
% stream is an unevaluated expression:
% - we try to infer the chanlocs & their types from it without evaluating too much of it
% - we substitute the stream expression itself
streams{s} = resolve_stream_properties(streams{s});
end
end
% now resolve rawdata nodes using the stream information
if ~iscell(pip)
% pipeline given as single filter chain
if exist('chanlocs','var') && ~isempty(chanlocs)
labels = {chanlocs.labels};
if isfield(chanlocs,'type')
types = unique({chanlocs.type});
else
types = [];
end
else
labels = [];
types = [];
end
pip = resolve_rawdata(pip,streams,labels,types);
else
% pipeline given as a cell array: resolve each one by one
if exist('chanlocs','var') && ~isempty(chanlocs)
if ~iscell(chanlocs)
error('If given, chanlocs should be a cell array with one cell for each chain in the filter graph.'); end
if length(chanlocs) ~= length(pip)
error('The Chanlocs array has a different number of elements than the filter graph.'); end
for p = 1:length(pip)
labels{p} = {chanlocs{p}.labels}; %#ok<AGROW>
if isfield(chanlocs{p},'type')
types{p} = unique({chanlocs{p}.type}); %#ok<AGROW>
else
types{p} = [];
end
end
else
labels = repmat({[]},1,length(pip));
types = repmat({[]},1,length(pip));
end
for p = 1:length(pip)
pip{p} = resolve_rawdata(pip{p},streams,labels{p},types{p}); end
end
function pip = resolve_rawdata(pip,streams,chan_subset,type_subset)
% Resolve rawdata nodes in a single filter chain into streams.
%
% In:
% Pipeline : the filter chain
%
% Streams : cell array of structs with fields .labels, .types, and .substitute
% (.labels is a cell array of labels provided by the stream, .types is a cell array of
% channel types (unique) provided by the stream, and .substitute is the object that
% should be used for substitution in the respective rawdata slot if it matches)
%
% RequiredChannels : full set of channel labels that are required from this pipeline (may be a
% subset of the channel labels expected at the @rawdata node, in which case
% fewer channels need to be provided by a matching stream); may be a cell array
% of channel labels or index range, or [] (which stands for "all channels" of this stage)
%
% RequiredTypes : full set of channel types that are required from this pipeline (may be a subset
% of the types expected at the rawdata node, in which case fewer channeels need to
% be provided by the matching stream); may also be [] (which stands for "all types" of this stage)
%
% Out:
% Pipeline : the filter chain with @rawdata nodes substituted appropriately
%
phead = char(pip.head);
if ~strcmp(phead,'rawdata')
% --- intermediate node ---
% figure out the needed channels & types along the way
if strcmp(phead,'flt_selchans')
% a selchans node: informs us that we need only a subset of channels from our input streams
% find the last index in the pipeline's arguments that is 'channels'...
% the channel selection is the argument following that (it is a name-value pair)
ci = find(strcmp(pip.parts,'channels'),1,'last');
selected_chans = pip.parts{ci+1};
% our current channel working subset is either a subset of the selection done by this
% flt_selchans or refers to "all" channels
if isempty(chan_subset)
% "all" channels required: we need the entire chan selection at this level
chan_subset = selected_chans;
elseif isnumeric(chan_subset)
% we need an index subrange of pip.parts
chan_subset = selected_chans(chan_subset);
else
% we known which named subset we need; the flt_selchans does not provide additional info
end
elseif strcmp(phead,'flt_seltypes')
% a seltypes node: informs us that we need only a subset of channel types from here on
if isempty(type_subset)
% find the last index in the pipeline's arguments that is 'types'...
% the channel selection is the argument following that (it is a name-value pair)
ti = find(strcmp(pip.parts,'chantypes'),1,'last');
type_subset = pip.parts{ti+1};
if ~iscell(type_subset)
type_subset = {type_subset}; end
else
% note: if we already have a type subset from farther up in the processing chain we
% don't need additional info from this stage
end
else
% a generic node: check if this one mixes channels -- in which case we need all channels & types from below
props = hlp_microcache('props',@arg_report,'properties',pip.head,{hlp_fileinfo(pip.head,[],'hash')});
if ~props.independent_channels
% the node doesn't have independent channels: need all channnels & types from below
chan_subset = [];
type_subset = [];
end
end
% and follow down its inlets
for p = find(cellfun(@(p)all(isfield(p,{'head','parts'})),pip.parts))
pip.parts{p} = resolve_rawdata(pip.parts{p},streams,chan_subset,type_subset); end
else
% --- reached a rawdata node: resolve it using streams ---
% find out what types we need
if isempty(type_subset)
% all types from here are needed
needed_types = pip.parts{2};
elseif iscell(type_subset)
% can restrict the types according to the already known type subset (from further up the pipeline)
needed_types = intersect(pip.parts{2},type_subset);
else
error('Unsupported type subset format.');
end
% find out what channels we need
if isempty(chan_subset)
% all channels are needed
needed_channels = pip.parts{1};
elseif iscell(chan_subset)
% a particular named set of channels is needed
needed_channels = chan_subset;
elseif isnumeric(chan_subset)
% an index range referring to the base channel set is needed
needed_channels = pip.parts{1}(chan_subset);
else
error('Unsupported channel subset format.');
end
satisfies_channels = logical([]); % the stream can provide all the channels required by the pipeline (ideal case if non-ambiguous)
satisfies_types = logical([]); % the stream has the same number of channels and set of types as required by the pipeline (happens when the online plugin doesn't supply the correct channel labels...)
% for each stream...
for s = 1:length(streams)
% find out if the stream matches
satisfies_channels(s) = isempty(fast_setdiff(lower(needed_channels),lower(streams{s}.labels)));
satisfies_types(s) = length(pip.parts{1}) == length(streams{s}.labels) && isequal(sort(lower(needed_types)),lower(streams{s}.types));
end
% resolve the stream used for this rawdata node
if nnz(satisfies_channels) == 1
% found exactly one applicable stream
strm = streams{satisfies_channels};
if ischar(strm.substitute)
% substitute a variable name into the rawdata node
pip = struct('head',@rawdata,'parts',{{strm.substitute,set_chanid(strm.labels,needed_channels)}});
else
% substitute the rawdata node by the stream's expression
pip = strm.substitute;
end
else
% no clear-cut case: check whether the channel numbers & set of types matches
if nnz(satisfies_channels) > 1
% found more than one stream: include the type constraint
if nnz(satisfies_channels & satisfies_types) == 1
% now it is non-ambiguous, but warn
warning('BCILAB:onl_newpredictor:ambiguous','More than one of the supplied/available streams could supply the required channels; falling back to basic channel type requirements to resolve the ambiguity.');
strm = streams{satisfies_channels & satisfies_types};
if ischar(strm.substitute)
% stream given as a variable name: augment the rawdata node
pip = struct('head',@rawdata,'parts',{{strm.substitute,set_chanid(strm.labels,needed_channels)}});
else
% substitute the rawdata node by the stream's expression
pip = strm.substitute;
end
elseif nnz(satisfies_channels & satisfies_types) > 1
% still ambiguous
error('BCILAB:onl_newpredictor:ambiguous','More than one of the supplied/available streams could supply the required channels & types; please provide the desired subset of streams.');
else
% the additional constraint eliminates all options
error('BCILAB:onl_newpredictor:ambiguous','More than one of the supplied/available streams could supply the required channels; please provide the desired subset of streams.');
end
elseif nnz(satisfies_types) == 1
% found exactly one stream which has the correct number of channels and the same set of types
warning('BCILAB:onl_newpredictor:ambiguous','No stream was found which contains the required channels; however, a stream was found to have the same number of channels and set of types as required by the pipeline.');
strm = streams{satisfies_types};
if ischar(strm)
% stream given as a variable name: augment the rawdata node
pip = struct('head',@rawdata,'parts',{{strm,1:length(strm.labels)}});
else
% substitute the rawdata node by the stream's expression
pip = strm.substitute;
end
else
% found no applicable stream
error('BCILAB:onl_newpredictor:nostream',['None of the supplied/available streams has the required channels: ' hlp_tostring(needed_channels) '.']);
end
end
end
function output = resolve_stream_properties(stream)
% recursively infer the channel labels & types, as well as the substitution expression produced by this pipeline stage
if isfield(stream,'chanlocs')
% we have reached a data set node: derive all properties
output.chanlocs = stream.chanlocs;
output.labels = {stream.chanlocs.labels};
output.types = unique({stream.chanlocs.type});
try
output.substitute = stream.tracking.expression;
catch %#ok<CTCH>
error('Reached a dataset node which is lacking an associated expression. This should have been resolved previously using utl_check_dataset or utl_check_bundle.');
end
elseif all(isfield(stream,{'head','parts'}))
% we are looking at a symbolic expression
output.substitute = stream;
% check if it is a special known one
shead = char(stream.head);
switch(shead)
case 'io_loadset'
% the chanlocs info can be obtained from the underlying raw data set
tmp = exp_eval_optimized(stream);
output.chanlocs = tmp.chanlocs;
output.labels = {tmp.chanlocs.labels};
output.types = unique({tmp.chanlocs.type});
case 'flt_selchans'
% a channel subset has been selected here: get the chanlocs from further below...
subprops = resolve_stream_properties(stream.parts{find(cellfun(@(p)all(isfield(p,{'head','parts'})),stream.parts),1)});
% and get the selected channel labels
selection = stream.parts{find(strcmp(stream.parts,'channels'),1,'last')+1};
output.chanlocs = subprops.chanlocs(set_chanid(subprops.chanlocs,selection));
output.labels = {output.chanlocs.labels};
output.types = unique({output.chanlocs.type});
case 'flt_seltypes'
% a type subset has been selected here: get the chanlocs from further below
subprops = resolve_stream_properties(stream.parts{find(cellfun(@(p)all(isfield(p,{'head','parts'})),stream.parts),1)});
% and get the selected type labels
selection = stream.parts{find(strcmp(stream.parts,'types'),1,'last')+1};
if ~iscell(selection)
selection = {selection}; end
% now restrict both the types and the chanlocs appropriately
[dummy,ia] = intersect(lower({subprops.chanlocs.type}),lower(selection)); %#ok<ASGLU>
output.chanlocs = subprops.chanlocs(ia);
output.labels = {output.chanlocs.labels};
output.types = unique({output.chanlocs.type});
case 'exp_block'
output = resolve_stream_properties(stream.parts{2});
otherwise
% generic expression node: check if this node mixes up channels ...
props = hlp_microcache('props',@arg_report,'properties',stream.head,{hlp_fileinfo(stream.head,[],'hash')});
if isfield(props,'independent_channels') && props.independent_channels
% has independent channels: just take the output from below
output = resolve_stream_properties(stream.parts{find(cellfun(@(p) any(isfield(p,{'parts','chanlocs'})),stream.parts),1)});
output.substitute = stream;
else
% does not have independent channels: need to evaluate the sub-expression
tmp = exp_eval_optimized(stream);
output.chanlocs = tmp.chanlocs;
output.labels = {tmp.chanlocs.labels};
output.types = unique({tmp.chanlocs.type});
end
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_collection_partition.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_collection_partition.m
| 14,933 |
utf_8
|
ac43428cc40e2b8adf3e76d0eb985dfc
|
function res = utl_collection_partition(collection,inds,settings)
% Partition a dataset collection according to some settings
% Result = utl_collection_partition(Collection,IndexSet,Settings)
%
% In:
% Collection : a dataset collection, i.e. cell array of structs with meta-data
%
% IndexSet : the index set to use for partitioning; this partitioner is somewhat special;
% * if this is [], the function generates the partitioning, i.e. returns
% a cell array of partitions, each of which is a cell array of:
% {training collection, test collection, {'goal_identifier',identifier for test collection}}
%
% * otherwise, we assume that this is one of the partitioned collections that we
% generated, and just return it unmodified
%
% Settings : the settings for the partitioning; may have the following fields (or names, if given
% as a cell array of NvPs):
%
% 'restrict_to' : struct with properties to which the test sets under consideration are
% restricted (default: blank / no restriction)
% 'exclude' struct with a property signature to exclude from the test sets
% or a cell array of multiple signatures to exclude
% 'test_on' : identifier that determines the items to use as test sets (default:
% coarsest granularity out of the known identifiers or element-by-element,
% if none known)
% 'consider' : modifier that determines how to pack and optionally prune the test
% items ('each', 'all', 'last', or 'allexceptfirst')
% (default: 'each')
% 'per' : if consider is not each, determines the context to which the
% packing and pruning operation of 'consider' refers
% (default: next coarser granularity than test_on)
%
% 'scope_order' : odering of partitioning-relevant properties from coarsest granularity
% to finest (default: {'group','subject','day','montage','session','recording'}
%
% This expresses, among others, that there exist multiple sessions
% (say 1,2,3) for each subject -- i.e. the session property is *per
% subject*, and thus two sets tagged with session 3 do not
% necessarily refer to the same unique session (unless the subject,
% day, montage (if present) are also the same. If any such nesting
% relationship is properly expressed, the 'test_on' and 'per' settings
% will work as expected.
%
% Out:
% Result : result of the partitioning; depends on the IndexSet
%
% See also:
% set_partition, bci_train
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-08-29
if isempty(inds)
settings = hlp_varargin2struct(settings, ...
{'scope_order','ScopeOrdering'}, {'group','subject','day','montage','session','recording'}, ... % the known granularities ordered from coarsest to finest
{'restrict_to','RestrictTo'}, [], ... % struct with properties to which restrict test considered test sets (default: blank)
{'exclude','Exclude'}, {}, ... % struct with a property signature to exclude from the test sets, or cell array of such structs) (default: blank)
{'test_on','TestOn'}, [], ... % identifier that determines the items to use as test sets (default: coarsest known granularity)
{'consider','Consider'},'each', ... % specifier that determines which items to consider (options: 'each','all','last','allexceptfirst')
{'per','Per'},[] ... % if consider is not each, determines the context to which the last/allbutfirst refers (default: next coarsest granularity)
);
known_granularities = settings.scope_order;
if length(unique(known_granularities)) < length(known_granularities)
error('Please do not pass duplicates in the scope_order parameter.'); end
% first tag all items in the collection with a unique tracking id
% (will be used towards the end to determine the contents of the respective training sets)
for k=1:length(collection)
collection{k}.tracking_index = k; end
% restrict the collection of test set material according to the restrict_to property
test_material = collection;
if ~isempty(settings.restrict_to)
for fn = fieldnames(settings.restrict_to)'
field = fn{1};
present = find(cellfun(@(x)isfield(x,field),test_material));
if isempty(present)
fprintf('None of the sets in the collection has the property "%s"; ignoring this restriction.\n',field);
else
test_material = test_material(present);
end
restrictor = settings.restrict_to.(field);
retain = cellfun(isequal_weak(@(x)x.(field),restrictor),test_material,'UniformOutput',false);
if ~any(retain)
fprintf('None of the sets in the collection has value "%s" for property "%s"; ignoring this restriction.\n',hlp_tostring(restrictor),field);
else
test_material = test_material(retain);
end
end
end
% implement the exclusion
if isstruct(settings.exclude)
settings.exclude = {settings.exclude}; end
% for each excluder...
for e=1:length(settings.exclude)
ex = settings.exclude{e};
% go through all fields and identify matches
potential_match = true(1,length(test_material));
for fn=fieldnames(ex)'
field = fn{1};
val = ex.(field);
present = cellfun(@(x)isfield(x,field),test_material);
matching_value = true(1,length(test_material));
matching_value(present) = cellfun(@(x)isequal_weak(x.(field),val),test_material(present));
potential_match = potential_match & present & matching_value;
end
% retain only the non-matching test items
test_material = test_material(~potential_match);
end
% remove all entries from known_granularities which are not contained in the test material and
% remove all elements from the test material which are lacking one of the remaining granularity properties
retain = [];
for k=1:length(known_granularities)
gran = known_granularities{k};
present = cellfun(@(x)isfield(x,gran),test_material);
if any(present)
test_material = test_material(present);
retain(end+1) = k;
end
end
known_granularities = known_granularities(retain);
if isempty(settings.test_on)
% use coarsest granularity to test on
if ~isempty(known_granularities)
settings.test_on = known_granularities{1}; end
end
if ~strcmp(settings.consider,'each')
if isempty(settings.per)
% need to determine the granularity at which to pack test items
if isempty(settings.test_on)
% we're testing on individual data items, so the finest known granularity in the
% data will be used for grouping
if ~isempty(known_granularities)
settings.per = known_granularities{end}; end
else
% see if we can find the next-coarser granularity
known_gran = find(strcmp(settings.test_on,known_granularities),1);
if ~isempty(known_gran)
if known_gran == 1
error('The testing is already performed at the coarsest known granularity; cannot determine a coarser granularity to group data into. You may specify the ''per'' property manually.');
else
settings.per = known_granularities{known_gran-1};
end
end
end
if isempty(settings.per)
error('Please specify a granularity (i.e. a property) over which the ''consider'' clause should apply.'); end
end
% prune the test material appropriately
present = find(cellfun(@(x)isfield(x,settings.per),test_material));
if isempty(present)
error('None of the sets in the collection has the ''per'' property "%s".\n',settings.per);
else
% exclude all items that are lacking the given field
test_material = test_material(present);
end
end
% build the test sets, which is a cell array of collections -- one per test set
test_sets = {};
if isempty(settings.test_on)
% test at the granularity of data sets in the collection (finest)
for k=1:length(test_material)
test_sets{k} = {test_material{k}}; end
else
% test at the given granularity
present = find(cellfun(@(x)isfield(x,settings.test_on),test_material));
if isempty(present)
error('None of the sets in the collection has the ''test_on'' property "%s".\n',settings.test_on);
else
% exclude all items that are lacking the given field
test_material = test_material(present);
end
% we partition the test material into test sets by unique elements of the 'test_on' property
% and all coarser properties, if any; next: build the list of these properties
pos = find(strcmp(settings.test_on,known_granularities));
if ~isempty(pos)
partition_properties = known_granularities(1:pos);
else
partition_properties = {settings.test_on};
end
% now partition
values = cellfun(@(x)getprops_as_string(x,partition_properties),test_material,'UniformOutput',false);
uniquevals = unique(values);
for v=1:length(uniquevals)
matches = strcmp(values,uniquevals{v});
test_sets{v} = test_material(matches);
end
end
% optionally re-pack and/or prune the test sets according to the consider clause
if ~strcmp(settings.consider,'each')
% we repack the test sets into groups by unique elements of the 'per' property
% and all coarser properties, if any; next: build the list of these properties
pos = find(strcmp(settings.per,known_granularities));
if ~isempty(pos)
partition_properties = known_granularities(1:pos);
else
partition_properties = {settings.per};
end
% sanity check: make sure that each test set has only one unique 'per' identifier
for k=1:length(test_sets)
if length(unique(cellfun(@(x)getprops_as_string(x,partition_properties),test_sets{k},'UniformOutput',false))) > 1
error('You are trying to operate on your %s''s in groups per %s, but some of the %s''s consist of items in multiple groups. You can likely avoid this problem by specifying including both properties in the ''scope_order'' list at the appropriate place.'); end
end
% now partition by 'per'
test_groups = {};
values = cellfun(@(x)getprops_as_string(x{1},partition_properties),test_sets,'UniformOutput',false);
uniquevals = unique(values);
for v=1:length(uniquevals)
matches = strcmp(values,uniquevals{v});
test_groups{v} = test_sets(matches);
end
% and re-pack/prune to get the final test sets
test_sets = {};
switch settings.consider
case 'all'
% flatten the test groups
for g=1:length(test_groups)
test_sets{g} = [test_groups{g}{:}]; end
case 'last'
% take only the last set per group (= the one with the highest value for the test_on property)
for g=1:length(test_groups)
idx = argmax(cellfun(@(x)x{1}.(settings.test_on),test_groups{g}));
test_sets{g} = [test_groups{g}{idx}];
end
case 'allexceptfirst'
% take all except for the first set per group (= all except for those with the lowest value for the test_on property)
for g=1:length(test_groups)
idx = argmin(cellfun(@(x)x{1}.(settings.test_on),test_groups{g}));
test_sets{g} = [test_groups{g}{setdiff(1:end,idx)}];
end
otherwise
error('Unsupported ''consider'' clause specified.');
end
end
% build the final partition
res = {};
for s=1:length(test_sets)
testset = test_sets{s};
% derive the corresponding training sets
test_indices = cellfun(@(x)x.tracking_index,testset);
not_in_test = cellfun(@(x)~ismember(x.tracking_index,test_indices),collection);
trainset = collection(not_in_test);
% get rid of tracking indices
for k=1:length(trainset)
trainset{k} = rmfield(trainset{k},'tracking_index'); end
for k=1:length(testset)
testset{k} = rmfield(testset{k},'tracking_index'); end
% also derive the common identifying information of the test sets:
common_fields = setdiff(fieldnames(testset{1}),{'streams'});
for k=2:length(testset)
common_fields = intersect(common_fields,fieldnames(testset{k})); end
if length(testset) > 1
% restrict to those fields that are unique across all test sets
retain = [];
for c=1:length(common_fields)
field = common_fields{c};
val = testset{1}.(field);
if all(cellfun(@(x)isequal_weak(x.(field),val),testset(2:end)))
retain(end+1) = c; end
end
common_fields = common_fields(retain);
end
% form an identifier struct for the test set; the cross-validation will append the contents
% of this cell array as additional arguments into the trainer function
identifier = [];
for f=1:length(common_fields)
identifier.(common_fields{f}) = testset{1}.(common_fields{f}); end
% combine
res{s} = {trainset,testset,{'goal_identifier',identifier}};
end
else
% otherwise just pass through the index set
res = inds;
end
% obtain a string version of values from a struct, for a given cell array of properties
function y = getprops_as_string(x,props)
y = hlp_tostring(cellfun(@(p)x.(p),props,'UniformOutput',false));
|
github
|
ZijingMao/baselineeegtest-master
|
utl_timeseries_fields.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_timeseries_fields.m
| 2,603 |
utf_8
|
09b9960261401f01fc406f35b8985890
|
function fields = utl_timeseries_fields(signal)
% Get the time-series fields of te given signal.
% function Fields = utl_timeseries_fields(Signal)
%
% This function returns the field names in the given signal that are
% carrying time-series information (and which therefore should be filtered,
% buffered, etc.). The result is a combination of a set of hard-coded fields
% and the names listed in the field .tracking.timeseries_fields. Only fields
% that are present in the signal are returned.
%
% In:
% Signal : a signal for which time-series field names shall be looked up
%
% Out:
% Fields : Cell array of field names (row vector). It is assumed that the second dimension of
% these fields is the time axis along which buffering and/or filtering should happen; any
% number of other dimensions may be present for any field returned by this function.
%
% See also:
% utl_register_field
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2013-08-16
% define a database of cached queries and associated results
% (this approach is more than 10x as fast as using unique/intersect every time)
persistent keys;
persistent values;
% generate the query (assuming that the signal usually has the right fields)
try
query = [fieldnames(signal)' {'|'} signal.tracking.timeseries_fields];
catch
query = fieldnames(signal)';
end
% turn into a string
query = [query{:}];
try
% look up from the database (assuming that it is already contained)
fields = values{strcmp(keys,query)};
catch
% not yet in DB: actually determine the timeseries fields
if isfield(signal,'tracking') && isfield(signal.tracking,'timeseries_fields')
fields = get_timeseries_fields(fieldnames(signal),signal.tracking.timeseries_fields);
else
fields = get_timeseries_fields(fieldnames(signal),[]);
end
% initialize the DB if necessary, otherwise append
if ~iscell(keys)
keys = {query};
values = {fields};
else
keys{end+1} = query;
values{end+1} = fields;
end
end
function fields = get_timeseries_fields(field_names,ts_fields)
% This function performs the actual computation
% generate initial list of candidates
candidates = {'data','icaact','srcpot'};
% append whatever is registered in the signal's .tracking.timeseries_fields
candidates = unique([candidates(:); ts_fields(:)]);
% restrict to those that are actually present in the signal
fields = intersect(candidates(:),field_names);
fields = fields(:)';
|
github
|
ZijingMao/baselineeegtest-master
|
utl_printapproach.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_printapproach.m
| 2,158 |
utf_8
|
f2d75a0e24733c93a2b3841475b3a743
|
function string = utl_printapproach(app,strip_direct,indent,indent_incr)
% Convert an approach to a string representation
% String = utl_printapproach(Approach)
%
% In:
% Approach : a BCI approach, either designed in the GUI or constructed in a script
%
% StripDirect : strip arg_direct flags (default: true)
%
% Indent : initial indent (default: 0)
%
% IndentIncrement : indentation increment (default: 4)
%
% Out:
% String : a string representation of the approach, for use in scripts
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2013-10-22
% check inputs
if nargin < 2
strip_direct = true; end
if nargin < 3
indent = 0; end
if nargin < 4
indent_incr = 4; end
% get required approach properties
if ischar(app)
paradigm = ['Paradigm' app];
parameters = {};
elseif iscell(app)
paradigm = ['Paradigm' app{1}];
parameters = app(2:end);
else
paradigm = app.paradigm;
parameters = app.parameters;
end
% get a handle to the paradigm's calibrate() function
instance = eval(paradigm);
func = @instance.calibrate;
% report both the defaults of the paradigm and
% the current settings in form of argument specifications
defaults = clean_fields(arg_report('rich',func));
settings = clean_fields(arg_report('lean',func,parameters));
% get the difference as cell array of human-readable name-value pairs
specdiff = arg_diff(defaults,settings);
difference = arg_tovals(specdiff,[],'HumanReadableCell',false);
% pre-pend the paradigm choice
paradigm_name = char(paradigm);
difference = [{'arg_selection',paradigm_name(9:end)} difference];
% and convert to string
string = arg_tostring(difference,strip_direct,indent,indent_incr);
% clean fields of x, by removing all arg_direct instances and
% all skippable fields
function x = clean_fields(x)
x(strcmp({x.first_name},'arg_direct') | [x.skippable]) = [];
try
children = {x.children};
empty_children = cellfun('isempty',children);
[x(~empty_children).children] = celldeal(cellfun(@clean_fields,children(~empty_children),'UniformOutput',false));
catch
end
|
github
|
ZijingMao/baselineeegtest-master
|
utl_match.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/utils/utl_match.m
| 3,245 |
utf_8
|
31c0021a79888d0261036c7eff8d1feb
|
function [r,dict] = utl_match(x,f,dict)
% Check whether an expression is matched by a pattern.
% [Equals,Assignment] = utl_match(Expression, Pattern, Assignment)
%
% The pattern may contain blanks, conditional expressions, and named sub-patterns.
% Assignment is an optional output which contains sub-expressions matched by named parts of the pattern.
% note: exp_symbol('x') and @x are considered non-equal by utl_match.
%
% See also:
% exp_match, utl_same
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-19
if isfield(f,{'head','parts'})
% f is a canonical expression (may be a pattern or a blank)
head = char(f.head);
if strcmp(head,'Pattern')
% f is a pattern: try to match its form
[r,dict] = utl_match(x,f.parts{2},dict);
if r
% we have a match for a named pattern
name = char(f.parts{1});
if name(1) == '@'
% normalize if it has a symbolic lambda name
name = name(28:end-21); end
% try to store the name-x relationship in the dictionary
[r,dict] = update_dict(dict,name,x);
end
elseif strcmp(head,'Blank') && (isempty(f.parts) || strcmp(char(get_function_symbol(f.parts{1})),char(exp_head(x))))
% we have a match for an unnamed pattern
r = 1;
elseif strcmp(head,'Condition')
% f is a condition expression: try to match its expression
[r,dict] = utl_match(x,f.parts{1},dict);
% then substitute the named sub-expressions into f's condition and evaluate that
r = r && exp_eval(utl_replacerepeated(f.parts{2},dict),inf);
else
% f is a non-pattern expression... match recursively
if isfield(x,'tracking') && isfield(x.tracking,'expression')
% normalize impure x
x = x.tracking.expression; end
if isfield(x,{'head','parts'})
% x has substructure: we have to match recursively
if ~isequal(x.head,f.head) || (length(x.parts) ~= length(f.parts))
r = false;
else
for k=1:length(x.parts)
[r,dict] = utl_match(x.parts{k},f.parts{k},dict);
if ~r
return; end
end
r = true;
end
else
% x has no substructure (but f has)
r = false;
end
end
elseif isfield(f,'tracking') && isfield(f.tracking,'expression')
% f is an impure expression; descend
[r,dict] = utl_match(x,f.tracking.expression,dict);
elseif isa(f,'function_handle') && isa(x,'function_handle')
% f an x are function handles: compare their string representations
r = strcmp(char(f),char(x));
else
% f is atomic; x must be identical
r = isequalwithequalnans(f,x);
end
% update the given dictionary with a name-value pair; also return whether the naming is still consistent
function [ok,dict] = update_dict(dict,name,val)
ok = true;
if isfield(dict,name)
if ~utl_same(dict.(name),val)
% mismatch!
ok = false;
return;
end
else
dict.(name) = val;
end
|
github
|
ZijingMao/baselineeegtest-master
|
arg_guidialog.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_guidialog.m
| 11,737 |
utf_8
|
37a7d0aadf53e47998dd759d4f19867c
|
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 : either a struct that is a valid input to the Function or the outputs of the function
% when Invoke is set to true (possibly multiple outputs)
%
% 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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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 iscell(s.range) % 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
|
ZijingMao/baselineeegtest-master
|
arg_define.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_define.m
| 32,685 |
utf_8
|
8d8bd4577decde884d4bcb63072bb9e1
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% --- 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
try
for k=1:2:length(vals)
assignin('caller',vals{k},vals{k+1}); end
catch e
if strcmp(e.identifier,'MATLAB:err_static_workspace_violation')
error('In a function with nested functions you need to capture the outputs of arg_define into a struct.');
else
rethrow(e);
end
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 = 'N/A';
end
if isempty(disallowed_nvp)
% the assumption was correct: 0 arguments are positional
fmt = 0;
else
% the assumption was violated: most likely k arguments are positional
% but check if at least one of the names in the first k arguments would have matched
% and warn if so
if iscellstr(nvps(1:2:end))
matching_nvp = intersect(nvps(1:2:min(end,max(fmt))),[joint_names {'arg_selection','arg_direct'}]);
if ~isempty(matching_nvp)
% if you get this warning you passed in a sequence of parameters to a function that uses
% arg_define and permits both 1) a number of positional arguments followed by name-value pairs
% or 2) alternatively all arguments passed in as name-value pairs. If your sequence is
% interpreted as all name-value pairs (case 2), a fraction of them are recognized as matching
% arguments (indicating that they are indeed NVPs), while another fraction of them are
% not recognized (indicating that the sequence is in fact consisting of some positional arguments).
% Therefore either the matching names are actually values that you passed in (and spuriously match),
% or you have a typo in one of your intended argument names, or perhaps the argument has been removed
% from the function.
caller = hlp_getcaller;
warn_once([caller ':arg_define:possible_conflict'],'arg_define() in %s: Possible parameter conflict -- both unrecognized names %s and matching names %s passed in. Assuming that the function is called with some positional arguments. This warning will not be repeated for this MATLAB session.',caller,hlp_tostring(disallowed_nvp),hlp_tostring(matching_nvp));
end
end
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
if iscell(disallowed_nvp)
% 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 function ' hlp_getcaller ': ' format_cellstr(disallowed_nvp) '.']);
else
% maybe the user intended to pass 0 positionals, but used some disallowed names
error(['Possibly the argument order was confused when calling ' hlp_getcaller ': ' hlp_tostring(vals,20) '.']);
end
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});
newvalue = nvps{k+1};
if spec(idx).deprecated && ~isequal_weak(spec(idx).value,newvalue)
if ~isempty(spec(idx).help)
disp_once(['Using deprecated argument "' nvps{k} '" in function ' hlp_getcaller ' (help: ' [spec(idx).help{:}] ').']);
else
disp_once(['Using deprecated argument "' nvps{k} '" in function ' hlp_getcaller '.']);
end
end
spec(idx) = spec(idx).assigner(spec(idx),newvalue);
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
try
for fn=fieldnames(res)'
assignin('caller',fn{1},res.(fn{1})); end
catch e
if strcmp(e.identifier,'MATLAB:err_static_workspace_violation')
error('In a function with nested functions you need to capture the outputs of arg_define into a struct.');
else
rethrow(e);
end
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
|
ZijingMao/baselineeegtest-master
|
invoke_arg_internal.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/invoke_arg_internal.m
| 5,224 |
utf_8
|
2784cfbfe50f9ab2d84cdd3e0fa13f95
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
arg_report.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_report.m
| 7,719 |
utf_8
|
8c31f7700b53f8cc14f0f913ba6aaf20
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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' hlp_getresult(5,@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
res = {};
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
|
ZijingMao/baselineeegtest-master
|
arg_subswitch.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_subswitch.m
| 18,030 |
utf_8
|
2b99bc728471da69b824b4c58fbcdcd3
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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 isempty(selection)
error(['The chosen selector argument (empty) does not match any of the possible options (' sprintf('%s, ',selectors{1:end-1}) selectors{end} ') in the function argument ' names{1} '.']);
elseif ~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
|
ZijingMao/baselineeegtest-master
|
arg_sub.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_sub.m
| 12,903 |
utf_8
|
d2d222baf398ec763c607d5b9168fd97
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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
|
ZijingMao/baselineeegtest-master
|
arg_subtoggle.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_subtoggle.m
| 16,104 |
utf_8
|
7e89df9d3f60a509a08809550a8266e1
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
% 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
|
ZijingMao/baselineeegtest-master
|
arg_guipanel.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_guipanel.m
| 4,253 |
utf_8
|
f1f39d58a10b31916e58237bd50d0811
|
function result = arg_guipanel(varargin)
% Create a uipanel that displays an argument property inspector for a Function.
% Result = arg_guipanel(Options ...)
% Result = arg_guipanel(Parent, Options ...)
%
% The handle supports the method .GetPropertySpecification(), by means of which the edited argument
% specification can be retrieved. This result can be turned into a valid Function argument using
% arg_tovals(). Additional Parameters may be passed to the Function, in order to override some of
% its defaults.
%
% In:
% Parent : optional parent widget
%
% Options : name-value pairs; possible names are:
% 'Function' : the function for which to display arguments
%
% 'Parameters' : cell array of parameters to the function
%
% 'Position' : position of the panel within the parent widget
%
% 'PanelOnly' : if true, generate only a uipanel that can be embedded in a dialog;
% otherwise generate a figure and wait until it is closed.
% (default: true)
%
% Out:
% Result : * if PanelOnly, this is the handle to the panel; supports .GetPropertySpecification()
% to obain the edited specification (when done)
% * otherwise this is the PropertySpecification of the function at the time when the
% figure is closed
%
% Examples:
% % get a uipanel that allows to edit parameters to a function
% f = figure;
% h = arg_guipanel(f,'Function',@myfunction);
%
% % get a uipanel that allows to edit parameters to a function, and customize initial settings
% f = figure;
% h = arg_guipanel(f,'Function',@myfunction,'Parameters',{3,21,'test'});
%
% % get a uipanel that allows to edit parameters to a function, and put it in a specific position
% f = figure;
% h = arg_guipanel(f,'Function',@myfunction,'Position',[0 0 100 200]);
%
% See also:
% arg_guidialog, arg_guidialog_ex, arg_define
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-10-24
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
global tracking;
if ~isfield(tracking,'gui') || ~isfield(tracking.gui,'show_guru')
tracking.gui.show_guru = true; end
% separate the parent, if specified
if isscalar(varargin{1}) && ishandle(varargin{1})
parent = varargin{1};
varargin = varargin(2:end);
else
mp = get(0,'MonitorPositions')';
parent = figure('MenuBar','none','Position',[mp(3)/2-200,mp(4)/2-200,400,400]);
end
% get the options
opts = hlp_varargin2struct(varargin, {'Function','function','func'},mandatory, {'Parameters','parameters','params'},{}, {'Position','position','pos'},[0 0 1 1],{'PanelOnly','panel_only'},true);
% obtain the argument specification for the function
spec = arg_report('rich', opts.Function, opts.Parameters);
% ... and turn it into an array of PropertyGridField's
properties = PropertyGridField.GenerateFrom(spec);
% instantiate the grid
args = hlp_struct2varargin(opts,'suppress',{'Function','Parameters','PanelOnly'});
hpanel = PropertyGrid(parent,args{:},'Properties',properties,'ShowExpert',tracking.gui.show_guru);
if ~opts.PanelOnly
% in this case a figure is generated and we wait until the figure is closed
set(hpanel.Parent,'CloseRequestFcn',@(hfig,v)extract_properties(hfig));
uiwait(hpanel.Parent);
else
result = hpanel;
end
function extract_properties(hfig)
result = arg_tovals(hpanel.GetPropertySpecification);
delete(hfig);
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
arg_tovals.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_tovals.m
| 3,298 |
utf_8
|
4c53983211063113b2ef46011720a192
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
|
ZijingMao/baselineeegtest-master
|
arg_specifier.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/arguments/arg_specifier.m
| 3,766 |
utf_8
|
d9f9eaf9bd9514675f5ba5e7832bf577
|
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
% Copyright (C) Christian Kothe, SCCN, 2010, [email protected]
%
% 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
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
'displayable',{true},...% whether the argument may be displayed by GUIs (true/false)
'deprecated',{false},...% whether the argument has been deprecated (true/false)
'experimental',{false},...% whether the argument is marked as experimental or "prototype-stage" (true/false)
'guru',{false},... % whether the argument is marked as guru-level (true/false)
'reportable',{true},... % whether the argument can be reported to outer function (given that it is assigned), or not (true/false)
'to_double',{true} ... % convert numeric values to double before returning them to the function
);
% 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
|
ZijingMao/baselineeegtest-master
|
is_needing_search.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/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
|
ZijingMao/baselineeegtest-master
|
is_raw_dataset.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/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
|
ZijingMao/baselineeegtest-master
|
asr_process.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/ASR/asr_process.m
| 10,842 |
utf_8
|
2b9444373fa0587a1378382eea5850ec
|
function [outdata,outstate] = asr_process(data,srate,state,windowlen,lookahead,stepsize,maxdims,maxmem,usegpu)
% Processing function for the Artifact Subspace Reconstruction (ASR) method.
% [Data,State] = asr_process(Data,SamplingRate,State,WindowLength,LookAhead,StepSize,MaxDimensions,MaxMemory,UseGPU)
%
% This function is used to clean multi-channel signal using the ASR method. The required inputs are
% the data matrix, the sampling rate of the data, and the filter state (as initialized by
% asr_calibrate). If the data is used on successive chunks of data, the output state of the previous
% call to asr_process should be passed in.
%
% In:
% Data : Chunk of data to process [#channels x #samples]. This is a chunk of data, assumed to be
% a continuation of the data that was passed in during the last call to asr_process (if
% any). The data should be *zero-mean* (e.g., high-pass filtered the same way as for
% asr_calibrate).
%
% SamplingRate : sampling rate of the data in Hz (e.g., 250.0)
%
% State : initial filter state (determined by asr_calibrate or from previous call to asr_process)
%
% WindowLength : Length of the statistcs window, in seconds (e.g., 0.5). This should not be much
% longer than the time scale over which artifacts persist, but the number of samples
% in the window should not be smaller than 1.5x the number of channels. Default: 0.5
%
% LookAhead : Amount of look-ahead that the algorithm should use. Since the processing is causal,
% the output signal will be delayed by this amount. This value is in seconds and should
% be between 0 (no lookahead) and WindowLength/2 (optimal lookahead). The recommended
% value is WindowLength/2. Default: WindowLength/2
%
% StepSize : The statistics will be updated every this many samples. The larger this is, the faster
% the algorithm will be. The value must not be larger than WindowLength*SamplingRate.
% The minimum value is 1 (update for every sample) while a good value is 1/3 of a second.
% Note that an update is always performed also on the first and last sample of the data
% chunk. Default: 32
%
% MaxDimensions : Maximum dimensionality of artifacts to remove. Up to this many dimensions (or up
% to this fraction of dimensions) can be removed for a given data segment. If the
% algorithm needs to tolerate extreme artifacts a higher value than the default
% may be used (the maximum fraction is 1.0). Default 0.66
%
% MaxMemory : The maximum amount of memory used by the algorithm when processing a long chunk with
% many channels, in MB. The recommended value is at least 256. To run on the GPU, use
% the amount of memory available to your GPU here (needs the parallel computing toolbox).
% default: min(5000,1/2 * free memory in MB). Using smaller amounts of memory leads to
% longer running times.
%
% UseGPU : Whether to run on the GPU. This makes sense for offline processing if you have a a card
% with enough memory and good double-precision performance (e.g., NVIDIA GTX Titan or
% K20). Note that for this to work you need to have the Parallel Computing toolbox.
% Default: false
%
% Out:
% Data : cleaned data chunk (same length as input but delayed by LookAhead samples)
%
% State : final filter state (can be passed in for subsequent calls)
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-08-31
% UC Copyright Notice
% This software is Copyright (C) 2013 The Regents of the University of California. All Rights Reserved.
%
% Permission to copy, modify, and distribute this software and its documentation for educational,
% research and non-profit purposes, without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the following three paragraphs appear
% in all copies.
%
% Permission to make commercial use of this software may be obtained by contacting:
% Technology Transfer Office
% 9500 Gilman Drive, Mail Code 0910
% University of California
% La Jolla, CA 92093-0910
% (858) 534-5815
% [email protected]
%
% This software program and documentation are copyrighted by The Regents of the University of
% California. The software program and documentation are supplied "as is", without any accompanying
% services from The Regents. The Regents does not warrant that the operation of the program will be
% uninterrupted or error-free. The end-user understands that the program was developed for research
% purposes and is advised not to rely exclusively on the program for any reason.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
% SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
% THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
% CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
% MODIFICATIONS.
if nargin < 4 || isempty(windowlen)
windowlen = 0.5; end
windowlen = max(windowlen,1.5*size(data,1)/srate);
if nargin < 5 || isempty(lookahead)
lookahead = windowlen/2; end
if nargin < 6 || isempty(stepsize)
stepsize = 32; end
if nargin < 7 || isempty(maxdims)
maxdims = 0.66; end
if nargin < 9 || isempty(usegpu)
usegpu = false; end
if nargin < 8 || isempty(maxmem)
if usegpu
dev = gpuDevice(); maxmem = dev.FreeMemory/2^20;
else
maxmem = hlp_memfree/(2^21);
end
end
if maxdims < 1
maxdims = round(size(data,1)*maxdims); end
if isempty(data)
outdata = data; outstate = state; return; end
[C,S] = size(data);
N = round(windowlen*srate);
P = round(lookahead*srate);
[T,M,A,B] = deal(state.T,state.M,state.A,state.B);
% initialize prior filter state by extrapolating available data into the past (if necessary)
if isempty(state.carry)
state.carry = repmat(2*data(:,1),1,P) - data(:,1+mod(((P+1):-1:2)-1,S)); end
data = [state.carry data];
data(~isfinite(data(:))) = 0;
% split up the total sample range into k chunks that will fit in memory
splits = ceil((C*C*S*8*8 + C*C*8*S/stepsize + C*S*8*2 + S*8*5) / (maxmem*1024*1024 - C*C*P*8*3));
if splits > 1
fprintf('Now cleaning data in %i blocks',splits); end
for i=1:splits
range = 1+floor((i-1)*S/splits) : min(S,floor(i*S/splits));
if ~isempty(range)
% get spectrally shaped data X for statistics computation (range shifted by lookahead)
[X,state.iir] = filter(B,A,double(data(:,range+P)),state.iir,2);
% move it to the GPU if applicable
if usegpu && length(range) > 1000
try X = gpuArray(X); catch,end; end
% compute running mean covariance (assuming a zero-mean signal)
[Xcov,state.cov] = moving_average(N,reshape(bsxfun(@times,reshape(X,1,C,[]),reshape(X,C,1,[])),C*C,[]),state.cov);
% extract the subset of time points at which we intend to update
update_at = min(stepsize:stepsize:(size(Xcov,2)+stepsize-1),size(Xcov,2));
% if there is no previous R (from the end of the last chunk), we estimate it right at the first sample
if isempty(state.last_R)
update_at = [1 update_at];
state.last_R = eye(C);
end
Xcov = reshape(Xcov(:,update_at),C,C,[]);
if usegpu
Xcov = gather(Xcov); end
% do the reconstruction in intervals of length stepsize (or shorter if at the end of a chunk)
last_n = 0;
for j=1:length(update_at)
% do a PCA to find potential artifact components
[V,D] = eig(Xcov(:,:,j));
[D,order] = sort(reshape(diag(D),1,C)); V = V(:,order);
% determine which components to keep (variance below directional threshold or not admissible for rejection)
keep = D<sum((T*V).^2) | (1:C)<(C-maxdims);
trivial = all(keep);
% update the reconstruction matrix R (reconstruct artifact components using the mixing matrix)
if ~trivial
R = real(M*pinv(bsxfun(@times,keep',V'*M))*V');
else
R = eye(C);
end
% apply the reconstruction to intermediate samples (using raised-cosine blending)
n = update_at(j);
if ~trivial || ~state.last_trivial
subrange = range((last_n+1):n);
blend = (1-cos(pi*(1:(n-last_n))/(n-last_n)))/2;
data(:,subrange) = bsxfun(@times,blend,R*data(:,subrange)) + bsxfun(@times,1-blend,state.last_R*data(:,subrange));
end
[last_n,state.last_R,state.last_trivial] = deal(n,R,trivial);
end
end
if splits > 1
fprintf('.'); end
end
if splits > 1
fprintf('\n'); end
% carry the look-ahead portion of the data over to the state (for successive calls)
state.carry = [state.carry data(:,(end-P+1):end)];
state.carry = state.carry(:,(end-P+1):end);
% finalize outputs
outdata = data(:,1:(end-P));
if usegpu
state.iir = gather(state.iir);
state.cov = gather(state.cov);
end
outstate = state;
function [X,Zf] = moving_average(N,X,Zi)
% Run a moving-average filter along the second dimension of the data.
% [X,Zf] = moving_average(N,X,Zi)
%
% In:
% N : filter length in samples
% X : data matrix [#Channels x #Samples]
% Zi : initial filter conditions (default: [])
%
% Out:
% X : the filtered data
% Zf : final filter conditions
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-01-10
if nargin <= 2 || isempty(Zi)
Zi = zeros(size(X,1),N); end
% pre-pend initial state & get dimensions
Y = [Zi X]; M = size(Y,2);
% get alternating index vector (for additions & subtractions)
I = [1:M-N; 1+N:M];
% get sign vector (also alternating, and includes the scaling)
S = [-ones(1,M-N); ones(1,M-N)]/N;
% run moving average
X = cumsum(bsxfun(@times,Y(:,I(:)),S(:)'),2);
% read out result
X = X(:,2:2:end);
if nargout > 1
Zf = [-(X(:,end)*N-Y(:,end-N+1)) Y(:,end-N+2:end)]; end
function result = hlp_memfree
% Get the amount of free physical memory, in bytes
result = java.lang.management.ManagementFactory.getOperatingSystemMXBean().getFreePhysicalMemorySize();
|
github
|
ZijingMao/baselineeegtest-master
|
asr_calibrate.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/ASR/asr_calibrate.m
| 20,719 |
utf_8
|
8fae81e23ca90db07857571dd5142fbb
|
function state = asr_calibrate(X,srate,cutoff,blocksize,B,A,window_len,window_overlap,max_dropout_fraction,min_clean_fraction)
% Calibration function for the Artifact Subspace Reconstruction (ASR) method.
% State = asr_calibrate(Data,SamplingRate,Cutoff,BlockSize,FilterB,FilterA,WindowLength,WindowOverlap,MaxDropoutFraction,MinCleanFraction)
%
% The input to this data is a multi-channel time series of calibration data. In typical uses the
% calibration data is clean resting EEG data of ca. 1 minute duration (can also be longer). One can
% also use on-task data if the fraction of artifact content is below the breakdown point of the
% robust statistics used for estimation (50% theoretical, ~30% practical). If the data has a
% proportion of more than 30-50% artifacts then bad time windows should be removed beforehand. This
% data is used to estimate the thresholds that are used by the ASR processing function to identify
% and remove artifact components.
%
% The calibration data must have been recorded for the same cap design from which data for cleanup
% will be recorded, and ideally should be from the same session and same subject, but it is possible
% to reuse the calibration data from a previous session and montage to the extent that the cap is
% placed in the same location (where loss in accuracy is more or less proportional to the mismatch
% in cap placement).
%
% The calibration data should have been high-pass filtered (for example at 0.5Hz or 1Hz using a
% Butterworth IIR filter).
%
% In:
% Data : Calibration data [#channels x #samples]; *zero-mean* (e.g., high-pass filtered) and
% reasonably clean EEG of not much less than 30 seconds length (this method is typically
% used with 1 minute or more).
%
% SamplingRate : Sampling rate of the data, in Hz.
%
%
% The following are optional parameters (the key parameter of the method is the RejectionCutoff):
%
% RejectionCutoff: Standard deviation cutoff for rejection. Data portions whose variance is larger
% than this threshold relative to the calibration data are considered missing
% data and will be removed. The most aggressive value that can be used without
% losing too much EEG is 2.5. A quite conservative value would be 5. Default: 5.
%
% Blocksize : Block size for calculating the robust data covariance and thresholds, in samples;
% allows to reduce the memory and time requirements of the robust estimators by this
% factor (down to Channels x Channels x Samples x 16 / Blocksize bytes). Default: 10
%
% FilterB, FilterA : Coefficients of an IIR filter that is used to shape the spectrum of the signal
% when calculating artifact statistics. The output signal does not go through
% this filter. This is an optional way to tune the sensitivity of the algorithm
% to each frequency component of the signal. The default filter is less
% sensitive at alpha and beta frequencies and more sensitive at delta (blinks)
% and gamma (muscle) frequencies. Default:
% [b,a] = yulewalk(8,[[0 2 3 13 16 40 min(80,srate/2-1)]*2/srate 1],[3 0.75 0.33 0.33 1 1 3 3]);
%
% WindowLength : Window length that is used to check the data for artifact content. This is
% ideally as long as the expected time scale of the artifacts but short enough to
% allow for several 1000 windows to compute statistics over. Default: 0.5.
%
% WindowOverlap : Window overlap fraction. The fraction of two successive windows that overlaps.
% Higher overlap ensures that fewer artifact portions are going to be missed (but
% is slower). Default: 0.66
%
% MaxDropoutFraction : Maximum fraction of windows that can be subject to signal dropouts
% (e.g., sensor unplugged), used for threshold estimation. Default: 0.1
%
% MinCleanFraction : Minimum fraction of windows that need to be clean, used for threshold
% estimation. Default: 0.25
%
%
% Out:
% State : initial state struct for asr_process
%
% Notes:
% This can run on a GPU with large memory and good double-precision performance for faster processing
% (e.g., on an NVIDIA GTX Titan or K20), but requires that the Parallel Computing toolbox is
% installed.
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-08-31
% asr_calibrate_version<1.03> -- for the cache
% UC Copyright Notice
% This software is Copyright (C) 2013 The Regents of the University of California. All Rights Reserved.
%
% Permission to copy, modify, and distribute this software and its documentation for educational,
% research and non-profit purposes, without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the following three paragraphs appear
% in all copies.
%
% Permission to make commercial use of this software may be obtained by contacting:
% Technology Transfer Office
% 9500 Gilman Drive, Mail Code 0910
% University of California
% La Jolla, CA 92093-0910
% (858) 534-5815
% [email protected]
%
% This software program and documentation are copyrighted by The Regents of the University of
% California. The software program and documentation are supplied "as is", without any accompanying
% services from The Regents. The Regents does not warrant that the operation of the program will be
% uninterrupted or error-free. The end-user understands that the program was developed for research
% purposes and is advised not to rely exclusively on the program for any reason.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
% SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
% THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
% INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
% CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
% MODIFICATIONS.
[C,S] = size(X);
if nargin < 3 || isempty(cutoff)
cutoff = 5; end
if nargin < 4 || isempty(blocksize)
blocksize = 10; end
blocksize = max(blocksize,ceil((C*C*S*8*3*2)/hlp_memfree));
if nargin < 6 || isempty(A) || isempty(B)
try
% try to use yulewalk to design the filter (Signal Processing toolbox required)
[B,A] = yulewalk(8,[[0 2 3 13 16 40 min(80,srate/2-1)]*2/srate 1],[3 0.75 0.33 0.33 1 1 3 3]);
catch e %#ok<NASGU>
% yulewalk not available (maybe no toolbox installed) -- use precomputed filter
% coefficients depending on sampling rate
switch srate
case 100
[B,A] = deal([0.9314233528641650 -1.0023683814963549 -0.4125359862018213 0.7631567476327510 0.4160430392910331 -0.6549131038692215 -0.0372583518046807 0.1916268458752655 0.0462411971592346],[1.0000000000000000 -0.4544220180303844 -1.0007038682936749 0.5374925521337940 0.4905013360991340 -0.4861062879351137 -0.1995986490699414 0.1830048420730026 0.0457678549234644]);
case 128
[B,A] = deal([1.1027301639165037 -2.0025621813611867 0.8942119516481342 0.1549979524226999 0.0192366904488084 0.1782897770278735 -0.5280306696498717 0.2913540603407520 -0.0262209802526358],[1.0000000000000000 -1.1042042046423233 -0.3319558528606542 0.5802946221107337 -0.0010360013915635 0.0382167091925086 -0.2609928034425362 0.0298719057761086 0.0935044692959187]);
case 200
[B,A] = deal([1.4489483325802353 -2.6692514764802775 2.0813970620731115 -0.9736678877049534 0.1054605060352928 -0.1889101692314626 0.6111331636592364 -0.3616483013075088 0.1834313060776763],[1.0000000000000000 -0.9913236099393967 0.3159563145469344 -0.0708347481677557 -0.0558793822071149 -0.2539619026478943 0.2473056615251193 -0.0420478437473110 0.0077455718334464]);
case 256
[B,A] = deal([1.7587013141770287 -4.3267624394458641 5.7999880031015953 -6.2396625463547508 5.3768079046882207 -3.7938218893374835 2.1649108095226470 -0.8591392569863763 0.2569361125627988],[1.0000000000000000 -1.7008039639301735 1.9232830391058724 -2.0826929726929797 1.5982638742557307 -1.0735854183930011 0.5679719225652651 -0.1886181499768189 0.0572954115997261]);
case 300
[B,A] = deal([1.9153920676433143 -5.7748421104926795 9.1864764859103936 -10.7350356619363630 9.6423672437729007 -6.6181939699544277 3.4219421494177711 -1.2622976569994351 0.2968423019363821],[1.0000000000000000 -2.3143703322055491 3.2222567327379434 -3.6030527704320621 2.9645154844073698 -1.8842615840684735 0.9222455868758080 -0.3103251703648485 0.0634586449896364]);
case 500
[B,A] = deal([2.3133520086975823 -11.9471223009159130 29.1067166493384340 -43.7550171007238190 44.3385767452216370 -30.9965523846388000 14.6209883020737190 -4.2743412400311449 0.5982553583777899],[1.0000000000000000 -4.6893329084452580 10.5989986701080210 -14.9691518101365230 14.3320358399731820 -9.4924317069169977 4.2425899618982656 -1.1715600975178280 0.1538048427717476]);
case 512
[B,A] = deal([2.3275475636130865 -12.2166478485960430 30.1632789058248850 -45.8009842020820410 46.7261263011068880 -32.7796858196767220 15.4623349612560630 -4.5019779685307473 0.6242733481676324],[1.0000000000000000 -4.7827378944258703 10.9780696236622980 -15.6795187888195360 15.1281978667576310 -10.0632079834518220 4.5014690636505614 -1.2394100873286753 0.1614727510688058]);
otherwise
error('repair_bursts:NoYulewalk','The yulewalk() function was not found and there is no pre-computed spectral filter for your sampling rate. If you would like to use the default spectral filter please try to resample to one of the supported rates (100,128,200,256,300,500,512) or get the appropriate toobox license (you can also disable the spectral weighting feature or supply your own precalculated IIR filter coefficients).');
end
end
end
if nargin < 8 || isempty(window_len)
window_len = 0.5; end
if nargin < 9 || isempty(window_overlap)
window_overlap = 0.66; end
if nargin < 10 || isempty(max_dropout_fraction)
max_dropout_fraction = 0.1; end
if nargin < 11 || isempty(min_clean_fraction)
min_clean_fraction = 0.25; end
X(~isfinite(X(:))) = 0;
% apply the signal shaping filter and initialize the IIR filter state
[X,iirstate] = filter(B,A,double(X),[],2); X = X';
if any(~isfinite(X(:)))
error('The IIR filter diverged on your data. Please try using either a more conservative filter or removing some bad sections/channels from the calibration data.'); end
% calculate the sample covariance matrices U (averaged in blocks of blocksize successive samples)
U = zeros(length(1:blocksize:S),C*C);
for k=1:blocksize
range = min(S,k:blocksize:(S+k-1));
U = U + reshape(bsxfun(@times,reshape(X(range,:),[],1,C),reshape(X(range,:),[],C,1)),size(U));
end
% get the mixing matrix M
M = sqrtm(real(reshape(block_geometric_median(U/blocksize),C,C)));
% window length for calculating thresholds
N = round(window_len*srate);
% get the threshold matrix T
fprintf('Determining per-component thresholds...');
[V,D] = eig(M); %#ok<NASGU>
X = abs(X*V);
for c = C:-1:1
% compute RMS amplitude for each window...
rms = X(:,c).^2;
rms = sqrt(sum(rms(bsxfun(@plus,round(1:N*(1-window_overlap):S-N),(0:N-1)')))/N);
% fit a distribution to the clean part
[mu(c),sig(c)] = fit_eeg_distribution(rms,min_clean_fraction,max_dropout_fraction);
end
T = diag(mu + cutoff*sig)*V';
disp('done.');
% initialize the remaining filter state
state = struct('M',M,'T',T,'B',B,'A',A,'cov',[],'carry',[],'iir',iirstate,'last_R',[],'last_trivial',true);
function y = block_geometric_median(X,blocksize,varargin)
% Calculate a blockwise geometric median (faster and less memory-intensive
% than the regular geom_median function).
%
% This statistic is not robust to artifacts that persist over a duration that
% is significantly shorter than the blocksize.
%
% In:
% X : the data (#observations x #variables)
% blocksize : the number of successive samples over which a regular mean
% should be taken
% tol : tolerance (default: 1.e-5)
% y : initial value (default: median(X))
% max_iter : max number of iterations (default: 500)
%
% Out:
% g : geometric median over X
%
% Notes:
% This function is noticably faster if the length of the data is divisible by the block size.
% Uses the GPU if available.
%
if nargin < 2 || isempty(blocksize)
blocksize = 1; end
if blocksize > 1
[o,v] = size(X); % #observations & #variables
r = mod(o,blocksize); % #rest in last block
b = (o-r)/blocksize; % #blocks
if r > 0
X = [reshape(sum(reshape(X(1:(o-r),:),blocksize,b*v)),b,v); sum(X((o-r+1):end,:))*(blocksize/r)];
else
X = reshape(sum(reshape(X,blocksize,b*v)),b,v);
end
end
try
y = gather(geometric_median(gpuArray(X),varargin{:}))/blocksize;
catch
y = geometric_median(X,varargin{:})/blocksize;
end
function y = geometric_median(X,tol,y,max_iter)
% Calculate the geometric median for a set of observations (mean under a Laplacian noise distribution)
% This is using Weiszfeld's algorithm.
%
% In:
% X : the data, as in mean
% tol : tolerance (default: 1.e-5)
% y : initial value (default: median(X))
% max_iter : max number of iterations (default: 500)
%
% Out:
% g : geometric median over X
if ~exist('tol','var') || isempty(tol)
tol = 1.e-5; end
if ~exist('y','var') || isempty(y)
y = median(X); end
if ~exist('max_iter','var') || isempty(max_iter)
max_iter = 500; end
for i=1:max_iter
invnorms = 1./sqrt(sum(bsxfun(@minus,X,y).^2,2));
[y,oldy] = deal(sum(bsxfun(@times,X,invnorms)) / sum(invnorms),y);
if norm(y-oldy)/norm(y) < tol
break; end
end
function result = hlp_memfree
% Get the amount of free physical memory, in bytes
result = java.lang.management.ManagementFactory.getOperatingSystemMXBean().getFreePhysicalMemorySize();
function [mu,sig,alpha,beta] = fit_eeg_distribution(X,min_clean_fraction,max_dropout_fraction,quants,step_sizes,beta)
% Estimate the mean and standard deviation of clean EEG from contaminated data.
% [Mu,Sigma,Alpha,Beta] = fit_eeg_distribution(X,MinCleanFraction,MaxDropoutFraction,FitQuantiles,StepSizes,ShapeRange)
%
% This function estimates the mean and standard deviation of clean EEG from a sample of amplitude
% values (that have preferably been computed over short windows) that may include a large fraction
% of contaminated samples. The clean EEG is assumed to represent a generalized Gaussian component in
% a mixture with near-arbitrary artifact components. By default, at least 25% (MinCleanFraction) of
% the data must be clean EEG, and the rest can be contaminated. No more than 10%
% (MaxDropoutFraction) of the data is allowed to come from contaminations that cause lower-than-EEG
% amplitudes (e.g., sensor unplugged). There are no restrictions on artifacts causing
% larger-than-EEG amplitudes, i.e., virtually anything is handled (with the exception of a very
% unlikely type of distribution that combines with the clean EEG samples into a larger symmetric
% generalized Gaussian peak and thereby "fools" the estimator). The default parameters should be
% fine for a wide range of settings but may be adapted to accomodate special circumstances.
%
% The method works by fitting a truncated generalized Gaussian whose parameters are constrained by
% MinCleanFraction, MaxDropoutFraction, FitQuantiles, and ShapeRange. The alpha and beta parameters
% of the gen. Gaussian are also returned. The fit is performed by a grid search that always finds a
% close-to-optimal solution if the above assumptions are fulfilled.
%
% In:
% X : vector of amplitude values of EEG, possible containing artifacts
% (coming from single samples or windowed averages)
%
% MinCleanFraction : Minimum fraction of values in X that needs to be clean
% (default: 0.25)
%
% MaxDropoutFraction : Maximum fraction of values in X that can be subject to
% signal dropouts (e.g., sensor unplugged) (default: 0.1)
%
% FitQuantiles : Quantile range [lower,upper] of the truncated generalized Gaussian distribution
% that shall be fit to the EEG contents (default: [0.022 0.6])
%
% StepSizes : Step size of the grid search; the first value is the stepping of the lower bound
% (which essentially steps over any dropout samples), and the second value
% is the stepping over possible scales (i.e., clean-data quantiles)
% (default: [0.01 0.01])
%
% ShapeRange : Range that the clean EEG distribution's shape parameter beta may take (default:
% 1.7:0.15:3.5)
%
% Out:
% Mu : estimated mean of the clean EEG distribution
%
% Sigma : estimated standard deviation of the clean EEG distribution
%
% Alpha : estimated scale parameter of the generalized Gaussian clean EEG distribution (optional)
%
% Beta : estimated shape parameter of the generalized Gaussian clean EEG distribution (optional)
% assign defaults
if ~exist('min_clean_fraction','var') || isempty(min_clean_fraction)
min_clean_fraction = 0.25; end
if ~exist('max_dropout_fraction','var') || isempty(max_dropout_fraction)
max_dropout_fraction = 0.1; end
if ~exist('quants','var') || isempty(quants)
quants = [0.022 0.6]; end
if ~exist('step_sizes','var') || isempty(step_sizes)
step_sizes = [0.01 0.01]; end
if ~exist('beta','var') || isempty(beta)
beta = 1.7:0.15:3.5; end
% sanity checks
if ~isvector(quants) || numel(quants) > 2
error('Fit quantiles needs to be a 2-element vector (support for matrices deprecated).'); end
if any(quants(:)<0) || any(quants(:)>1)
error('Unreasonable fit quantiles.'); end
if any(step_sizes<0.0001) || any(step_sizes>0.1)
error('Unreasonable step sizes.'); end
if any(beta>=7) || any(beta<=1)
error('Unreasonable shape range.'); end
% sort data so we can access quantiles directly
X = double(sort(X(:)));
n = length(X);
% calc z bounds for the truncated standard generalized Gaussian pdf and pdf rescaler
for b=1:length(beta)
zbounds{b} = sign(quants-1/2).*gammaincinv(sign(quants-1/2).*(2*quants-1),1/beta(b)).^(1/beta(b)); %#ok<*AGROW>
rescale(b) = beta(b)/(2*gamma(1/beta(b)));
end
% determine the quantile-dependent limits for the grid search
lower_min = min(quants); % we can generally skip the tail below the lower quantile
max_width = diff(quants); % maximum width is the fit interval if all data is clean
min_width = min_clean_fraction*max_width; % minimum width of the fit interval, as fraction of data
% get matrix of shifted data ranges
X = X(bsxfun(@plus,(1:round(n*max_width))',round(n*(lower_min:step_sizes(1):lower_min+max_dropout_fraction))));
X1 = X(1,:); X = bsxfun(@minus,X,X1);
opt_val = Inf;
% for each interval width...
for m = round(n*(max_width:-step_sizes(2):min_width))
% scale and bin the data in the intervals
nbins = round(3*log2(1+m/2));
H = bsxfun(@times,X(1:m,:),nbins./X(m,:));
logq = log(histc(H,[0:nbins-1,Inf]) + 0.01);
% for each shape value...
for b=1:length(beta)
bounds = zbounds{b};
% evaluate truncated generalized Gaussian pdf at bin centers
x = bounds(1)+(0.5:(nbins-0.5))/nbins*diff(bounds);
p = exp(-abs(x).^beta(b))*rescale(b); p=p'/sum(p);
% calc KL divergences
kl = sum(bsxfun(@times,p,bsxfun(@minus,log(p),logq(1:end-1,:)))) + log(m);
% update optimal parameters
[min_val,idx] = min(kl);
if min_val < opt_val
opt_val = min_val;
opt_beta = beta(b);
opt_bounds = bounds;
opt_lu = [X1(idx) X1(idx)+X(m,idx)];
end
end
end
% recover distribution parameters at optimum
alpha = (opt_lu(2)-opt_lu(1))/diff(opt_bounds);
mu = opt_lu(1)-opt_bounds(1)*alpha;
beta = opt_beta;
% calculate the distribution's standard deviation from alpha and beta
sig = sqrt((alpha^2)*gamma(3/beta)/gamma(1/beta));
|
github
|
ZijingMao/baselineeegtest-master
|
set_merge.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_merge.m
| 1,974 |
utf_8
|
755faf243ef5fb29eb8933010d7985cd
|
function [data,idxmap] = set_merge(varargin)
% Merge epoched EEGLAB data sets across trials or time in a fault-tolerant way.
% [Merged,IndexMap] = set_merge(Set-#1, Set-#2, ...)
%
% In:
% Set-#k : data set #k
%
% Out:
% Merged : The merged epoched data set
%
% IndexMap : a mapping from trial index (in the merged set), to data set index
% (in the list of sets supplied)
%
% Notes:
% This function merges data sets either across trials (if epoched) or across time (if continuous)
% in a manner that supports inconsistent meta-data. For data that is known to be consistent, use
% set_joinepos or set_concat, which are much faster.
%
% Examples:
% % merge data sets eegA, eegB and eegC across trials
% eeg = set_merge(eegA,eegB,eegC)
%
% See also:
% set_concat, set_joinepos
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-03-31
% set_merge_version<1.0> -- for the cache
if ~exp_beginfun('editing') return; end
declare_properties('name','MergeSets','independent_channels',true,'independent_trials',true);
idxmap = {};
data = {};
if ~isempty(varargin)
% identify non-empty sets & create the index map
for i=1:length(varargin)
if isfield(varargin{i},'data')
data{end+1} = varargin{i}; %#ok<AGROW>
idxmap{end+1} = i*ones(1,size(varargin{i}.data,3)); %#ok<AGROW>
end
end
% do the merging
data = merge(data{:});
idxmap = [idxmap{:}];
end
exp_endfun;
% merge recursively to avoid growing big arrays incrementally
function X = merge(varargin)
if nargin > 1
A = merge(varargin{1:floor(nargin/2)});
B = merge(varargin{(floor(nargin/2)+1):end});
try
X = pop_mergeset(A,B);
catch err
disp(['The two data sets ' hlp_tostring(A) ' and ' hlp_tostring(B) ' cannot be merged; reason:']);
rethrow(err);
end
else
X = varargin{1};
end
|
github
|
ZijingMao/baselineeegtest-master
|
set_gettarget.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_gettarget.m
| 4,587 |
utf_8
|
cc8abafa68a3a656c951cd1a88a51321
|
function targ = set_gettarget(signal)
% Generic function to extract the target values from a data set (epoched/continuous).
% Target = set_gettarget(Signal)
%
% Data sets may have associated "target values" in their meta-data (usually one per epoch and/or per
% event). These target values encode what outputs a cognitive monitoring system is supposed to
% output at the given epoch/marker time point/etc. These meta-data are the primary means in which
% the relationship between raw data and cognitive state is specified.
%
% If an epoched data set is passed, the .target field of the epochs will be used. If a continuous
% data set is passed which has events with a non-empty .target field, the target values of those
% events will be returned. Otherwise, if the signal has channels with a .type field that is set to
% 'target', the time course of these channels will be returned. Otherwise, the signal has no associated
% target values and this function will throw an error.
%
% In:
% Signal : EEGLAB data set, either epoched or continuous
%
% Out:
% Target : Array target values for the data set; either per epoch, per event, or per sample
% this is of the form [N x D] where N is the number of target values and D is the dimensionality
% of the target values (usually 1).
%
% Examples:
% % obtain the target values for the given set
% labels = set_gettarget(eeg)
%
% See also:
% set_targetmarkers, set_makepos
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-07
if ~exist('signal','var')
% trivial
targ = [];
else
% we got a bundle: extract target markers from the first stream
if isfield(signal,'streams')
signal = signal.streams{1}; end
if all(isfield(signal,{'head','parts'})) && strcmp(char(signal.head),'set_partition') && length(signal.parts) >= 2
% a computational shortcut applies if we're operating on partitioned data: this allows us to skip
% the actual partitioning and instead look just at the target markers
sourcetargets = set_gettarget(signal.parts{1});
targ = sourcetargets(signal.parts{2},:);
else
% make sure that the data is evaluated
signal = exp_eval_optimized(signal);
if isfield(signal,'epoch') && ~isempty(signal.epoch) && isfield(signal.epoch,'target')
% epoched data set with target field: get per-epoch targets
targets = {signal.epoch.target};
targetmask = ~cellfun('isempty',targets);
if any(targetmask)
targ = concat_targets(targets(targetmask));
return;
end
end
% continuous data set: check for events with non-empty target field
if isfield(signal,'event') && isfield(signal.event,'target')
targets = {signal.event.target};
targetmask = ~cellfun('isempty',targets);
if any(targetmask)
if ~issorted([signal.event.latency])
warning('BCILAB:unsorted_events','The events in this data set are unsorted - this is likely an error in your processing pipeline.'); end
targ = concat_targets(targets(targetmask));
return;
end
end
if isfield(signal,'chanlocs') && isfield(signal.chanlocs,'type') && isfield(signal,'data') && size(signal.data,3) == 1
% continuous data set: get per-sample epoch targets
targchans = strcmpi('target',{signal.chanlocs.type});
if any(targchans)
targ = signal.data(targchans,:)';
return;
end
end
% otherwise...
error('set_gettarget did not find any target information in this data set. See help of set_gettarget and set_targetmarkers for how data sets can be annotated with target information.');
end
end
function targets = concat_targets(targets)
if all(cellfun('size',targets,1) == 1)
if length(unique(cellfun('size',targets,2))) > 1
error('The target values in this set must have uniform dimensionality.'); end
targets = vertcat(targets{:});
elseif all(cellfun('size',targets,2) == 1)
if length(unique(cellfun('size',targets,1))) > 1
error('The target values in this set must have uniform dimensionality.'); end
targets = horzcat(targets{:})';
else
error('The target values in this set must be either all row vectors or all column vectors.');
end
|
github
|
ZijingMao/baselineeegtest-master
|
set_insert_markers.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_insert_markers.m
| 20,491 |
utf_8
|
2fbcb099d528aa6023ef9d7caba9cee8
|
function newsignal = set_insert_markers(varargin)
% Inject runs of markers into specific segments of a continuous data set.
% Signal = set_insert_markers(Signal, Options...)
%
% Almost all real-time inference in BCIs is done on the basis of epochs, and epochs are most
% conveniently created relative to certain ("time-locking") events/markers in the data. This
% function allows to cover periods of continuous data with events, at regular or random intervals,
% so that epochs covering these ranges can subsequently be extracted. What periods shall be
% populated with events can be flexibly specified.
%
% In:
% Signal : continuous data set
%
% SegmentSpec : segment specification. cell array of one of the following forms (lats in seconds):
% (default: {0 Inf})
% note: the ordering of time values w.r.t. event-type values and cell-array values in the subsequent
% specifications is arbitrary, whereas the ordering of time values w.r.t. each other is relevant
% (first time value shall be lower than second time value); the ordering of eventtypes w.r.t. each
% other is also relevant.
% * {absolute_time absolute_time}:
% segment specified using two time points
% * {event_type relative_time relative_time} / {relative_time event_type relative_time} /
% {relative_time relative_time event_type}:
% here, the segment is relative to some event (of a given type), in between the time interval given by the
% first and second time value
% * {event_type relative_time relative_time event_type} / {relative_time event_type event_type relative_time} / ...
% here, the segment is in between two immediately successive events of the given types (any intervals with other
% events in between the specified ones are not considered for injection), constrained by the relative lats
% for each event
% * {event_type relative_time {ignore_type1,ignore_type2,...} relative_time event_type}
% as above, except that intermediate events of type ignore_type1/ignore_type2/etc. are ignored
% (if the in-between cell array is empty, any other events are ignored)
%
% Limits : optional time limits (in seconds) to constrain event placement (default: [-Inf Inf])
%
% Event : the inserted event type string, or alternatively a template event struct
% (default: "mytype_i", when injected relative to an event of type "mytype" or
% "mytype1_mytype2", when injected in between two events of type "mytype1" and "mytype2")
% * if a string is specified, all event fields besides the 'type', 'latency' and 'duration' fields
% contained in the data will be left empty
% * if a struct is specified, the 'latency' field will be substituted appropriately
%
% Count : number of events inserted within an interval; see Counting for the counting scheme (default: 1)
%
% Counting : what count means for any given segmentspec, either 'perinterval' or 'persecond' (default: 'perinterval')
%
% Placement : how the injected events should be placed, either 'random' or 'equidistant' (default: 'equidistant')
%
% Repeatable : whether the randomization procedure shall give repeatable results (default: 1); different numbers (aside from 0)
% give different repeatable runs, i.e. the value determines the randseed
%
% MinLength : segments that are shorter than this (in seconds) are ignored. (default: 0)
%
% MaxLength : segments that are longer than this (in seconds) are ignored. (default: Inf)
%
% Out:
% Signal : continuous data set with new events injected
%
% Notes:
% The only parameter that may be specified by position (instead of as name-value pair) is the first one.
%
% Examples:
% % place 20 events of type 'X' within the interval 1000s to 2000s into the given data set (regular placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{1000 2000},'Count',20,'Event','X')
%
% % as before, but use an event struct
% eeg = set_insert_markers(eeg, 'SegmentSpec',{1000 2000},'Count',20,'Event',struct('type','X'))
%
% % place 20 events within the interval 1000s to 2000s into the given data set (random pleacement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{1000 2000},'Count',20,'Placement','random','Event','X')
%
% % place 3 events per second within the interval 1000s to 2000s into the given data set (regular placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{1000 2000}, 'Count',3, 'Counting','persecond','Event','X')
%
% % place on average 3 events per second within the interval 1000s to 2000s into the given data set (random placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{1000 2000}, 'Count',3, 'Counting','persecond','Placement','random','Event','X')
%
% % place 20 events of type 'X' within each interval within 2s to 10s following each occurrence of the event 'A'
% eeg = set_insert_markers(eeg, 'SegmentSpec',{'A',2,10},'Count',20,'Event','X')
%
% % place on average 5 events per second (typed 'X') within each interval within -5s to 10s around each occurrence of the event 'A' (random placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{'A',-5,10},'Counting','persecond','Count',5,'Event','X','Placement','random')
%
% % same as before, equivalent SegmentSpec formatting
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A',10},'Counting','persecond','Count',5,'Event','X','Placement','random')
%
% % place 10 events (typed 'X') between each successive occurrence of event 'A' followed by event 'B' (with no other event in between),
% % and begin the interval 5s after event 'A' and end it 3s before event 'B' (regular placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{'A',5,-3,'B'},'Count',10,'Event','X')
%
% % place 10 events (typed 'X') between each successive occurrence of event 'A' followed by event 'B' (with no other event in between),
% % and begin the interval 5s *before* event 'A' and end it right on event 'B' (regular placement)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A',0,'B'},'Count',10,'Event','X')
%
% % as before, but insert 3 events per second
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A',0,'B'},'Count',3,'Counting','persecond','Event','X')
%
% % as before, but also consider those intervals where other events of type 'p' and/or 'q' occur between the 'A' and the 'B'
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {'p','q'}, 0,'B'},'Count',3,'Counting','persecond','Event','X')
%
% % as before, but also consider intervals where any other event occurs between the 'A' and the 'B' (except for 'B' obviously)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {}, 0,'B'},'Count',3,'Counting','persecond','Event','X')
%
% % as before, but discard segments that would be longer than 10 seconds
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {}, 0,'B'},'Count',3,'Counting','persecond','Event','X','MaxLength',10)
%
% % as before, but use random placement
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {}, 0,'B'},'Count',3,'Counting','persecond','Event','X','Placement','random')
%
% % as before, but use a random rand seed to obtain different placing at every call
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {}, 0,'B'},'Count',3,'Counting','persecond','Event','X','Placement','random','Repeatable',0)
%
% % as before, but use a fixed specific rand seed to obtain a specific (but repeatable placing)
% eeg = set_insert_markers(eeg, 'SegmentSpec',{-5,'A', {}, 0,'B'},'Count',3,'Counting','persecond','Event','X','Placement','random','Repeatable',10)
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-05-24
% set_insert_markers_version<1.0> -- for the cache
global tracking;
if ~exp_beginfun('editing') return; end
declare_properties('name','MarkerInsertion', 'independent_channels',true, 'cannot_follow','set_makepos', 'independent_channels',true,'independent_trials',true);
opts = arg_define([0 1],varargin, ...
arg_norep({'signal','Signal'}), ...
arg_subswitch({'segmentspec','SegmentSpec','segment'},'absoluterange', ...
{'absoluterange',{ ...
arg({'lo','BeginOffset'},0,[],'Lower bound of insertion interval. Events will be inserted beginning from this time point, in seconds.'), ...
arg({'hi','EndOffset'},Inf,[],'Upper bound of insertion interval. Events will be inserted up to this time point, in seconds. If this is negative, it counts from the end of the recording.')}, ...
'relativerange',{ ...
arg({'event','EventType'},'event1',[],'Reference event type. New events will be inserted in a range around each event of this type.'), ...
arg({'lo','BeginOffset'},-0.5,[],'Lower bound relative to event. This is the lower boundary of insertion intervals relative to the reference events. In seconds.'), ...
arg({'hi','EndOffset'},1,[],'Upper bound relative to event. This is the upper boundary of insertion intervals relative to the reference events. In seconds.')}, ...
'spannedrange',{ ...
arg({'openevent','OpenEvent'},'event1',[],'Type of opening reference event. New events will be inserted between each pair of successive events with types OpenEvent and CloseEvent.'), ...
arg({'closeevent','CloseEvent'},'event2',[],'Type of closing reference event. New events will be inserted between each pair of successive events with types OpenEvent and CloseEvent.'), ...
arg({'lo','OpenOffset'},0.5,[],'Offset relative to opening event. This is an offset relative to the position of the opening reference event, which shifts the beginning of a spanned insertion interval. In seconds.'), ...
arg({'hi','CloseOffset'},-0.5,[],'Offset relative to closing event. This is an offset relative to the position of the closing reference event, which shifts the beginning of a spanned insertion interval. In seconds.'), ...
arg({'ignored','IgnoredEvents'},{},[],'Ignored event types. This is the list of event types that may occur between the opening and closing events. If any other event appears between a pair of successive opening and closing events, this range will not be considered for event insertion (it is considered "broken"). If set to ''ignoreall'', any event type may appear in between.', 'type','cellstr','shape','row')} ...
},'Insertion interval definition. Events can be inserted either in fixed, absolute time window of the data set (absoluterange), or in time windows relative to reference events of a certain type (relativerange), or in time window spanned by two subsequent events of certain types (called the opening event and the closing event), optionally with ignored events in between (spannedrange).','cat','Time Ranges','mapper',@parse_segment), ...
arg({'limits','Limits'},[-Inf Inf],[],'Time limits for event placement. Events that fall outside these bounds will be skipped. Therefore, intervals that intersect these boundaries may have fewer events than others.','cat','Time Ranges'),...
arg({'event','InsertedType','Event'},'newevent',[],'Type of inserted events. The event type for the newly inserted events.','cat','Placement'), ...
arg({'count','Count'},1,[],'Number of inserted events. This is either per interval or per second, depending on the Counting argument.','cat','Placement'), ...
arg({'counting','Counting'},'perinterval',{'perinterval','persecond'},'Counting measure. Events can be inserted in a certain number per interval or per second','cat','Placement'), ...
arg({'placement','Placement'},'equidistant',{'equidistant','random'},'Event placement scheme. Events can be inserted at equal (regular) distance from each other, or at random positions.','cat','Placement'), ...
arg({'repeatable','Repeatable'},1,[],'Repeatable versus random placement. If 0, placement is random, if different from 0, the number is taken as the random seed, giving a unique repeatable run per number.','cat','Placement'), ...
arg({'minlen','MinLength'},0,[],'Minimum segment length. Ignore segments that are shorter than this, in seconds.'), ...
arg({'maxlen','MaxLength'},Inf,[],'Maximum segment length. Ignore segments that are longer than this, in seconds.'));
signal = opts.signal;
if isfield(signal,'epoch') && ~isempty(signal.epoch)
error('the data set appears to contain epochs: only continuous data set are supported for now.'); end
% refine options
opts.limits = sort(max(min(opts.limits,signal.xmax),signal.xmin));
opts.limits = opts.limits*signal.srate;
opts.segmentspec.lo = opts.segmentspec.lo*signal.srate;
opts.segmentspec.hi = opts.segmentspec.hi*signal.srate;
% init randomization
if strcmp(opts.placement,'random') && opts.repeatable
if hlp_matlab_version < 707
% save & override RNG state
randstate = rand('state'); %#ok<RAND>
rand('state',5182+opts.repeatable); %#ok<RAND>
else
% create a legacy-compatible RandStream
tracking.temp.randstream_inject_events = RandStream('swb2712','Seed',5182+opts.repeatable);
end
end
newsignal = signal;
switch opts.segmentspec.arg_selection
case 'absoluterange'
if opts.segmentspec.lo == -Inf
opts.segmentspec.lo = signal.xmin*signal.srate; end
if opts.segmentspec.hi == Inf
opts.segmentspec.hi = signal.xmax*signal.srate; end
if opts.segmentspec.hi < 0
opts.segmentspec.hi = signal.xmax*signal.srate - opts.segmentspec.hi; end
% inject using absolute latencies
if isempty(opts.event)
error('an event type must be specified'); end
if ischar(opts.event)
opts.event = make_default_event(signal.event,opts.event); end
newsignal = perform_injection(newsignal,[opts.segmentspec.lo opts.segmentspec.hi],opts);
case 'relativerange'
% inject relative to one single marker
if isempty(opts.event)
opts.event = [opts.segmentspec.event '_i']; end
if ischar(opts.event)
opts.event = make_default_event(signal.event,opts.event); end
for e=1:length(signal.event)
if strcmp(signal.event(e).type,opts.segmentspec.event)
newsignal = perform_injection(newsignal,signal.event(e).latency+[opts.segmentspec.lo opts.segmentspec.hi],opts); end
end
case 'spannedrange'
% inject in between two successive markersputting that
if isempty(opts.event)
opts.event = [opts.segmentspec.openevent '_' opts.segmentspec.closeevent]; end
if ischar(opts.event)
opts.event = make_default_event(signal.event,opts.event); end
startlat = [];
for e=1:length(signal.event)
% ignorance turned off but intermediate marker found?
if ~iscell(opts.segmentspec.ignored) && ~strcmp(signal.event(e).type,opts.segmentspec.closeevent)
startlat = []; end
% selective ignorance turned on but non-ignored intermediate marker found?
if ~isequal(opts.segmentspec.ignored,{'ignoreall'}) && ~any(strcmp(signal.event(e).type,[opts.segmentspec.ignored {opts.segmentspec.closeevent}]))
startlat = []; end
% found the begin-marker: open a new segmentspec
if strcmp(signal.event(e).type,opts.segmentspec.openevent)
startlat = signal.event(e).latency; end
% reached the end-marker & have an open segmentspec: inject.
if ~isempty(startlat) && strcmp(signal.event(e).type,opts.segmentspec.closeevent)
newsignal = perform_injection(newsignal,[startlat+opts.segmentspec.lo,signal.event(e).latency+opts.segmentspec.hi],opts); end
end
end
% sort the events by latency...
newsignal.event = newsignal.event(hlp_getresult(2,@sort,[newsignal.event.latency]));
% update .urevent field if trivial
if isempty(newsignal.urevent) || isequal([newsignal.event.urevent],1:length(newsignal.event))
newsignal.urevent = newsignal.event;
[newsignal.event.urevent] = arraydeal(1:length(newsignal.event));
end
% conclude randomization
if strcmp(opts.placement,'random') && opts.repeatable && hlp_matlab_version < 707
% restore saved RNG state
rand('state',randstate); %#ok<RAND>
end
exp_endfun;
function [signal,coverage] = perform_injection(signal,ival,opts)
global tracking;
coverage = 0;
% sanity check
if length(ival) == 2 && ival(1) <= ival(2)
coverage = ival(2)-ival(1);
% check the segment length
seg_length = coverage/signal.srate;
if seg_length < opts.minlen || seg_length > opts.maxlen
return; end
% hande the spacing method
if strcmp(opts.counting,'persecond')
opts.count = max(1,round(opts.count*(ival(2)-ival(1))/signal.srate)); end
% handle the placement method
if strcmp(opts.placement,'equidistant')
if coverage ~= 0
stepsize = (ival(2)-ival(1))/(opts.count-1);
ival = round(ival(1):stepsize:ival(2));
else
ival = ival(1)*ones(1,opts.count);
end
elseif strcmp(opts.placement,'random')
if ival(1) < ival(2)
if hlp_matlab_version < 707
positions = rand(1,opts.count);
else
positions = rand(tracking.temp.randstream_inject_events,1,opts.count);
end
ival = round(positions*(ival(2)-ival(1))+ival(1));
elseif ival(1) == ival(2)
ival = ival(1)*ones(1,opts.count);
else
ival = [];
end
else
error('unsupported placement scheme specified');
end
if ~isempty(ival)
% compute the individual latencies
lats = ival(ival>=opts.limits(1) & ival<=opts.limits(2));
% sanitize latencies
lats = min(max(lats,1),signal.pnts);
if ~isempty(signal.urevent)
signal.urevent = []; end
if isempty(signal.event)
signal.event = setfield(setfield(opts.event,'latency',1),'type','dummy'); end; %#ok<SFLD>
range = length(signal.event) + (1:length(lats));
[signal.event(range)] = deal(opts.event);
[signal.event(range).latency] = arraydeal(lats);
end
end
% create a default event from an event array
function evt = make_default_event(evts,type)
if isempty(evts)
evt = struct('type',{type},'latency',{[]},'duration',{1},'urevent',{[]});
else
evt = evts(1);
for fn=fieldnames(evt)'
evt.(fn{1}) = []; end
evt.type = type;
if isfield(evt,'duration')
evt.duration = 1; end
end
% parse a segmentspec specification into a cell array {tag,name,value,name,value,...}
function [selection,spec] = parse_segment(spec)
if isempty(spec)
selection = 'absoluterange';
elseif ischar(spec) && any(strcmp(spec,{'absoluterange','relativerange','spannedrange'}))
selection = spec;
spec = {};
elseif iscell(spec) && any(strcmp(spec{1},{'absoluterange','relativerange','spannedrange'}))
selection = spec{1};
spec = {};
elseif isfield(spec{1},'arg_selection')
selection = spec{1}.arg_selection;
elseif any(strcmp(spec{1},{'absoluterange','relativerange','spannedrange'}))
[selection,spec] = deal(spec{1},spec(2:end));
else
% we have a custom segmentspec specification (as indicated in the function's help text)
% parse it.
mrks = {};
lats = [];
ignored = [];
for i=1:length(spec)
if ischar(spec{i})
mrks{end+1} = spec{i};
elseif iscell(spec{i})
ignored = [ignored spec{i}];
else
lats(end+1) = spec{i};
end
end
% and configure parameters
if isempty(mrks)
selection = 'absoluterange'; spec = {'lo' min(lats) 'hi' max(lats)};
elseif length(mrks) == 1
selection = 'relativerange'; spec = {'event' mrks{1} 'lo' min(lats) 'hi' max(lats)};
elseif length(mrks) == 2
if isequal(ignored,{})
ignored = {'ignoreall'};
elseif isequal(ignored,[])
ignored = {};
end
selection = 'spannedrange'; spec = {'openevent' mrks{1} 'closeevent' mrks{2} 'lo' lats(1) 'hi' lats(2) 'ignored' ignored};
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
set_concat.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_concat.m
| 3,110 |
utf_8
|
46fd9077c3b6a6e2c007ff4991a9712c
|
function result = set_concat(varargin)
% Concatenate continuous signals across time.
% Result = set_joinepos(Set1, Set2, ...)
%
% In:
% SetK : The k'th data set to concatenate.
%
% Out:
% Result : A new data set that is the concatenation of all input sets. The following changes are made:
% * .data and all other time-series fields are concatenated across time (2nd dimension)
% * .event is joined and .latency fields are updated appropriately
% * .xmax/.pnts are updated
%
% Notes:
% This function returns a new data set with meta-data set to that of the first input set, and the
% time series field sjoined across all sets. No checks for meta-data consistency are done. There
% is a heavy-duty function for merging inconsistent sets called set_merge, which can merge cats
% and dogs. This function does not attempt to keep miscellaneous EEGLAB meta-data consistent,
% including: setname,filename,filepath,subject,group,condition,session,comments,urevent,reject,stats,history,etc
%
% Examples:
% % concatenate data sets eegA, eegB and eegC across time
% eeg = set_concat(eegA,eegB,eegC)
%
% See also:
% set_joinepos, set_merge
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-03-31
% set_joinepos_version<1.0> -- for the cache
if ~exp_beginfun('editing') return; end
declare_properties('name','Concatenate','independent_channels',true,'independent_trials',false);
if ~isempty(varargin)
if any(cellfun(@(x)isfield(x,'epoch') && ~isempty(x.epoch),varargin))
error('Only continuous data can be concatenated with set_concat -- use set_joinepos for epoched data.'); end
result = varargin{1};
if length(varargin) > 1
% concatenate time series fields
for field = utl_timeseries_fields(result)
data = cellfun(@(x)x.(field{1}),varargin,'UniformOutput',false);
result.(field{1}) = cat(2,data{:});
if isempty(result.(field{1}))
result.(field{1}) = []; end
end
% count events, epochs and samples in each set
event_count = cellfun(@(x)length(x.event),varargin);
sample_count = cellfun(@(x)x.pnts,varargin);
% concatenate .event and .epoch fields
event = cellfun(@(x)x.event,varargin,'UniformOutput',false); result.event = [event{:}];
% shift event latencies based on cumulative sample counts
if ~isempty(result.event)
[result.event.latency] = arraydeal([result.event.latency]+replicate(cumsum(sample_count)-sample_count,event_count)); end
% update misc fields
[result.nbchan,result.pnts,result.trials,extra_dims] = size(result.data); %#ok<NASGU>
result.xmax = result.xmin + (result.pnts-1)/result.srate;
end
else
result = eeg_emptyset;
end
exp_endfun;
function result = replicate(values,counts)
% Replicate each element Values(k) by Count(k) times.
result = zeros(1,sum(counts));
k = 0;
for p=find(counts)
result(k+(1:counts(p))) = values(p);
k = k+counts(p);
end
|
github
|
ZijingMao/baselineeegtest-master
|
set_fit_dipoles.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_fit_dipoles.m
| 13,316 |
utf_8
|
5ca3bc4f74abcc0a542211d0525687ba
|
function signal = set_fit_dipoles(varargin)
% Fit dipoles for each independent component of an IC-decomposed dataset.
%
% This function uses the Dipfit plugin for EEGLAB to automatically derive dipole locations
% for all IC's in the data set. The returned coordinates are in the MNI coordinate system.
% In addition, (probabilistic) anatomical labels can be looked up from different brain atlases [1,2].
%
%
% In:
% Signal : data set with valid IC decomposition
%
% HeadModel : head model file (see pop_dipfit_settings) (default: standard BEM volume)
%
% MRImage : anatomical MR head image file (default: standard BEM image)
%
% ChannelLocations : coregistered channel locations file (default: standard 10-20 locations)
%
% LookupLabels : whether to look up anatomical labels & probabilities (default: true)
%
% ConfusionRange : radius (in mm) of uncertainty over which to scan for labels (default: 4)
%
% BrainAtlas : brain atlas to use. Talairach has a larger repertoire of areas, but is (in
% this version) non-probabilistic. The LONI LBPA40 atlas is a high-quality
% probabilistic atlas.
%
% Out:
% Signal : data set with added dipole annotations
%
% Notes:
% In the default settings, a standard Eurasian BEM head model amd MR image is used, and channel
% locations are assumed to be standard 10-20 locations if not specifically given.
%
% Examples:
% % for a data set which is annotated with independent components, e.g. via
% eeg = flt_ica(raw);
%
% % ... fit dipoles for each component using default settings, and look up the nearby anatomical
% % structures and their hit probabilities)
% eeg = set_fit_dipoles(eeg)
%
% % ... fit dipoles and and look up anatomical structures within a radius of 10mm around each
% % dipole coordinate (passing arguments by name)
% eeg = set_fit_dipoles('Signal',eeg,'ConfusionRange',10)
%
% % ... fit dipoles but do not look up anatomical structures
% eeg = set_fit_dipoles('Signal',eeg,'LookupLabels',false)
%
% % ... fit dipoles using a (subject-) specific head model and MR file
% eeg = set_fit_dipoles('Signal',eeg,'HeadModel','volXY.mat','MRImage','mriXY.mat')
%
% % ... fit dipoles using a (subject-) specific head model and MR file, as well as digitized
% % channel locations
% eeg = set_fit_dipoles('Signal',eeg,'HeadModel','my_vol.mat','MRImage','my_mri.mat','ChannelLocations','my_locs.mat')
%
% References:
% [1] Lancaster JL, Woldorff MG, Parsons LM, Liotti M, Freitas CS, Rainey L, Kochunov PV, Nickerson D, Mikiten SA, Fox PT, "Automated Talairach Atlas labels for functional brain mapping".
% Human Brain Mapping 10:120-131, 2000
% [2] Shattuck DW, Mirza M, Adisetiyo V, Hojatkashani C, Salamon G, Narr KL, Poldrack RA, Bilder RM, Toga AW, "Construction of a 3D probabilistic atlas of human cortical structures."
% Neuroimage. 2008 39(3):1064-80
%
% See also:
% flt_ica, coregister, pop_multifit
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2011-01-21
% set_fit_dipoles_version<0.91> -- for the cache
if ~exp_beginfun('filter') return; end
% declare GUI name, etc.
declare_properties('name',{'DipoleFitting','dipfit'}, 'depends','flt_ica', 'precedes','flt_project', 'independent_channels',true, 'independent_trials',true);
% define arguments...
arg_define(varargin, ...
arg_norep({'signal','Signal'}), ...
arg({'hdm_file','HeadModel'}, '', [],'Head model file. The BEM head model that should be used by dipfit (using a standard model if empty).'),...
arg({'mri_file','MRImage'}, '', [],'MR head image file. The MR head image that should be used by dipfit (using a standard image if empty).'),...
arg({'chan_file','ReferenceLocations'}, '', [],'Coregistered reference chanlocs. The coregistered electrode locations that should be used as reference for alignment warping.'),...
arg({'lookup_labels','LookupLabels'},true,[], 'Look up dipole labels. If enabled, look up anatomical labels from the selected brain atlas.'),...
arg({'confusion_range','ConfusionRange'}, 4, [1 30], 'Confusion Radius (mm). Assumed standard deviation of uncertainty in the dipole fits, in millimeters.'),...
arg({'brain_atlas','BrainAtlas'}, 'Talairach', {'Talairach','LBPA40'}, 'Brain atlas to use. Talairach has a larger repertoire of areas, but is (in this version) non-probabilistic. The LONI LBPA40 atlas is a high-quality probabilistic atlas; however, you have to to download it yourself.'),...
arg({'var_threshold','VarianceThreshold'}, 15, [1 100], 'Residual Variance Thresold (%). The threshold in dipole fit residual variance above which dipoles models are rejected.'),...
arg({'mri_constraints','UseMRIConstraints'}, false, [], 'Use MRI constraints. If enabled, restricts dipole solutions to the grey-matter volume. The currently requires the SPM toolbox to be in the path.'),...
arg({'discard_nonlocalizable','DiscardNonlocalizable'}, false, [], 'Discard non-localizable components.'),...
arg({'verbose','VerboseOutput'}, false, [], 'Verbose output.'),...
arg_norep('dipfit_info', unassigned));
if ~exist('dipfit_info','var')
% use standard data if unspecified
if isempty(hdm_file) %#ok<*NODEF>
hdm_file = env_translatepath('resources:/standard_BEM/standard_vol.mat'); end
if isempty(mri_file)
if mri_constraints
mri_file = env_translatepath('resources:/standard_BEM/standard_mri_gm.mat');
else
mri_file = '';
end
end
if isempty(chan_file)
% figure out the labeling scheme to determine the correct coregistration...
if ~isfield(signal.chaninfo,'labelscheme')
signal.chaninfo.labelscheme = '10-20'; end
switch signal.chaninfo.labelscheme
case '10-20'
chan_file = env_translatepath('resources:/standard_BEM/elec/standard_1005.elc');
case 'sccn_128_v1'
chan_file = env_translatepath('resources:/sccn_BEM_coregistered_128_v1.xyz');
case 'sccn_128_v2'
chan_file = env_translatepath('resources:/sccn_BEM_coregistered_128_v2.xyz');
case 'sccn_256_v1'
chan_file = env_translatepath('resources:/sccn_BEM_coregistered_256_v1.xyz');
case 'sccn_256_v2'
chan_file = env_translatepath('resources:/sccn_BEM_coregistered_256_v2.xyz');
otherwise
error('Unknown channel labeling scheme -- please supply a chan_file argument.');
end
end
disp(['Now fitting dipoles... (montage reference: ' chan_file ')']);
% fit icaweights
if verbose
dipfit_info = hlp_diskcache('dipfits',@do_fitting,signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);
else
[text,dipfit_info] = evalc('hlp_diskcache(''dipfits'',@do_fitting,signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold)');
end
try
% check if we need to fit Amica models, too...
if isfield(signal.etc,'amica')
sig = signal;
multimodel = {};
for m=1:size(signal.etc.amica.W,3)
sig.icaweights = signal.etc.amica.W(:,:,m);
sig.icawinv = signal.etc.amica.A(:,:,m);
sig.icasphere = signal.etc.amica.S;
if verbose
tmp = hlp_diskcache('dipfits',@do_fitting,sig,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);
else
[text,tmp] = evalc('hlp_diskcache(''dipfits'',@do_fitting,sig,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold);');
end
multimodel{m} = tmp.model; %#ok<AGROW>
end
dipfit_info.multimodel = multimodel;
end
catch
disp('Could not compute dipfit solutions for Amica models.');
end
end
signal.dipfit = dipfit_info;
if discard_nonlocalizable
retain_ics = ~cellfun(@isempty,{signal.dipfit.model.posxyz});
% update the dipole model
signal.dipfit.model = signal.dipfit.model(retain_ics);
% restrict the ICs & some derived data
signal.icaweights = signal.icaweights(retain_ics,:);
signal.icawinv = signal.icawinv(:,retain_ics);
if ~isempty(signal.icaact) && ~isscalar(signal.icaact)
signal.icaact = signal.icaact(retain_ics,:,:); end
end
if isfield(signal.etc,'amica')
signal.etc.amica.dipfit = dipfit_info; end
global tracking;
tracking.inspection.dipfit = dipfit_info;
% when applied online, include the dipfit info into the parameters (so it gets attached immediately)
exp_endfun('append_online',{'dipfit_info',dipfit_info});
function result = do_fitting(signal,mri_file,hdm_file,chan_file,lookup_labels,brain_atlas,confusion_range,var_threshold)
% coregister chanlocs to reference channels
[dummy,warping] = coregister(signal.chanlocs,chan_file,'warp','auto','manual','off'); %#ok<ASGLU>
% generate the dipfit info
%nosedir needs to be set to +X here for dipfit to work
signal.chaninfo.nosedir = '+X';
tmp = pop_multifit(pop_dipfit_settings(pop_select(signal,'channel',signal.icachansind), ...
'mrifile',mri_file, 'hdmfile',hdm_file,'chanfile',chan_file,'coordformat','MNI','coord_transform',warping), 1:size(signal.icaweights,1),'threshold',var_threshold);
% optionally derive anatomical labels & probabilities
if lookup_labels
switch lower(brain_atlas)
case 'talairach'
db = org.talairach.Database;
db.load(env_translatepath('resources:/talairach.nii'));
for k=1:length(tmp.dipfit.model)
try
p = icbm_spm2tal(tmp.dipfit.model(k).posxyz);
tmp.dipfit.model(k).labels = cellfun(@(d)char(d),cell(db.search_range(p(1),p(2),p(3),1.5*confusion_range)),'UniformOutput',false);
% and compute structure probabilities within the selected volume
[structures,x,idxs] = unique(hlp_split(sprintf('%s,',tmp.dipfit.model(k).labels{:}),',')); %#ok<ASGLU>
probabilities = mean(bsxfun(@eq,1:max(idxs),idxs'));
[probabilities,reindex] = sort(probabilities,'descend');
structures = structures(reindex);
mask = ~strcmp(structures,'*');
tmp.dipfit.model(k).structures = structures(mask);
tmp.dipfit.model(k).probabilities = probabilities(mask)*5; % there are 5 partitions
% figure('Position',[0 0 2560 900]); topoplot(tmp.icawinv(:,k),tmp.chanlocs); title([hlp_tostring(structures(mask)) 10 hlp_tostring(5*probabilities(mask))]); pop_dipplot(tmp,k);
catch
tmp.dipfit.model(k).labels = {};
tmp.dipfit.model(k).structures = {};
tmp.dipfit.model(k).probabilities = [];
end
end
case 'lbpa40'
mask = find(~cellfun('isempty',{tmp.dipfit.model.posxyz}));
% build query
coords = vertcat(tmp.dipfit.model.posxyz);
coords = [coords confusion_range * ones(size(coords,1),1)];
% look up from atlas (note: slow!)
[probs,labels] = label_dipoles(coords);
% determine overlapped specialty regions to match up with Talairach's labeling scheme
L = ~cellfun('isempty',strfind(labels,' L '));
R = ~cellfun('isempty',strfind(labels,' R '));
B = ~cellfun('isempty',strfind(labels,'Brainstem'));
C = ~cellfun('isempty',strfind(labels,'Cerebellum'));
allprobs = [sum(probs(:,L),2) sum(probs(:,R),2) sum(probs(:,C),2)*[0.5 0.5] sum(probs(:,B),2)];
allstructs = {'Left Cerebrum' 'Right Cerebrum' 'Left Cerebellum' 'Right Cerebellum' 'Brainstem'};
% go through all gyri and add up left & right probabilities
gyri = unique(cellfun(@(l)l(12:end),labels(1:end-2),'UniformOutput',false))';
allstructs = [allstructs gyri];
for g=1:length(gyri)
curgyrus = gyri{g};
matches = ~cellfun('isempty',strfind(labels,curgyrus));
allprobs = [allprobs sum(probs(:,matches),2)];
end
for k=1:length(mask)
% retain only those with non-zero probability
sel = allprobs(k,:) ~= 0;
probabilities = allprobs(k,sel);
structures = allstructs(sel);
% sort probs & associated structs by descending probability
[probabilities,reindex] = sort(probabilities,'descend');
structures = structures(reindex);
% store in the model...
tmp.dipfit.model(mask(k)).structures = structures;
tmp.dipfit.model(mask(k)).probabilities = probabilities;
% figure('Position',[0 0 2560 900]);topoplot(tmp.icawinv(:,k),tmp.chanlocs); title([hlp_tostring(structures) 10 hlp_tostring(probabilities)]); pop_dipplot(tmp,k);
end
end
end
result = tmp.dipfit;
|
github
|
ZijingMao/baselineeegtest-master
|
set_joinepos.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/dataset_editing/set_joinepos.m
| 3,572 |
utf_8
|
86418e7bbad408ccff0c1f5d02c48478
|
function result = set_joinepos(varargin)
% Join epoched signals across epochs.
% Result = set_joinepos(Set1, Set2, ...)
%
% In:
% SetK : The k'th data set to join.
%
% Out:
% Result : A new data set with trials from all sets joined. The following changes are made:
% * .data and all other time-series fields are joined across trials (3rd dimension)
% * .epoch is joined and its .event field is updated appropriately
% * .event is joined and its .epoch and .latency fields are updated appropriately
% * .xmax/.trials are updated
%
% Notes:
% This function returns a new data set with meta-data set to that of the first input set, and the
% trials joined across all sets. No checks for meta-data consistency are done. There is a
% heavy-duty function for merging inconsistent sets called set_merge, which can merge cats and
% dogs. This function does not attempt to keep miscellaneous EEGLAB meta-data consistent, including:
% setname,filename,filepath,subject,group,condition,session,comments,urevent,reject,stats,history,etc
%
% To concatenate continuous sets across time, use set_concat.
%
% Examples:
% % merge data sets eegA, eegB and eegC across epochs
% eeg = set_joinepos(eegA,eegB,eegC)
%
% See also:
% set_concat, set_merge
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-03-31
% set_joinepos_version<1.0> -- for the cache
if ~exp_beginfun('editing') return; end
declare_properties('name','JoinTrials','independent_channels',true,'independent_trials',true);
if ~isempty(varargin)
result = varargin{1};
if length(varargin) > 1
% concatenate time series fields
for field = utl_timeseries_fields(result)
data = cellfun(@(x)x.(field{1}),varargin,'UniformOutput',false);
result.(field{1}) = cat(3,data{:});
if isempty(result.(field{1}))
result.(field{1}) = []; end
end
% count events, epochs and samples in each set
event_count = cellfun(@(x)length(x.event),varargin);
epoch_count = cellfun(@(x)length(x.epoch),varargin);
sample_count = cellfun(@(x)x.pnts,varargin).*epoch_count;
% concatenate .event and .epoch fields
event = cellfun(@(x)x.event,varargin,'UniformOutput',false); result.event = [event{:}];
epoch = cellfun(@(x)x.epoch,varargin,'UniformOutput',false); result.epoch = [epoch{:}];
% shift event latencies based on cumulative sample counts
if ~isempty(result.event)
[result.event.latency] = arraydeal([result.event.latency]+replicate(cumsum(sample_count)-sample_count,event_count));
% shift event/epoch cross-references based on cumulative counts
[result.event.epoch] = arraydeal([result.event.epoch]+replicate(cumsum(epoch_count)-epoch_count,event_count));
[result.epoch.event] = chopdeal([result.epoch.event]+replicate(cumsum(event_count)-event_count,event_count),cellfun('length',{result.epoch.event}));
end
% update misc fields
[result.nbchan,result.pnts,result.trials,extra_dims] = size(result.data); %#ok<NASGU>
result.xmax = result.xmin + (result.pnts-1)/result.srate;
end
else
result = eeg_emptyset;
end
exp_endfun;
function result = replicate(values,counts)
% Replicate each element Values(k) by Count(k) times.
result = zeros(1,sum(counts));
k = 0;
for p=find(counts)
result(k+(1:counts(p))) = values(p);
k = k+counts(p);
end
|
github
|
ZijingMao/baselineeegtest-master
|
exp_eval_optimized.m
|
.m
|
baselineeegtest-master/BigEEGConsortium-ESS/Ess_tools/dependency/expressions/exp_eval_optimized.m
| 5,336 |
utf_8
|
ebfd9f7b2500706eaefa02a690f4c01d
|
function varargout = exp_eval_optimized(x,iters)
% Evaluate the given expression using optimizations.
% Out-Args = exp_eval_optimized(exp)
%
% This function should produce the same result as exp_eval(), however it may cache intermediate
% results in memory or on disk (and reuse them later), or perform some (known-to-be-safe) reorderings
% of computations. Currently, this function is primarily relevant for evaluating filter expressions
% efficiently, and it contains some domain-specific optimizations to expedite their evaluation.
%
% In:
% Expression : expression to evaluate
%
% Iterations : optionally restrict the number of iterations done by exp_eval (default: 1)
%
% Out:
% Out-Args : the result of the evaluation
%
% Notes:
% The currently implemented optimizations are memory and optional disk caching of all expressions
% (while it does not attempt to disk-cache expressions that contain a set_partition() since, as
% there can be 100s of partitioned versions during bootstrap/resampling calculations). The other
% optimization is that partitioning steps are being reodered to come after expensive filter operations
% (e.g., resampling), so that the same data does not have to be processed over and over for different
% overlapping partitions. Partitioning steps are not moved over processing steps that compute
% statistics over the data (such as ICA, SSA or standardization), as declared by the
% 'independent_trials' property of the respective stage.
%
% See also:
% exp_eval
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2010-04-15
if ~exist('iters','var')
iters = 1; end
varargout = {x};
if isfield(x,{'head','parts'})
% first (and key) optimization: "pull up" any set_partition() node in the expression as high as
% possible (i.e. partition the data as late as possible); the only nodes that cannot be skipped by
% a partition operation are those which have their 'independent_trials' property set to false.
x = pull_up(x);
% now add caching hints recursively...
[x,unpartitioned] = add_cache_hints(x,iters);
% ... and evaluate with the remaining evaluation hints around the top-level expression
[varargout{1:nargout}] = hlp_scope({'memoize',{'memory',1,'disk',double(unpartitioned)}}, @exp_eval,x,iters);
end
% add disk cache hints around whatever is sitting below a set_partition expression...
function [x,unpartitioned] = add_cache_hints(x,iters)
unpartitioned = true;
if all(isfield(x,{'parts','head'}))
% first recurse and find out whether the sub-expressions are partitioned or not
for p=1:length(x.parts)
[x.parts{p},unp] = add_cache_hints(x.parts{p},iters);
unpartitioned = unpartitioned & unp;
end
% check if this is a set_partition expression
chead = char(x.head);
if strcmp(chead,'set_partition')
if unpartitioned
% it is sitting on top of an unpartitioned sub-expression: add a disk cache hint
% around that sub-expression
x.parts{1} = exp_block({exp_rule(@memoize,{'memory',1,'disk',1})},x.parts{1},iters);
end
unpartitioned = false;
end
end
function [x,chead] = pull_up(x)
% recursively pull up set_partition(x,_) nodes in an expression structure
chead = char(x.head);
num_expressions = 0; % number of sub-expressions
partition_at = []; % indices of the set_partition sub-expressions in parts, if any
% recurse into parts...
for p=1:length(x.parts)
if isfield(x.parts{p},{'head','parts'})
[x.parts{p},head_p] = pull_up(x.parts{p});
% count the number of sub-expressions
num_expressions = num_expressions+1;
% remember the places where we have set_partition sub-expressions
if strcmp(head_p,'set_partition')
partition_at(end+1) = p; end %#ok<AGROW>
end
end
% now perform the reordering, if applicable
if num_expressions == length(partition_at) && num_expressions > 0
% check if the current node has the independent_trials=false property (which prevents reordering)
props = hlp_microcache('props',@arg_report,'properties',x.head,{hlp_fileinfo(x.head,[],'hash')});
if ~props.independent_trials
return; end
% we can proceed
if num_expressions == 1
% simple standard case: reorder this node with the set_partition below it
% make a backup of our old set_partition(<y>,index_set) sub-expression
oldchild = x.parts{partition_at};
% replace our old set_partition(<y>,index_set) by the <y>
x.parts{partition_at} = oldchild.parts{1};
% and replace the whole thing by a new set_partition(<the whole thing>,index_set) node
x = struct('head',{@set_partition},'parts',{{x,oldchild.parts{2:end}}});
chead = 'set_partition';
% finally recurse again and pull up any subordinate set_partition's
for p=1:length(x.parts)
if isfield(x.parts{p},{'head','parts'})
x.parts{p} = pull_up(x.parts{p}); end
end
else
% fusion of multiple partitioned data sets (only permitted if indices are identical)
return; % not yet implemented...
end
end
|
github
|
minogame/caffe-qhconv-master
|
prepare_batch.m
|
.m
|
caffe-qhconv-master/matlab/caffe/prepare_batch.m
| 1,298 |
utf_8
|
68088231982895c248aef25b4886eab0
|
% ------------------------------------------------------------------------
function images = prepare_batch(image_files,IMAGE_MEAN,batch_size)
% ------------------------------------------------------------------------
if nargin < 2
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
end
num_images = length(image_files);
if nargin < 3
batch_size = num_images;
end
IMAGE_DIM = 256;
CROPPED_DIM = 227;
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
center = floor(indices(2) / 2)+1;
num_images = length(image_files);
images = zeros(CROPPED_DIM,CROPPED_DIM,3,batch_size,'single');
parfor i=1:num_images
% read file
fprintf('%c Preparing %s\n',13,image_files{i});
try
im = imread(image_files{i});
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% Transform GRAY to RGB
if size(im,3) == 1
im = cat(3,im,im,im);
end
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% Crop the center of the image
images(:,:,:,i) = permute(im(center:center+CROPPED_DIM-1,...
center:center+CROPPED_DIM-1,:),[2 1 3]);
catch
warning('Problems with file',image_files{i});
end
end
|
github
|
minogame/caffe-qhconv-master
|
matcaffe_demo_vgg.m
|
.m
|
caffe-qhconv-master/matlab/caffe/matcaffe_demo_vgg.m
| 3,036 |
utf_8
|
f836eefad26027ac1be6e24421b59543
|
function scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file)
%
% Demo of the matlab wrapper using the networks described in the BMVC-2014 paper "Return of the Devil in the Details: Delving Deep into Convolutional Nets"
%
% INPUT
% im - color image as uint8 HxWx3
% use_gpu - 1 to use the GPU, 0 to use the CPU
% model_def_file - network configuration (.prototxt file)
% model_file - network weights (.caffemodel file)
% mean_file - mean BGR image as uint8 HxWx3 (.mat file)
%
% OUTPUT
% scores 1000-dimensional ILSVRC score vector
%
% EXAMPLE USAGE
% model_def_file = 'zoo/VGG_CNN_F_deploy.prototxt';
% model_file = 'zoo/VGG_CNN_F.caffemodel';
% mean_file = 'zoo/VGG_mean.mat';
% use_gpu = true;
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file, mean_file);
%
% NOTES
% the image crops are prepared as described in the paper (the aspect ratio is preserved)
%
% PREREQUISITES
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% init caffe network (spews logging info)
matcaffe_init(use_gpu, model_def_file, model_file);
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im, mean_file)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
% size(scores)
scores = squeeze(scores);
% scores = mean(scores,2);
% [~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im, mean_file)
% ------------------------------------------------------------------------
IMAGE_DIM = 256;
CROPPED_DIM = 224;
d = load(mean_file);
IMAGE_MEAN = d.image_mean;
% resize to fixed input size
im = single(im);
if size(im, 1) < size(im, 2)
im = imresize(im, [IMAGE_DIM NaN]);
else
im = imresize(im, [NaN IMAGE_DIM]);
end
% RGB -> BGR
im = im(:, :, [3 2 1]);
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices_y = [0 size(im,1)-CROPPED_DIM] + 1;
indices_x = [0 size(im,2)-CROPPED_DIM] + 1;
center_y = floor(indices_y(2) / 2)+1;
center_x = floor(indices_x(2) / 2)+1;
curr = 1;
for i = indices_y
for j = indices_x
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :)-IMAGE_MEAN, [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
images(:,:,:,5) = ...
permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:)-IMAGE_MEAN, ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
github
|
minogame/caffe-qhconv-master
|
matcaffe_demo.m
|
.m
|
caffe-qhconv-master/matlab/caffe/matcaffe_demo.m
| 3,344 |
utf_8
|
669622769508a684210d164ac749a614
|
function [scores, maxlabel] = matcaffe_demo(im, use_gpu)
% scores = matcaffe_demo(im, use_gpu)
%
% Demo of the matlab wrapper using the ILSVRC network.
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format:
% % convert from uint8 to single
% im = single(im);
% % reshape to a fixed size (e.g., 227x227)
% im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % permute from RGB to BGR and subtract the data mean (already in BGR)
% im = im(:,:,[3 2 1]) - data_mean;
% % flip width and height to make width the fastest dimension
% im = permute(im, [2 1 3]);
% If you have multiple images, cat them with cat(4, ...)
% The actual forward function. It takes in a cell array of 4-D arrays as
% input and outputs a cell array.
% init caffe network (spews logging info)
if exist('use_gpu', 'var')
matcaffe_init(use_gpu);
else
matcaffe_init();
end
if nargin < 1
% For demo purposes we will use the peppers image
im = imread('peppers.png');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
size(scores)
scores = squeeze(scores);
scores = mean(scores,2);
[~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im)
% ------------------------------------------------------------------------
d = load('ilsvrc_2012_mean');
IMAGE_MEAN = d.image_mean;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% resize to fixed input size
im = single(im);
im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% permute from RGB to BGR (IMAGE_MEAN is already BGR)
im = im(:,:,[3 2 1]) - IMAGE_MEAN;
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
curr = 1;
for i = indices
for j = indices
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
center = floor(indices(2) / 2)+1;
images(:,:,:,5) = ...
permute(im(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:), ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
|
github
|
minogame/caffe-qhconv-master
|
matcaffe_demo_vgg_mean_pix.m
|
.m
|
caffe-qhconv-master/matlab/caffe/matcaffe_demo_vgg_mean_pix.m
| 3,069 |
utf_8
|
04b831d0f205ef0932c4f3cfa930d6f9
|
function scores = matcaffe_demo_vgg_mean_pix(im, use_gpu, model_def_file, model_file)
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file)
%
% Demo of the matlab wrapper based on the networks used for the "VGG" entry
% in the ILSVRC-2014 competition and described in the tech. report
% "Very Deep Convolutional Networks for Large-Scale Image Recognition"
% http://arxiv.org/abs/1409.1556/
%
% INPUT
% im - color image as uint8 HxWx3
% use_gpu - 1 to use the GPU, 0 to use the CPU
% model_def_file - network configuration (.prototxt file)
% model_file - network weights (.caffemodel file)
%
% OUTPUT
% scores 1000-dimensional ILSVRC score vector
%
% EXAMPLE USAGE
% model_def_file = 'zoo/deploy.prototxt';
% model_file = 'zoo/model.caffemodel';
% use_gpu = true;
% im = imread('../../examples/images/cat.jpg');
% scores = matcaffe_demo_vgg(im, use_gpu, model_def_file, model_file);
%
% NOTES
% mean pixel subtraction is used instead of the mean image subtraction
%
% PREREQUISITES
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% init caffe network (spews logging info)
matcaffe_init(use_gpu, model_def_file, model_file);
% mean BGR pixel
mean_pix = [103.939, 116.779, 123.68];
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im, mean_pix)};
toc;
% do forward pass to get scores
% scores are now Width x Height x Channels x Num
tic;
scores = caffe('forward', input_data);
toc;
scores = scores{1};
% size(scores)
scores = squeeze(scores);
% scores = mean(scores,2);
% [~,maxlabel] = max(scores);
% ------------------------------------------------------------------------
function images = prepare_image(im, mean_pix)
% ------------------------------------------------------------------------
IMAGE_DIM = 256;
CROPPED_DIM = 224;
% resize to fixed input size
im = single(im);
if size(im, 1) < size(im, 2)
im = imresize(im, [IMAGE_DIM NaN]);
else
im = imresize(im, [NaN IMAGE_DIM]);
end
% RGB -> BGR
im = im(:, :, [3 2 1]);
% oversample (4 corners, center, and their x-axis flips)
images = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices_y = [0 size(im,1)-CROPPED_DIM] + 1;
indices_x = [0 size(im,2)-CROPPED_DIM] + 1;
center_y = floor(indices_y(2) / 2)+1;
center_x = floor(indices_x(2) / 2)+1;
curr = 1;
for i = indices_y
for j = indices_x
images(:, :, :, curr) = ...
permute(im(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :), [2 1 3]);
images(:, :, :, curr+5) = images(end:-1:1, :, :, curr);
curr = curr + 1;
end
end
images(:,:,:,5) = ...
permute(im(center_y:center_y+CROPPED_DIM-1,center_x:center_x+CROPPED_DIM-1,:), ...
[2 1 3]);
images(:,:,:,10) = images(end:-1:1, :, :, curr);
% mean BGR pixel subtraction
for c = 1:3
images(:, :, c, :) = images(:, :, c, :) - mean_pix(c);
end
|
github
|
minogame/caffe-qhconv-master
|
classification_demo.m
|
.m
|
caffe-qhconv-master/matlab/demo/classification_demo.m
| 5,412 |
utf_8
|
8f46deabe6cde287c4759f3bc8b7f819
|
function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github
|
PSLmodels/Geo-DICE-master
|
T_Utility.m
|
.m
|
Geo-DICE-master/CTP/T_Utility.m
| 1,456 |
utf_8
|
925d74c7c2c30029e45997ddcc1ee234
|
%Algorithm for calculating the social utility of each state under ceratin
%action (a3)
function [ U ] = T_Utility( S4, a4, g4, Wm4, t4)
%Social Utility for a given state St
% state = S4
% action = a4, g4
% time = t4
global theta1 theta2 theta3 L alpha Gcoeff deltarf Fex etha1
global thetaGE sai2temp sai2ocean sai2atmos nuG Geffective TP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Radiative Forcings change due to GE
RF0 = S4(9);
S4(9) = (deltarf * ((log(S4(4)) - log(596.4)) / log(2)) + Fex(t4)) * (1 - Geffective * g4);
%Atmospheric Temperature change due to GE
S4(2) = S4(2) + etha1 * (S4(9) - RF0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if TP == 7 && S4(10) == 1
dm = 0.01;
else
dm = 0;
end
% Damage cost function
Damage = (1 - dm)/((1 + sai2temp * (Wm4 * S4(2)) ^ 2 + sai2ocean * (S4(5) - 1094) ^ 2 + sai2atmos * (S4(4) - 596.4) ^ 2) * (1 + nuG * g4 ^ 2));
Dam = 1 - Damage;
% Abatement cost function
Abate = theta1(t4) * a4 ^ theta2;
% Geoengineering cost function
%Geoengineer = Gcoeff * theta1(t4) * g4 ^ theta3;
Geoengineer = Gcoeff * thetaGE * g4 ^ theta3;
% Net output after damage and abatement
Q = (1 - (Dam + Abate + Geoengineer)) * S4(7);
% Consumption
C = (1 - 0.22) * Q;
% Consumption per capita
c = C / L(t4) * 1000;
% Utility per capita
u = 1 + c ^ (1 - alpha) / (1 - alpha);
% Social utility
U = u * L(t4) * 10;
end
|
github
|
PSLmodels/Geo-DICE-master
|
Rep_Utility.m
|
.m
|
Geo-DICE-master/CTP/MHE-DWI/Rep_Utility.m
| 745 |
utf_8
|
d33cbd5b2f47256faebac97e812f7a35
|
%Algorithm for calculating the social utility of each state under ceratin
%action (a3)
function [ U ] = Rep_Utility( S4, a4, Wm4, t4)
%Social Utility for a given state St
% state = S4
% action = a4
% time = t4
global theta1 theta2 L alpha
global sai1 sai2 sai3
% Damage cost function
Damage = 1 / (1 + sai1 * S4(2) + sai2 * (Wm4 * S4(2)) ^ sai3);
Dam = 1 - Damage;
% Abatement cost function
Abate = theta1(t4) * a4 ^ theta2;
% Net output after damage and abatement
Q = (1 - (Dam + Abate)) * S4(7);
% Consumption
C = (1 - 0.22) * Q;
% Consumption per capita
c = C / L(t4) * 1000;
% Utility per capita
u = 1 + c ^ (1 - alpha) / (1 - alpha);
% Social utility
U = u * L(t4) * 10;
end
|
github
|
PSLmodels/Geo-DICE-master
|
T_G_Utility.m
|
.m
|
Geo-DICE-master/CTP/MHE-DWI/T_G_Utility.m
| 1,460 |
utf_8
|
94eca70573405582478bde2db91a5d39
|
%Algorithm for calculating the social utility of each state under ceratin
%action (a3)
function [ U ] = T_G_Utility( S4, a4, g4, Wm4, t4)
%Social Utility for a given state St
% state = S4
% action = a4, g4
% time = t4
global theta1 theta2 theta3 L alpha Gcoeff deltarf Fex etha1
global thetaGE sai2temp sai2ocean sai2atmos nuG Geffective TP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Radiative Forcings change due to GE
RF0 = S4(9);
S4(9) = (deltarf * ((log(S4(4)) - log(596.4)) / log(2)) + Fex(t4)) * (1 - Geffective * g4);
%Atmospheric Temperature change due to GE
S4(2) = S4(2) + etha1 * (S4(9) - RF0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if TP == 7 && S4(10) == 1
dm = 0.01;
else
dm = 0;
end
% Damage cost function
Damage = (1 - dm)/((1 + sai2temp * (Wm4 * S4(2)) ^ 2 + sai2ocean * (S4(5) - 1094) ^ 2 + sai2atmos * (S4(4) - 596.4) ^ 2) * (1 + nuG * g4 ^ 2));
Dam = 1 - Damage;
% Abatement cost function
Abate = theta1(t4) * a4 ^ theta2;
% Geoengineering cost function
%Geoengineer = Gcoeff * theta1(t4) * g4 ^ theta3;
Geoengineer = Gcoeff * thetaGE * g4 ^ theta3;
% Net output after damage and abatement
Q = (1 - (Dam + Abate + Geoengineer)) * S4(7);
% Consumption
C = (1 - 0.22) * Q;
% Consumption per capita
c = C / L(t4) * 1000;
% Utility per capita
u = 1 + c ^ (1 - alpha) / (1 - alpha);
% Social utility
U = u * L(t4) * 10;
end
|
github
|
PSLmodels/Geo-DICE-master
|
Utility.m
|
.m
|
Geo-DICE-master/SGEUPC/Utility.m
| 1,448 |
utf_8
|
b544380a9a72033fabc965a1f78de0f6
|
%Algorithm for calculating the social utility of each state under ceratin
%action (a3)
function [ U ] = Utility( S4, a4, g4, Wm4, t4)
%Social Utility for a given state St
% state = S4
% action = a4, g4
% time = t4
global theta1 theta2 theta3 L alpha Gcoeff deltarf Fex etha1
global thetaGE sai2temp sai2ocean sai2atmos nuG TP Geffective
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Radiative Forcings change due to GE
RF0 = S4(9);
S4(9) = (deltarf * ((log(S4(4)) - log(596.4)) / log(2)) + Fex(t4)) * (1 - Geffective * g4);
%Atmospheric Temperature change due to GE
S4(2) = S4(2) + etha1 * (S4(9) - RF0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Damage cost function
if TP == 7 && S4(10) == 1
dm = 0.01;
else
dm = 0;
end
Damage = (1 - dm)/((1 + sai2temp * (Wm4 * S4(2)) ^ 2 + sai2ocean * (S4(5) - 1094) ^ 2 + sai2atmos * (S4(4) - 596.4) ^ 2) * (1 + nuG * g4 ^ 2));
Dam = 1 - Damage;
% Abatement cost function
Abate = theta1(t4) * a4 ^ theta2;
% Geoengineering cost function
%Geoengineer = Gcoeff * theta1(t4) * g4 ^ theta3;
Geoengineer = Gcoeff * thetaGE * g4 ^ theta3;
% Net output after damage and abatement
Q = (1 - (Dam + Abate + Geoengineer)) * S4(7);
% Consumption
C = (1 - 0.22) * Q;
% Consumption per capita
c = C / L(t4) * 1000;
% Utility per capita
u = 1 + c ^ (1 - alpha) / (1 - alpha);
% Social utility
U = u * L(t4) * 10;
end
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/Unsolved/linear regression/ex1/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/Unsolved/linear regression/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/Unsolved/linear regression/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/Unsolved/linear regression/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/Unsolved/linear regression/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/Unsolved/handwriting recognition/ex3/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/Unsolved/handwriting recognition/ex3/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/Unsolved/handwriting recognition/ex3/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/Unsolved/handwriting recognition/ex3/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/Unsolved/handwriting recognition/ex3/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/Unsolved/logistic regression/ex2/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/Unsolved/logistic regression/ex2/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/Unsolved/logistic regression/ex2/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/Unsolved/logistic regression/ex2/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/Unsolved/logistic regression/ex2/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submit.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/submit.m
| 2,064 |
utf_8
|
7c4fcf60df3a7e09d05a74f7772fed3b
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'anomaly-detection-and-recommender-systems';
conf.itemName = 'Anomaly Detection and Recommender Systems';
conf.partArrays = { ...
{ ...
'1', ...
{ 'estimateGaussian.m' }, ...
'Estimate Gaussian Parameters', ...
}, ...
{ ...
'2', ...
{ 'selectThreshold.m' }, ...
'Select Threshold', ...
}, ...
{ ...
'3', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Cost', ...
}, ...
{ ...
'4', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Gradient', ...
}, ...
{ ...
'5', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Cost', ...
}, ...
{ ...
'6', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
n_u = 3; n_m = 4; n = 5;
X = reshape(sin(1:n_m*n), n_m, n);
Theta = reshape(cos(1:n_u*n), n_u, n);
Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
R = Y > 0.5;
pval = [abs(Y(:)) ; 0.001; 1];
yval = [R(:) ; 1; 0];
params = [X(:); Theta(:)];
if partId == '1'
[mu sigma2] = estimateGaussian(X);
out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
elseif partId == '2'
[bestEpsilon bestF1] = selectThreshold(yval, pval);
out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
elseif partId == '3'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', J(:));
elseif partId == '4'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', grad(:));
elseif partId == '5'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', J(:));
elseif partId == '6'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', grad(:));
end
end
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/Unsolved/Anomaly Detection and Recommender
Systems/ex8/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/solved/linear regression/ex1/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/solved/linear regression/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/solved/linear regression/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/solved/linear regression/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/solved/linear regression/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submit.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/submit.m
| 2,064 |
utf_8
|
7c4fcf60df3a7e09d05a74f7772fed3b
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'anomaly-detection-and-recommender-systems';
conf.itemName = 'Anomaly Detection and Recommender Systems';
conf.partArrays = { ...
{ ...
'1', ...
{ 'estimateGaussian.m' }, ...
'Estimate Gaussian Parameters', ...
}, ...
{ ...
'2', ...
{ 'selectThreshold.m' }, ...
'Select Threshold', ...
}, ...
{ ...
'3', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Cost', ...
}, ...
{ ...
'4', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Gradient', ...
}, ...
{ ...
'5', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Cost', ...
}, ...
{ ...
'6', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
n_u = 3; n_m = 4; n = 5;
X = reshape(sin(1:n_m*n), n_m, n);
Theta = reshape(cos(1:n_u*n), n_u, n);
Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
R = Y > 0.5;
pval = [abs(Y(:)) ; 0.001; 1];
yval = [R(:) ; 1; 0];
params = [X(:); Theta(:)];
if partId == '1'
[mu sigma2] = estimateGaussian(X);
out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
elseif partId == '2'
[bestEpsilon bestF1] = selectThreshold(yval, pval);
out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
elseif partId == '3'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', J(:));
elseif partId == '4'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', grad(:));
elseif partId == '5'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', J(:));
elseif partId == '6'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', grad(:));
end
end
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/solved/anomaly detection and reccomendor system/ex8/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submit.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/submit.m
| 1,567 |
utf_8
|
1dba733a05282b2db9f2284548483b81
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'multi-class-classification-and-neural-networks';
conf.itemName = 'Multi-class Classification and Neural Networks';
conf.partArrays = { ...
{ ...
'1', ...
{ 'lrCostFunction.m' }, ...
'Regularized Logistic Regression', ...
}, ...
{ ...
'2', ...
{ 'oneVsAll.m' }, ...
'One-vs-All Classifier Training', ...
}, ...
{ ...
'3', ...
{ 'predictOneVsAll.m' }, ...
'One-vs-All Classifier Prediction', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Neural Network Prediction Function' ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxdata)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...
1 1 ; 1 2 ; 2 1 ; 2 2 ; ...
-1 1 ; -1 2 ; -2 1 ; -2 2 ; ...
1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];
ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
if partId == '1'
[J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == '2'
out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));
elseif partId == '3'
out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));
elseif partId == '4'
out = sprintf('%0.5f ', predict(t1, t2, Xm));
end
end
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/solved/handwriting recognition/ex3/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
uday1201/MLworkshop-master
|
submit.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/submit.m
| 1,605 |
utf_8
|
9b63d386e9bd7bcca66b1a3d2fa37579
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'logistic-regression';
conf.itemName = 'Logistic Regression';
conf.partArrays = { ...
{ ...
'1', ...
{ 'sigmoid.m' }, ...
'Sigmoid Function', ...
}, ...
{ ...
'2', ...
{ 'costFunction.m' }, ...
'Logistic Regression Cost', ...
}, ...
{ ...
'3', ...
{ 'costFunction.m' }, ...
'Logistic Regression Gradient', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Predict', ...
}, ...
{ ...
'5', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Cost', ...
}, ...
{ ...
'6', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
if partId == '1'
out = sprintf('%0.5f ', sigmoid(X));
elseif partId == '2'
out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y));
elseif partId == '3'
[cost, grad] = costFunction([0.25 0.5 -0.5]', X, y);
out = sprintf('%0.5f ', grad);
elseif partId == '4'
out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X));
elseif partId == '5'
out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1));
elseif partId == '6'
[cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', grad);
end
end
|
github
|
uday1201/MLworkshop-master
|
submitWithConfiguration.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
uday1201/MLworkshop-master
|
savejson.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
uday1201/MLworkshop-master
|
loadjson.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
loadubjson.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
uday1201/MLworkshop-master
|
saveubjson.m
|
.m
|
MLworkshop-master/solved/logistic regression/ex2/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
marcotcr/BlackBoxAuditing-master
|
SLIMCoefficientConstraints.m
|
.m
|
BlackBoxAuditing-master/MATLAB_code/src/SLIMCoefficientConstraints.m
| 17,125 |
utf_8
|
d66e1a62518673dd6497f25601e4c046
|
classdef SLIMCoefficientConstraints
%Helper class to store, access, and change information used for
%coefficients in a SLIM model.
%
%Fields include:
%
%variable_name: names of each feature, X_1...X_d by default
%
%ub: upperbound on coefficient set, 10 by default
%
%lb: lowerbound on coefficient set, -10 by default
%
%type: type of coefficient, 'integer' by default
% if 'integer' then coefficient will take on integer values in [lb,ub]
% if 'custom' then coefficient will take any value specified in 'values'
%
%values: values that can be taken by a 'custom' coefficient, empty by default
%
%sign: sign of the coefficient set, =0 by default
% -1 means coefficient is restricted to negative values
% 1 means coefficient is restricted to positive values
% 0 means coefficient can take on positive/negative values
%
% setting sign will override conflicts with lb/ub/values field,
% so if [lb,ub] = [-10,10] and we set sign to 1, then [lb,ub] will change to [0,10]
%
%C_0j: custom sparsity parameter, NaN by default
% must be either NaN or a value in [0,1]
% C_0j represents the minimum % accuracy that feature j must add
% in order to be included in the SLIM classifier (i.e. have a non-zero
% coefficient
%
%Author: Berk Ustun | [email protected] | www.berkustun.com
%Reference: SLIM for Optimized Medical Scoring Systems, http://arxiv.org/abs/1502.04269
%Repository: <a href="matlab: web('https://github.com/ustunb/slim_for_matlab')">slim_for_matlab</a>
properties(Access=private)
constraintArray;
n_variables;
end
properties(Dependent)
variable_name
ub
lb
type
values
sign
C_0j
end
methods
%% Constructor to create new coefConstraints object
function obj = SLIMCoefficientConstraints(varargin)
if nargin > 0
if nargin == 1 && isnumeric(varargin{1})
obj.n_variables = varargin{1};
variable_names = arrayfun(@(j) sprintf('X_%d',j), 1:obj.n_variables, 'UniformOutput', false);
elseif nargin == 1 && iscell(varargin{1})
variable_names = varargin{1};
obj.n_variables = length(variable_names);
end
varargin
tmpArray = cellfun(@(n) SLIMCoefficientFields(n), variable_names, 'UniformOutput', false);
obj.constraintArray = [tmpArray{:}];
obj.checkRep()
end
end
%% Native Getter Methods
function variable_name = get.variable_name(obj)
variable_name = {obj.constraintArray(:).variable_name}';
end
function ub = get.ub(obj)
ub = [obj.constraintArray(:).ub]';
end
function lb = get.lb(obj)
lb = [obj.constraintArray(:).lb]';
end
function sign = get.sign(obj)
sign = [obj.constraintArray(:).sign]';
end
function C_0j = get.C_0j(obj)
C_0j = [obj.constraintArray(:).C_0j]';
end
function type = get.type(obj)
type = {obj.constraintArray(:).type}';
end
function values = get.values(obj)
values = {obj.constraintArray(:).values}';
end
%% Native Setter Methods
function obj = set.variable_name(obj, new_name)
if ischar(new_name)
new_name = {new_name};
end
if length(new_name)==1
new_name = repmat(new_name, obj.n_variables, 1);
else
assert(length(new_name)==length(obj.constraintArray))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).variable_name = new_name{i};
end
obj.checkRep()
end
function obj = set.values(obj, new_values)
if isnumeric(new_values)
new_values = {new_values};
end
if length(new_values)==1
new_values = repmat(new_values, obj.n_variables, 1);
else
assert(length(new_values)==length(obj.constraintArray),...
sprintf('new values must have length = 1 or %d', obj.n_variables))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).values = new_values{i};
end
obj.checkRep()
end
function obj = set.type(obj, new_type)
if length(new_type)==1
new_type = repmat(new_type, obj.n_variables, 1);
else
assert(length(new_type)==length(obj.constraintArray),...
sprintf('new type must have length = 1 or %d', obj.n_variables))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).type = new_type(i);
end
obj.checkRep()
end
function obj = set.ub(obj, new_ub)
if length(new_ub)==1
new_ub = repmat(new_ub, obj.n_variables, 1);
else
assert(length(new_ub)==length(obj.constraintArray),...
sprintf('new ub values must have length = 1 or %d', obj.n_variables))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).ub = new_ub(i);
end
obj.checkRep()
end
function obj = set.lb(obj, new_lb)
if length(new_lb)==1
new_lb = repmat(new_lb, obj.n_variables, 1);
else
assert(length(new_lb)==length(obj.constraintArray))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).lb = new_lb(i);
end
obj.checkRep()
end
function obj = set.sign(obj, new_sign)
if length(new_sign)==1
new_sign = repmat(new_sign, obj.n_variables, 1);
else
assert(length(new_sign)==length(obj.constraintArray))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).sign = new_sign(i);
end
obj.checkRep()
end
function obj = set.C_0j(obj, new_C_0j)
if length(new_C_0j)==1
new_C_0j = repmat(new_C_0j, obj.n_variables, 1);
else
assert(length(new_C_0j)==length(obj.constraintArray))
end
for i = 1:length(obj.constraintArray)
obj.constraintArray(i).C_0j = new_C_0j(i);
end
obj.checkRep()
end
%% Name-Based Getter/Setter Methods
function field_values = getfield(obj, varargin)
%Get field values for one or more variables
%
%variable_names names of the variables for which the field_name will be set to field_value
% can either be a single char or a cell array of strings
% all variable names must match the variable_name field of the SLIMCoefficientConstraint object
%
%field_name any field name of a SLIMCoefficientConstraints object
if nargin == 2
variable_names = obj.variable_name;
field_name = varargin{1};
elseif nargin == 3
variable_names = varargin{1};
field_name = varargin{2};
else
error('invalid number of inputs')
end
assert(sum(strcmp(field_name,{'variable_name','lb','ub','type','values','sign','C_0j'}))==1, ....
'field name must be: variable_name, lb, ub, values, type, sign, C_0j');
if ischar(variable_names)
variable_names = {variable_names};
end
current_names = obj.variable_name;
variable_names = unique(variable_names, 'stable');
valid_name_ind = ismember(variable_names, current_names, 'legacy');
valid_names = variable_names(valid_name_ind);
if any(~valid_name_ind)
invalid_names = variable_names(~valid_name_ind);
error_msg = sprintf('could not find variable matching name: %s\n', invalid_names{:});
error_msg = error_msg(1:end-1); %remove last \n
error(error_msg);
end
switch field_name
case {'variable_name', 'type', 'values'}
field_values = cell(length(valid_names),1);
counter = 1;
for i = 1:length(valid_names)
ind = find(strcmp(current_names, valid_names{i}));
for j = 1:length(ind)
field_values(counter) = {obj.constraintArray(ind(j)).(field_name)};
counter = counter + 1;
end
end
if length(field_values)==1
field_values = field_values{1};
end
otherwise
field_values = nan(length(valid_names),1);
counter = 1;
for i = 1:length(valid_names)
ind = find(strcmp(current_names, valid_names{i}));
for j = 1:length(ind)
field_values(counter) = obj.constraintArray(ind(j)).(field_name);
counter = counter + 1;
end
end
end
obj.checkRep()
end
function obj = setfield(obj, varargin)
%Set the field value for one or more variables
%
%variable_names names of the variables for which the field_name will be set to field_value
% can either be a single char or a cell array of strings
% all variable names must match the variable_name field of the SLIMCoefficientConstraint object
%
%
%field_name limited to be 'variable_name','lb','ub','values','sign','C_0j'
%
%field_value limited to valid values of the fields above
if nargin == 3
variable_names = obj.variable_name;
field_name = varargin{1};
field_value = varargin{2};
elseif nargin == 4
variable_names = varargin{1};
field_name = varargin{2};
field_value = varargin{3};
else
error('invalid number of inputs')
end
assert(sum(strcmp(field_name,{'variable_name','lb','ub','values','sign','C_0j'}))==1, ....
'field name must be: variable_name, lb,ub, values, sign, C_0j');
if ischar(variable_names)
variable_names = {variable_names};
end
current_names = obj.variable_name;
variable_names = unique(variable_names, 'stable');
valid_name_ind = ismember(variable_names, current_names, 'legacy');
valid_names = variable_names(valid_name_ind);
if any(~valid_name_ind)
invalid_names = variable_names(~valid_name_ind);
error_msg = sprintf('could not find variable matching name: %s\n', invalid_names{:});
error_msg = error_msg(1:end-1); %remove last \n
error(error_msg);
end
for i = 1:length(valid_names)
ind = find(strcmp(current_names, valid_names{i}));
for j = 1:length(ind)
obj.constraintArray(ind(j)).(field_name) = field_value;
end
end
obj.checkRep()
end
%% Display, Warnings and CheckRep
function print_warning(obj, msg)
warning('SLIM:ConstraintWarning', msg);
end
function disp(obj)
headers = {'variable_name','type','lb','ub','sign','values','C_0j'};
info = [...
obj.variable_name, ...
obj.type, ...
num2cell(obj.lb), ...
num2cell(obj.ub), ...
num2cell(int8(obj.sign)), ...
obj.values, ...
num2cell(obj.C_0j)...
];
coefTable = [headers;info];
disp(coefTable)
end
function n = numel(obj)
n = obj.n_variables;
end
function checkRep(obj)
assert(obj.n_variables>0, 'need at least 1 variable');
%check sizes
assert(length(obj.variable_name)==obj.n_variables, sprintf('variable_name field should have exactly %d entries', obj.n_variables));
assert(length(obj.ub)==obj.n_variables, sprintf('ub field should have exactly %d entries', obj.n_variables));
assert(length(obj.lb)==obj.n_variables, sprintf('ub field should have exactly %d entries', obj.n_variables));
assert(length(obj.C_0j)==obj.n_variables, sprintf('C_0j field should have exactly %d entries', obj.n_variables));
assert(length(obj.sign)==obj.n_variables, sprintf('sign field should have exactly %d entries', obj.n_variables));
assert(length(obj.type)==obj.n_variables, sprintf('type field should have exactly %d entries', obj.n_variables));
assert(length(obj.values)==obj.n_variables, sprintf('values field should have exactly %d entries', obj.n_variables));
%check types
assert(iscell(obj.variable_name), 'variable_name field should be a cell');
assert(iscell(obj.type), 'type field should be a cell');
assert(iscell(obj.values), 'values field should be a cell');
assert(isnumeric(obj.ub), 'ub field should be a array');
assert(isnumeric(obj.lb), 'lb field should be a array');
assert(isnumeric(obj.C_0j), 'C_0j field should be a array');
assert(isnumeric(obj.sign), 'sign field should be a array');
%check entries
assert(all(cellfun(@(x) ~isempty(x), obj.variable_name)), 'each variable_names entry should be non-empty');
assert(all(strcmp('integer',obj.type)| strcmp('custom',obj.type)),'type must be *integer* or *custom*');
assert(all(obj.C_0j<=1 | obj.C_0j>=0 | isnan(obj.C_0j)), 'each C_0j entry should be between 0 and 1 or NaN');
assert(all(obj.sign==0 | obj.sign==1 | obj.sign==-1), 'sign must either be -1,0,1');
%check ub/lb
assert(all(obj.ub >= obj.lb), 'ub should be > lb for each coefficient');
pos_sign = obj.sign==1;
neg_sign = obj.sign==-1;
%no_sign == obj.sign==0;
assert(all(obj.ub(neg_sign)<=0), 'ub <= for any coefficient s.t. sign == - 1');
assert(all(obj.lb(pos_sign)>=0), 'lb <= for any coefficient s.t. sign == - 1');
custom_ind = strcmp('custom', obj.type);
if any(custom_ind)
assert(all(cellfun(@(x) ~isempty(x), obj.values(custom_ind), 'UniformOutput', true)), 'if coefficient uses custom set of values, then values field must be non-empty and non-NaN');
end
end
end
end
%% Helper Functions
%apply a function to each entry of a cell/numeric array
%returns numeric array containing function output
function values = apply(f, entries)
assert(isa(f,'function_handle'), 'first input needs to be a function handle')
assert(iscell(entries)||isnumeric(entries), 'second input needs to be cell array or numeric array')
n = length(entries);
if iscell(entries)
values = cellfun(f, entries, 'UniformOutput', false);
elseif isnumeric(entries)
values = arrayfun(f, entries, 'UniformOutput', true);
end
end
|
github
|
kartik-nighania/Coursera-Machine-Learning-Course-by-Stanford-master
|
submit.m
|
.m
|
Coursera-Machine-Learning-Course-by-Stanford-master/5 bias vs variance linear regression/ex5/submit.m
| 1,765 |
utf_8
|
b1804fe5854d9744dca981d250eda251
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance';
conf.itemName = 'Regularized Linear Regression and Bias/Variance';
conf.partArrays = { ...
{ ...
'1', ...
{ 'linearRegCostFunction.m' }, ...
'Regularized Linear Regression Cost Function', ...
}, ...
{ ...
'2', ...
{ 'linearRegCostFunction.m' }, ...
'Regularized Linear Regression Gradient', ...
}, ...
{ ...
'3', ...
{ 'learningCurve.m' }, ...
'Learning Curve', ...
}, ...
{ ...
'4', ...
{ 'polyFeatures.m' }, ...
'Polynomial Feature Mapping', ...
}, ...
{ ...
'5', ...
{ 'validationCurve.m' }, ...
'Validation Curve', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)'];
y = sin(1:3:30)';
Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)'];
yval = sin(1:10)';
if partId == '1'
[J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', J);
elseif partId == '2'
[J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', grad);
elseif partId == '3'
[error_train, error_val] = ...
learningCurve(X, y, Xval, yval, 1);
out = sprintf('%0.5f ', [error_train(:); error_val(:)]);
elseif partId == '4'
[X_poly] = polyFeatures(X(2,:)', 8);
out = sprintf('%0.5f ', X_poly);
elseif partId == '5'
[lambda_vec, error_train, error_val] = ...
validationCurve(X, y, Xval, yval);
out = sprintf('%0.5f ', ...
[lambda_vec(:); error_train(:); error_val(:)]);
end
end
|
github
|
kartik-nighania/Coursera-Machine-Learning-Course-by-Stanford-master
|
submitWithConfiguration.m
|
.m
|
Coursera-Machine-Learning-Course-by-Stanford-master/5 bias vs variance linear regression/ex5/lib/submitWithConfiguration.m
| 3,734 |
utf_8
|
84d9a81848f6d00a7aff4f79bdbb6049
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
kartik-nighania/Coursera-Machine-Learning-Course-by-Stanford-master
|
savejson.m
|
.m
|
Coursera-Machine-Learning-Course-by-Stanford-master/5 bias vs variance linear regression/ex5/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
kartik-nighania/Coursera-Machine-Learning-Course-by-Stanford-master
|
loadjson.m
|
.m
|
Coursera-Machine-Learning-Course-by-Stanford-master/5 bias vs variance linear regression/ex5/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.