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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/submit.m
| 1,318 |
utf_8
|
bfa0b4ffb8a7854d8e84276e91818107
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'support-vector-machines';
conf.itemName = 'Support Vector Machines';
conf.partArrays = { ...
{ ...
'1', ...
{ 'gaussianKernel.m' }, ...
'Gaussian Kernel', ...
}, ...
{ ...
'2', ...
{ 'dataset3Params.m' }, ...
'Parameters (C, sigma) for Dataset 3', ...
}, ...
{ ...
'3', ...
{ 'processEmail.m' }, ...
'Email Preprocessing', ...
}, ...
{ ...
'4', ...
{ 'emailFeatures.m' }, ...
'Email Feature Extraction', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
x1 = sin(1:10)';
x2 = cos(1:10)';
ec = 'the quick brown fox jumped over the lazy dog';
wi = 1 + abs(round(x1 * 1863));
wi = [wi ; wi];
if partId == '1'
sim = gaussianKernel(x1, x2, 2);
out = sprintf('%0.5f ', sim);
elseif partId == '2'
load('ex6data3.mat');
[C, sigma] = dataset3Params(X, y, Xval, yval);
out = sprintf('%0.5f ', C);
out = [out sprintf('%0.5f ', sigma)];
elseif partId == '3'
word_indices = processEmail(ec);
out = sprintf('%d ', word_indices);
elseif partId == '4'
x = emailFeatures(wi);
out = sprintf('%d ', x);
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
porterStemmer.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/porterStemmer.m
| 9,902 |
utf_8
|
7ed5acd925808fde342fc72bd62ebc4d
|
function stem = porterStemmer(inString)
% Applies the Porter Stemming algorithm as presented in the following
% paper:
% Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
% no. 3, pp 130-137
% Original code modeled after the C version provided at:
% http://www.tartarus.org/~martin/PorterStemmer/c.txt
% The main part of the stemming algorithm starts here. b is an array of
% characters, holding the word to be stemmed. The letters are in b[k0],
% b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since
% matlab begins indexing by 1 instead of 0). k is readjusted downwards as
% the stemming progresses. Zero termination is not in fact used in the
% algorithm.
% To call this function, use the string to be stemmed as the input
% argument. This function returns the stemmed word as a string.
% Lower-case string
inString = lower(inString);
global j;
b = inString;
k = length(b);
k0 = 1;
j = k;
% With this if statement, strings of length 1 or 2 don't go through the
% stemming process. Remove this conditional to match the published
% algorithm.
stem = b;
if k > 2
% Output displays per step are commented out.
%disp(sprintf('Word to stem: %s', b));
x = step1ab(b, k, k0);
%disp(sprintf('Steps 1A and B yield: %s', x{1}));
x = step1c(x{1}, x{2}, k0);
%disp(sprintf('Step 1C yields: %s', x{1}));
x = step2(x{1}, x{2}, k0);
%disp(sprintf('Step 2 yields: %s', x{1}));
x = step3(x{1}, x{2}, k0);
%disp(sprintf('Step 3 yields: %s', x{1}));
x = step4(x{1}, x{2}, k0);
%disp(sprintf('Step 4 yields: %s', x{1}));
x = step5(x{1}, x{2}, k0);
%disp(sprintf('Step 5 yields: %s', x{1}));
stem = x{1};
end
% cons(j) is TRUE <=> b[j] is a consonant.
function c = cons(i, b, k0)
c = true;
switch(b(i))
case {'a', 'e', 'i', 'o', 'u'}
c = false;
case 'y'
if i == k0
c = true;
else
c = ~cons(i - 1, b, k0);
end
end
% mseq() measures the number of consonant sequences between k0 and j. If
% c is a consonant sequence and v a vowel sequence, and <..> indicates
% arbitrary presence,
% <c><v> gives 0
% <c>vc<v> gives 1
% <c>vcvc<v> gives 2
% <c>vcvcvc<v> gives 3
% ....
function n = measure(b, k0)
global j;
n = 0;
i = k0;
while true
if i > j
return
end
if ~cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
while true
while true
if i > j
return
end
if cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
n = n + 1;
while true
if i > j
return
end
if ~cons(i, b, k0)
break;
end
i = i + 1;
end
i = i + 1;
end
% vowelinstem() is TRUE <=> k0,...j contains a vowel
function vis = vowelinstem(b, k0)
global j;
for i = k0:j,
if ~cons(i, b, k0)
vis = true;
return
end
end
vis = false;
%doublec(i) is TRUE <=> i,(i-1) contain a double consonant.
function dc = doublec(i, b, k0)
if i < k0+1
dc = false;
return
end
if b(i) ~= b(i-1)
dc = false;
return
end
dc = cons(i, b, k0);
% cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant
% and also if the second c is not w,x or y. this is used when trying to
% restore an e at the end of a short word. e.g.
%
% cav(e), lov(e), hop(e), crim(e), but
% snow, box, tray.
function c1 = cvc(i, b, k0)
if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0))
c1 = false;
else
if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y')
c1 = false;
return
end
c1 = true;
end
% ends(s) is TRUE <=> k0,...k ends with the string s.
function s = ends(str, b, k)
global j;
if (str(length(str)) ~= b(k))
s = false;
return
end % tiny speed-up
if (length(str) > k)
s = false;
return
end
if strcmp(b(k-length(str)+1:k), str)
s = true;
j = k - length(str);
return
else
s = false;
end
% setto(s) sets (j+1),...k to the characters in the string s, readjusting
% k accordingly.
function so = setto(s, b, k)
global j;
for i = j+1:(j+length(s))
b(i) = s(i-j);
end
if k > j+length(s)
b((j+length(s)+1):k) = '';
end
k = length(b);
so = {b, k};
% rs(s) is used further down.
% [Note: possible null/value for r if rs is called]
function r = rs(str, b, k, k0)
r = {b, k};
if measure(b, k0) > 0
r = setto(str, b, k);
end
% step1ab() gets rid of plurals and -ed or -ing. e.g.
% caresses -> caress
% ponies -> poni
% ties -> ti
% caress -> caress
% cats -> cat
% feed -> feed
% agreed -> agree
% disabled -> disable
% matting -> mat
% mating -> mate
% meeting -> meet
% milling -> mill
% messing -> mess
% meetings -> meet
function s1ab = step1ab(b, k, k0)
global j;
if b(k) == 's'
if ends('sses', b, k)
k = k-2;
elseif ends('ies', b, k)
retVal = setto('i', b, k);
b = retVal{1};
k = retVal{2};
elseif (b(k-1) ~= 's')
k = k-1;
end
end
if ends('eed', b, k)
if measure(b, k0) > 0;
k = k-1;
end
elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0)
k = j;
retVal = {b, k};
if ends('at', b, k)
retVal = setto('ate', b(k0:k), k);
elseif ends('bl', b, k)
retVal = setto('ble', b(k0:k), k);
elseif ends('iz', b, k)
retVal = setto('ize', b(k0:k), k);
elseif doublec(k, b, k0)
retVal = {b, k-1};
if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ...
b(retVal{2}) == 'z'
retVal = {retVal{1}, retVal{2}+1};
end
elseif measure(b, k0) == 1 && cvc(k, b, k0)
retVal = setto('e', b(k0:k), k);
end
k = retVal{2};
b = retVal{1}(k0:k);
end
j = k;
s1ab = {b(k0:k), k};
% step1c() turns terminal y to i when there is another vowel in the stem.
function s1c = step1c(b, k, k0)
global j;
if ends('y', b, k) && vowelinstem(b, k0)
b(k) = 'i';
end
j = k;
s1c = {b, k};
% step2() maps double suffices to single ones. so -ization ( = -ize plus
% -ation) maps to -ize etc. note that the string before the suffix must give
% m() > 0.
function s2 = step2(b, k, k0)
global j;
s2 = {b, k};
switch b(k-1)
case {'a'}
if ends('ational', b, k) s2 = rs('ate', b, k, k0);
elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end;
case {'c'}
if ends('enci', b, k) s2 = rs('ence', b, k, k0);
elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end;
case {'e'}
if ends('izer', b, k) s2 = rs('ize', b, k, k0); end;
case {'l'}
if ends('bli', b, k) s2 = rs('ble', b, k, k0);
elseif ends('alli', b, k) s2 = rs('al', b, k, k0);
elseif ends('entli', b, k) s2 = rs('ent', b, k, k0);
elseif ends('eli', b, k) s2 = rs('e', b, k, k0);
elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end;
case {'o'}
if ends('ization', b, k) s2 = rs('ize', b, k, k0);
elseif ends('ation', b, k) s2 = rs('ate', b, k, k0);
elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end;
case {'s'}
if ends('alism', b, k) s2 = rs('al', b, k, k0);
elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0);
elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0);
elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end;
case {'t'}
if ends('aliti', b, k) s2 = rs('al', b, k, k0);
elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0);
elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end;
case {'g'}
if ends('logi', b, k) s2 = rs('log', b, k, k0); end;
end
j = s2{2};
% step3() deals with -ic-, -full, -ness etc. similar strategy to step2.
function s3 = step3(b, k, k0)
global j;
s3 = {b, k};
switch b(k)
case {'e'}
if ends('icate', b, k) s3 = rs('ic', b, k, k0);
elseif ends('ative', b, k) s3 = rs('', b, k, k0);
elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end;
case {'i'}
if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end;
case {'l'}
if ends('ical', b, k) s3 = rs('ic', b, k, k0);
elseif ends('ful', b, k) s3 = rs('', b, k, k0); end;
case {'s'}
if ends('ness', b, k) s3 = rs('', b, k, k0); end;
end
j = s3{2};
% step4() takes off -ant, -ence etc., in context <c>vcvc<v>.
function s4 = step4(b, k, k0)
global j;
switch b(k-1)
case {'a'}
if ends('al', b, k) end;
case {'c'}
if ends('ance', b, k)
elseif ends('ence', b, k) end;
case {'e'}
if ends('er', b, k) end;
case {'i'}
if ends('ic', b, k) end;
case {'l'}
if ends('able', b, k)
elseif ends('ible', b, k) end;
case {'n'}
if ends('ant', b, k)
elseif ends('ement', b, k)
elseif ends('ment', b, k)
elseif ends('ent', b, k) end;
case {'o'}
if ends('ion', b, k)
if j == 0
elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t'))
j = k;
end
elseif ends('ou', b, k) end;
case {'s'}
if ends('ism', b, k) end;
case {'t'}
if ends('ate', b, k)
elseif ends('iti', b, k) end;
case {'u'}
if ends('ous', b, k) end;
case {'v'}
if ends('ive', b, k) end;
case {'z'}
if ends('ize', b, k) end;
end
if measure(b, k0) > 1
s4 = {b(k0:j), j};
else
s4 = {b(k0:k), k};
end
% step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1.
function s5 = step5(b, k, k0)
global j;
j = k;
if b(k) == 'e'
a = measure(b, k0);
if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0))
k = k-1;
end
end
if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1)
k = k-1;
end
s5 = {b(k0:k), k};
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex6/ex6/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/submit.m
| 1,438 |
utf_8
|
665ea5906aad3ccfd94e33a40c58e2ce
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'k-means-clustering-and-pca';
conf.itemName = 'K-Means Clustering and PCA';
conf.partArrays = { ...
{ ...
'1', ...
{ 'findClosestCentroids.m' }, ...
'Find Closest Centroids (k-Means)', ...
}, ...
{ ...
'2', ...
{ 'computeCentroids.m' }, ...
'Compute Centroid Means (k-Means)', ...
}, ...
{ ...
'3', ...
{ 'pca.m' }, ...
'PCA', ...
}, ...
{ ...
'4', ...
{ 'projectData.m' }, ...
'Project Data (PCA)', ...
}, ...
{ ...
'5', ...
{ 'recoverData.m' }, ...
'Recover Data (PCA)', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
X = reshape(sin(1:165), 15, 11);
Z = reshape(cos(1:121), 11, 11);
C = Z(1:5, :);
idx = (1 + mod(1:15, 3))';
if partId == '1'
idx = findClosestCentroids(X, C);
out = sprintf('%0.5f ', idx(:));
elseif partId == '2'
centroids = computeCentroids(X, idx, 3);
out = sprintf('%0.5f ', centroids(:));
elseif partId == '3'
[U, S] = pca(X);
out = sprintf('%0.5f ', abs([U(:); S(:)]));
elseif partId == '4'
X_proj = projectData(X, Z, 5);
out = sprintf('%0.5f ', X_proj(:));
elseif partId == '5'
X_rec = recoverData(X(:,1:5), Z, 5);
out = sprintf('%0.5f ', X_rec(:));
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex7/ex7/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/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
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/ex5/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex5/ex5/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/ex3/submit.m
| 1,567 |
utf_8
|
1dba733a05282b2db9f2284548483b81
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'multi-class-classification-and-neural-networks';
conf.itemName = 'Multi-class Classification and Neural Networks';
conf.partArrays = { ...
{ ...
'1', ...
{ 'lrCostFunction.m' }, ...
'Regularized Logistic Regression', ...
}, ...
{ ...
'2', ...
{ 'oneVsAll.m' }, ...
'One-vs-All Classifier Training', ...
}, ...
{ ...
'3', ...
{ 'predictOneVsAll.m' }, ...
'One-vs-All Classifier Prediction', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Neural Network Prediction Function' ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxdata)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...
1 1 ; 1 2 ; 2 1 ; 2 2 ; ...
-1 1 ; -1 2 ; -2 1 ; -2 2 ; ...
1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];
ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
if partId == '1'
[J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == '2'
out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));
elseif partId == '3'
out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));
elseif partId == '4'
out = sprintf('%0.5f ', predict(t1, t2, Xm));
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/ex3/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/ex3/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/ex3/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex3/ex3/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/ex8/submit.m
| 2,135 |
utf_8
|
eebb8c0a1db5a4df20b4c858603efad6
|
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];
Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed
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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex8/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submit.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/ex1/submit.m
| 1,876 |
utf_8
|
8d1c467b830a89c187c05b121cb8fbfd
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'linear-regression';
conf.itemName = 'Linear Regression with Multiple Variables';
conf.partArrays = { ...
{ ...
'1', ...
{ 'warmUpExercise.m' }, ...
'Warm-up Exercise', ...
}, ...
{ ...
'2', ...
{ 'computeCost.m' }, ...
'Computing Cost (for One Variable)', ...
}, ...
{ ...
'3', ...
{ 'gradientDescent.m' }, ...
'Gradient Descent (for One Variable)', ...
}, ...
{ ...
'4', ...
{ 'featureNormalize.m' }, ...
'Feature Normalization', ...
}, ...
{ ...
'5', ...
{ 'computeCostMulti.m' }, ...
'Computing Cost (for Multiple Variables)', ...
}, ...
{ ...
'6', ...
{ 'gradientDescentMulti.m' }, ...
'Gradient Descent (for Multiple Variables)', ...
}, ...
{ ...
'7', ...
{ 'normalEqn.m' }, ...
'Normal Equations', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId)
% Random Test Cases
X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
Y2 = Y1.^0.5 + Y1;
if partId == '1'
out = sprintf('%0.5f ', warmUpExercise());
elseif partId == '2'
out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
elseif partId == '3'
out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));
elseif partId == '4'
out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
elseif partId == '5'
out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));
elseif partId == '6'
out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));
elseif partId == '7'
out = sprintf('%0.5f ', normalEqn(X2, Y2));
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
submitWithConfiguration.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/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
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
savejson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
loadubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
|
saveubjson.m
|
.m
|
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex1/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
devraj89/Canonical-Correlation-and-its-Variants-master
|
cca.m
|
.m
|
Canonical-Correlation-and-its-Variants-master/cca.m
| 1,404 |
utf_8
|
ade088dc6e270b320ffa9c6a7b7c01ab
|
% Modified version from David R. Hardoon
%
% http://www.davidroihardoon.com/Professional/Code_files/cca.m
%
% @article{hardoon:cca,
% author = {Hardoon, David and Szedmak, Sandor and {Shawe-Taylor}, John},
% title = {Canonical Correlation Analysis: An Overview with Application to Learning Methods},
% booktitle = {Neural Computation},
% volume = {Volume 16 (12)},
% pages = {2639--2664},
% year = {2004} }
function [Wx, Wy, r] = cca(X,Y,k)
% CCA calculate canonical correlations
%
% [Wx Wy r] = cca(X,Y) where Wx and Wy contains the canonical correlation
% vectors as columns and r is a vector with corresponding canonical
% correlations.
%
% Update 31/01/05 added bug handling.
% if (nargin ~= 2)
% disp('Inocorrect number of inputs');
% help cca;
% Wx = 0; Wy = 0; r = 0;
% return;
% end
% calculating the covariance matrices
z = [X; Y];
C = cov(z.');
sx = size(X,1);
sy = size(Y,1);
Cxx = C(1:sx, 1:sx) + k*eye(sx);
Cxy = C(1:sx, sx+1:sx+sy);
Cyx = Cxy';
Cyy = C(sx+1:sx+sy,sx+1:sx+sy) + k*eye(sy);
%calculating the Wx cca matrix
Rx = chol(Cxx);
invRx = inv(Rx);
Z = invRx'*Cxy*(Cyy\Cyx)*invRx;
Z = 0.5*(Z' + Z); % making sure that Z is a symmetric matrix
[Wx,r] = eig(Z); % basis in h (X)
r = sqrt(real(r)); % as the original r we get is lamda^2
Wx = invRx * Wx; % actual Wx values
% calculating Wy
Wy = (Cyy\Cyx) * Wx;
% by dividing it by lamda
Wy = Wy./repmat(diag(r)',sy,1);
|
github
|
JerryWisdom/Caffe-windows-master
|
classification_demo.m
|
.m
|
Caffe-windows-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
|
1988kramer/UTIAS-practice-master
|
animateMRCLAMdataSet.m
|
.m
|
UTIAS-practice-master/common/animateMRCLAMdataSet.m
| 6,719 |
utf_8
|
49bde0b6cf3366c8dfa03035dcc4ff2f
|
% UTIAS Multi-Robot Cooperative Localization and Mapping Dataset
% produced by Keith Leung ([email protected]) 2009
% Matlab script animateMRCLAMdataSet.m
% Description: This scripts creates an animation using ground truth data.
% Run this script after loadMRCLAMdataSet.m and sampleMRCLAMdataSet.m
function animateMRCLAMdataSet(Robots, Landmark_Groundtruth, timesteps, sample_time)
% Options %
start_timestep = 1;
end_timestep = timesteps;
timesteps_per_frame = 50;
pause_time_between_frames=0.01; %[s]
draw_measurements = 0;
% Options END %
n_robots = size(Robots, 1);
n_landmarks = length(Landmark_Groundtruth(:,1));
% Plots and Figure Setup
% Robot Colors
colour(1,:) = [1 0 0];
colour(2,:) = [0 0.75 0];
colour(3,:) = [0 0 1];
colour(4,:) = [1 0.50 0.25];
colour(5,:) = [1 0.5 1];
% Estimated Robot Colors
colour(6,:) = [.67 0 0];
colour(7,:) = [0 0.5 0];
colour(8,:) = [0 0 .67];
colour(9,:) = [.67 0.33 0.17];
colour(10,:) = [.67 0.33 .67];
for i=11:11+n_landmarks
colour(i,:) = [0.3 0.3 0.3];
end
figHandle = figure('Name','Dataset Groundtruth','Renderer','OpenGL');
set(gcf,'Position',[1300 1 630 950])
plotHandles_robot_gt = zeros(n_robots,1);
plotHandles_robot_est = zeros(n_robots,1);
plotHandles_landmark_gt = zeros(n_landmarks,1);
r_robot = 0.165;
d_robot = 2*r_robot;
r_landmark = 0.055;
d_landmark = 2*r_landmark;
% get initial positions for robot groundtruth
for i = 1:n_robots
x=Robots{i}.G(1,2);
y=Robots{i}.G(1,3);
z=Robots{i}.G(1,4);
x1 = d_robot*cos(z) + x;
y1 = d_robot*sin(z) + y;
p1 = x - r_robot;
p2 = y - r_robot;
plotHandles_robot_gt(i) = rectangle('Position',[p1,p2,d_robot,d_robot],'Curvature',[1,1],...
'FaceColor',colour(i,:),'LineWidth',1);
line([x x1],[y y1],'Color','k');
n_measurements(i) = length(Robots{i}.M(:,1));
end
% get initial positions for robot pose estimates
for i = 1:n_robots
x=Robots{i}.Est(1,2);
y=Robots{i}.Est(1,3);
z=Robots{i}.Est(1,4);
x1 = d_robot*cos(z) + x;
y1 = d_robot*sin(z) + y;
p1 = x - r_robot;
p2 = y - r_robot;
plotHandles_robot_est(i) = rectangle('Position',[p1,p2,d_robot,d_robot],'Curvature',[1,1],...
'FaceColor',colour(i + 5,:),'LineWidth',1);
line([x x1],[y y1],'Color','k');
end
% get positions for landmarks
for i = 1:n_landmarks
x=Landmark_Groundtruth(i, 2);
y=Landmark_Groundtruth(i, 3);
p1 = x - r_landmark;
p2 = y - r_landmark;
plotHandles_landmark_gt(i) = rectangle('Position',[p1,p2,d_landmark,d_landmark],'Curvature',[1,1],...
'FaceColor',colour(i+10,:),'LineWidth',1);
end
axis square;
axis equal;
axis([-2 6 -6 7]);
set(gca,'XTick',(-10:2:10)');
% Going throuhg data
measurement_time_index = ones(n_robots,1); % index of last measurement processed
barcode = 0;
for i=1:n_robots
tempIndex=find(Robots{i}.M(:,1)>=start_timestep*sample_time,1,'first');
if ~isempty(tempIndex)
measurement_time_index(i) = tempIndex;
else
measurement_time_index(i) = n_measurements(i)+1;
end
end
clear tempIndex
% animate robots groundtruth and pose estimates
for k=start_timestep:end_timestep
t = k*sample_time;
if(mod(k,timesteps_per_frame)==0)
delete(findobj('Type','line'));
end
for i= 1:n_robots
x_g(i) = Robots{i}.G(k,2);
y_g(i) = Robots{i}.G(k,3);
z_g(i) = Robots{i}.G(k,4);
x_est(i) = Robots{i}.Est(k,2);
y_est(i) = Robots{i}.Est(k,3);
z_est(i) = Robots{i}.Est(k,4);
if(mod(k,timesteps_per_frame)==0)
x1_g = d_robot*cos(z_g(i)) + x_g(i);
y1_g = d_robot*sin(z_g(i)) + y_g(i);
p1_g = x_g(i) - r_robot;
p2_g = y_g(i) - r_robot;
set(plotHandles_robot_gt(i),'Position',[p1_g,p2_g,d_robot,d_robot]);
line([x_g(i) x1_g],[y_g(i) y1_g],'Color','k');
x1_est = d_robot*cos(z_est(i)) + x_est(i);
y1_est = d_robot*sin(z_est(i)) + y_est(i);
p1_est = x_est(i) - r_robot;
p2_est = y_est(i) - r_robot;
set(plotHandles_robot_est(i),'Position',[p1_est,p2_est,d_robot,d_robot]);
line([x_est(i) x1_est],[y_est(i) y1_est],'Color','k');
end
% plot meaurements of robot i
if(draw_measurements)
while(n_measurements(i) >= measurement_time_index(i) && Robots{i}.M(measurement_time_index(i),1) <= t)
measure_id = Robots{i}.M(measurement_time_index(i),2);
measure_r = Robots{i}.M(measurement_time_index(i),3);
measure_b = Robots{i}.M(measurement_time_index(i),4);
landmark_index = find(Barcodes(:,2)==measure_id);
if(~isempty(landmark_index))
x1 = x(i) + measure_r*cos(measure_b + z(i));
y1 = y(i) + measure_r*sin(measure_b + z(i));
line([x(i) x1],[y(i) y1],'Color',colour(i,:),'LineWidth',1);
else
robot_index = find(Barcodes(1:5,2)==measure_id);
if(~isempty(robot_index))
x1 = x(i) + measure_r*cos(measure_b + z(i));
y1 = y(i) + measure_r*sin(measure_b + z(i));
line([x(i) x1],[y(i) y1],'Color',colour(i,:),'LineWidth',1);
end
end
measurement_time_index(i) = measurement_time_index(i) + 1;
end
end
end
% write time
if(mod(k,timesteps_per_frame)==0)
delete(findobj('Type','text'));
texttime = strcat('k= ',num2str(k,'%5d'), ' t= ',num2str(t,'%5.2f'), '[s]');
text(1.5,6.5,texttime);
pause(pause_time_between_frames);
else
if(draw_measurements)
pause(0.001);
end
end
end
clear Robot x x1 y y1 z r_robot r_landmark p1 p2 max_time measure_id d_robot d_landmark barcode k colour
clear texttime t measurement_time_index masure_id measure_r measure_b landmark_index robot_index i n_measurements plotHandles* angle
end
|
github
|
1988kramer/UTIAS-practice-master
|
sampleMRCLAMdataSet.m
|
.m
|
UTIAS-practice-master/common/sampleMRCLAMdataSet.m
| 4,367 |
utf_8
|
e87c4cda2a0f697ef211f7d1d26b8fd2
|
% UTIAS Multi-Robot Cooperative Localization and Mapping Dataset
% produced by Keith Leung ([email protected]) 2009
% Matlab script animateMRCLAMdataSet.m
% Description: This scripts samples the dataset at fixed intervals
% (default is 0.02s). Odometry data is interpolated using the recorded time. % Measurements are rounded to the nearest timestep.
% Run this script after loadMRCLAMdataSet.m
function [Robots, timesteps] = sampleMRCLAMdataSet(Robots, sample_time)
% sample_time = 0.02;
n_robots = size(Robots, 1);
min_time = Robots{1}.G(1,1);
max_time = Robots{1}.G(end,1);
for n=2:n_robots
min_time = min(min_time, Robots{n}.G(1,1));
max_time = max(max_time, Robots{n}.G(end,1));
end
for n=1:n_robots
Robots{n}.G(:,1) = Robots{n}.G(:,1) - min_time;
Robots{n}.M(:,1) = Robots{n}.M(:,1) - min_time;
Robots{n}.O(:,1) = Robots{n}.O(:,1) - min_time;
end
max_time = max_time - min_time;
timesteps = floor(max_time/sample_time)+1;
oldData = 0;
for n = 1:n_robots
oldData = Robots{n}.G;
k = 0;
t = 0;
i = 1;
p = 0;
[nr,nc] = size(oldData);
newData = zeros(timesteps,nc);
while(t <= max_time)
newData(k+1,1) = t;
while(oldData(i,1) <= t);
if(i==nr)
break;
end
i = i + 1;
end
if(i == 1 || i == nr)
newData(k+1,2:end) = 0;
else
p = (t - oldData(i-1,1))/(oldData(i,1) - oldData(i-1,1));
if(nc == 8) % i.e. ground truth data
sc = 3;
newData(k+1,2) = oldData(i,2); % keep id number
else
sc = 2;
end
for c = sc:nc
if(nc==8 && c>=6)
d = oldData(i,c) - oldData(i-1,c);
if d > pi
d = d - 2*pi;
elseif d < -pi
d = d + 2*pi;
end
newData(k+1,c) = p*d + oldData(i-1,c);
else
newData(k+1,c) = p*(oldData(i,c) - oldData(i-1,c)) + oldData(i-1,c);
end
end
end
k = k + 1;
t = t + sample_time;
end
Robots{n}.G = newData ;
end
oldData = 0;
for n = 1:n_robots
oldData = Robots{n}.O;
k = 0;
t = 0;
i = 1;
p = 0;
[nr,nc] = size(oldData);
newData = zeros(timesteps,nc);
while(t <= max_time)
newData(k+1,1) = t;
while(oldData(i,1) <= t);
if(i==nr)
break;
end
i = i + 1;
end
if(i == 1 || i == nr)
newData(k+1,2:end) = oldData(i,2:end);
else
p = (t - oldData(i-1,1))/(oldData(i,1) - oldData(i-1,1));
if(nc == 8) % i.e. ground truth data
sc = 3;
newData(k+1,2) = oldData(i,2); % keep id number
else
sc = 2;
end
for c = sc:nc
if(nc==8 && c>=6)
d = oldData(i,c) - oldData(i-1,c);
if d > pi
d = d - 2*pi;
elseif d < -pi
d = d + 2*pi;
end
newData(k+1,c) = p*d + oldData(i-1,c);
else
newData(k+1,c) = p*(oldData(i,c) - oldData(i-1,c)) + oldData(i-1,c);
end
end
end
k = k + 1;
t = t + sample_time;
end
Robots{n}.O = newData ;
end
oldData = 0;
for n = 1:n_robots
oldData = Robots{n}.M;
newData=oldData;
for i = 1:length(oldData)
newData(i,1) = floor(oldData(i,1)/sample_time + 0.5)*sample_time;
end
Robots{n}.M = newData ;
end
clear min_time oldData newData nr nc n p sc t k c i d array_names name;
end
|
github
|
1988kramer/UTIAS-practice-master
|
path_loss.m
|
.m
|
UTIAS-practice-master/common/path_loss.m
| 427 |
utf_8
|
f626413a793d78d0f53e23000161b355
|
% computes euclidean loss between robot's estimated path and ground truth
% ignores bearing error
function loss = path_loss(Robots, robot_num, start)
loss = 0;
for i = start:size(Robots{robot_num}.G,1)
x_diff = Robots{robot_num}.G(i,2) - Robots{robot_num}.Est(i,2);
y_diff = Robots{robot_num}.G(i,3) - Robots{robot_num}.Est(i,3);
err = x_diff^2 + y_diff^2;
loss = loss + err;
end
end
|
github
|
1988kramer/UTIAS-practice-master
|
loadMRCLAMdataSet.m
|
.m
|
UTIAS-practice-master/common/loadMRCLAMdataSet.m
| 2,240 |
utf_8
|
d74f623ab03b14b836499655dc8fa290
|
% UTIAS Multi-Robot Cooperative Localization and Mapping Dataset
% produced by Keith Leung ([email protected]) 2009
% Matlab script loadMRCLAMdataSet.m
% Description: This scripts parses the 17 text files that make up a
% dataset into Matlab arrays. Run this script within the the dataset
% directory.
% parameters:
% n_robots: set to any value from 1-5 to set the number of robots
%
% return values:
% does not currently return anything
% needs to be modified to fix this
function [Barcodes, Landmark_Groundtruth, Robots] = loadMRCLAMdataSet(n_robots)
addpath ../MRCLAM_Dataset1;
%disp('Parsing Dataset')
%disp('Reading barcode numbers')
[subject_num, barcode_num] = textread('Barcodes.dat', '%u %u','commentstyle','shell');
Barcodes = [subject_num, barcode_num];
clear subject_num barcode_num;
%disp('Reading landmark groundtruth')
[subject_num x y x_sd y_sd] = textread('Landmark_Groundtruth.dat', '%f %f %f %f %f','commentstyle','shell');
Landmark_Groundtruth = [subject_num x y x_sd y_sd];
clear subject_num x y x_sd y_sd;
n_landmarks = length(Landmark_Groundtruth);
Robots = cell(1, n_robots);
for i=1:n_robots
%disp(['Reading robot ' num2str(i) ' groundtruth'])
[time x y theta] = textread(['Robot' num2str(i) '_Groundtruth.dat'], '%f %f %f %f','commentstyle','shell');
eval(['Robot' num2str(i) '_Groundtruth = [time x y theta];']);
Robots{i}.G = [time x y theta];
clear time x y theta;
%disp(['Reading robot ' num2str(i) ' odometry'])
[time, v, w] = textread(['Robot' num2str(i) '_Odometry.dat'], '%f %f %f','commentstyle','shell');
eval(['Robot' num2str(i) '_Odometry = [time v w];']);
Robots{i}.O = [time v w];
clear time v w;
%disp(['Reading robot ' num2str(i) ' measurements'])
[time, barcode_num, r b] = textread(['Robot' num2str(i) '_Measurement.dat'], '%f %f %f %f','commentstyle','shell');
eval(['Robot' num2str(i) '_Measurement = [time barcode_num r b];']);
Robots{i}.M = [time barcode_num r b];
clear time barcode_num r b;
end
clear i
end
|
github
|
1988kramer/UTIAS-practice-master
|
kill_landmarks.m
|
.m
|
UTIAS-practice-master/feature-persistence/kill_landmarks.m
| 683 |
utf_8
|
83dafb1f6e2dceda8c2e066213394fcb
|
% returns an array of randomly selected times to kill the specified
% number of randomly chosen landmarks
% NOTE: death of certain, less used landmarks can go unnoticed
% should think of better way to select landmarks to kill
function times_of_death = kill_landmarks(n_landmarks, n_killed, t0, tmax, deltaT)
times_of_death = zeros(n_landmarks, 1); % times each landmark is killed
to_kill = randperm(n_landmarks, n_killed); % indices of landmarks to kill
kill_times = randi([int64(t0 / deltaT), int64(tmax / deltaT)], 1, n_killed);
kill_times = double(kill_times) .* deltaT;
for i = 1:n_killed
times_of_death(to_kill(i)) = kill_times(i);
end
end
|
github
|
PurviAgrawal/Unsupervised_modFilt_CRBM-master-master
|
nvmex_helper.m
|
.m
|
Unsupervised_modFilt_CRBM-master-master/nvmex_helper.m
| 8,678 |
utf_8
|
95177d5818ea641df37a6453697b13b1
|
function errorCode = nvmex_helper(varargin)
%MEX_HELPER is a helper function that contains the code that MEX.M (an
% autogenerated file) executes. It sets up the inputs to call mex.pl (on PC)
% and mex (on Unix).
%
% For information on how to use MEX see MEX help by typing "help mex" or
% "mex -h".
% Copyright 1984-2006 The MathWorks, Inc.
% $Revision: 1.1.6.1 $
if isunix
mexname = get_mex_opts(varargin{:});
if ~isempty(mexname)
[loaded_m, loaded_mex] = inmem;
if ~isempty(loaded_mex)
clear_mex_file(mexname);
end
end
args = [' "ARCH=' computer('arch') '"'];
if (nargin > 0)
args = [args sprintf(' "%s"', varargin{:})];
end
errCode = unix([matlabroot '/bin/mex' args]);
elseif ispc
mexname = get_mex_opts(varargin{:});
matlab_bin_location=[matlabroot '\bin'];
if ~isempty(mexname)
[loaded_m, loaded_mex] = inmem;
if ~isempty(loaded_mex)
clear_mex_file(mexname);
end
end
% Loop over all the arguments. Put extra quotes around any that
% contain spaces.
for i=1:numel(varargin)
if (find(varargin{i} == ' '))
varargin{i} = [ '"' varargin{i} '"' ];
end
end
% Format the mex command
cmdargs = ['-called_from_matlab -matlab "' matlabroot '" ' sprintf(' %s', varargin{:})];
if (any(matlab_bin_location == ' '))
quote_str = '"';
else
quote_str = '';
end
cmdtool = [quote_str matlabroot '\sys\perl\win32\bin\perl.exe' quote_str ' ' ...
quote_str matlab_bin_location '\nvmex.pl' quote_str];
[cmd, rspfile] = make_rsp_file(cmdtool, cmdargs);
try
errCode = dos([ cmd ' -' computer('arch') ]);
try
% This is done to force a change message in case
% notificationhandles are not working properly. If it fails, we
% just want to keep going.
mexpath = fileparts(mexname);
fschange(mexpath);
catch
end
catch
disp(lasterr);
errCode = 1; % failure
end
delete(rspfile);
end
if (nargout > 0)
errorCode = errCode;
elseif (errCode ~= 0)
errorStruct.identifier='MATLAB:MEX:genericFailure';
errorStruct.message='Unable to complete successfully.';
rethrow(errorStruct);
end
%%%%%%%%%%%%%%%%%%%%
%%% SUBFUNCTIONS %%%
%%%%%%%%%%%%%%%%%%%%
function result = read_response_file(filename)
%
% Read a response file (a filename that starts with '@')
% and return a cell of strings, one per entry in the response file.
% Use Perl to ensure processing of arguments is the same as mex.bat
%
result = {};
cmd = ['"' matlabroot '\sys\perl\win32\bin\perl" -e "' ...
'require ''' matlabroot '\\sys\\perl\\win32\\lib\\shellwords.pl'';' ...
'open(FILE, ''' filename ''') || die ''Could not open ' filename ''';' ...
'while (<FILE>) {$line .= $_;} ' ...
'$line =~ s/\\/\\\\/g;' ...
'@ARGS = &shellwords($line); ' ...
'$\" = \"\n\";' ...
'print \"@ARGS\";'];
[s, r] = dos(cmd);
if s == 0
cr = sprintf('\n');
while ~isempty(r)
[result{end+1}, r] = strtok(r, cr);
end
end
function [mexname, setup] = get_mex_opts(varargin)
%
% GET_MEX_OPTS gets the options from the command line.
%
% name:
% It gets the name of the destination MEX-file. This has two
% purposes:
% 1) All platforms need to clear the MEX-file from memory before
% attempting the build, to avoid problems rebuilding shared
% libraries that the OS considers "in use".
% 2) Windows MATLAB deletes the MEX-file before the build occurs.
% It then checks to see whether the MEX-file was created so as
% to establish error status.
% This function returns the minimum necessary information. Further
% processing is done on the MEX-file name by clear_mex_file to
% successfully clear it.
%
% setup:
% It also returns whether or not '-setup' was passed.
%
mexname = '';
outdir = '';
setup = 0;
% First, check for and expand response files into varargin.
v = {};
for count=1:nargin
arg = varargin{count};
if arg(1) == '@'
new_args = read_response_file(arg(2:end));
v(end+1:end+length(new_args)) = new_args;
else
v{end+1} = arg;
end
end
varargin = v;
count = 1;
while (count <= nargin)
arg = varargin{count};
if isempty(mexname) && arg(1) ~= '-' && ~any(arg=='=') && any(arg=='.')
% Source file: MEX-file will be built in current directory
% Only the first source file matters
mexname = arg;
[notUsed, mexname] = fileparts(mexname); %#ok
elseif strcmp(arg, '-f')
count = count + 1;
elseif strcmp(arg, '-output')
count = count + 1;
if count > length(varargin)
errorStruct.identifier = 'MATLAB:MEX:OutputSwitchMisuse';
errorStruct.message = 'The -output switch must be followed by a file name.';
rethrow(errorStruct);
end
mexname = varargin{count};
[outdirTemp,mexname]=fileparts(mexname);
elseif strcmp(arg, '-outdir')
count = count + 1;
if count > length(varargin)
errorStruct.identifier = 'MATLAB:MEX:OutdirSwitchMisuse';
errorStruct.message = 'The -outdir switch must be followed by a directory name.';
rethrow(errorStruct);
end
outdir = varargin{count};
elseif strcmp(arg, '-setup')
setup = 1;
break;
end
count = count + 1;
end
if isempty(outdir) && exist('outdirTemp','var') %Meaning -ouptut
%used but not -outdir
outdir = outdirTemp;
end
mexname = fullfile(outdir, mexname);
function clear_mex_file(basename)
%
% CLEAR_MEX_FILE Clear a MEX-file from memory. This is a tricky
% business and should be avoided if possible. It takes a relative
% or absolute filename as the MEX-file name, and the list of loaded
% MEX-file names.
%
% If CLEAR_MEX_FILE is unable to clear the MEX-file, it will error.
% This can happen if the MEX-file is locked.
% The purpose of following block is to make sure that fullname is a fully
% qualified path.
seps = find(basename == filesep);
if isempty(seps)
% basename is in the current directory
fullname = fullfile(cd,basename);
else
% -output or -outdir was used to determine the location, as well as the
% name of the mex file.
savedir = cd;
[destdir,destname] = fileparts(basename);
cd(destdir);
fullname = fullfile(cd,destname);
cd(savedir);
end
if ~isempty(findstr(fullname, 'private'))
% Things in private directories are represented by the full
% path
mexname = fullname;
else
modifiers = find(fullname == '@');
if any(modifiers)
% Methods have the class directory prepended
mexname = fullname((modifiers(end)+1):end);
% Methods are always displayed with UNIX file
% separators
mexname(mexname==filesep) = '/';
else
% Otherwise, we just use the base name
mexname = basename;
end
end
clear_mex(mexname);
% Make sure that the MEX-file is cleared
[ms, mexs] = inmem;
if ~isempty(strmatch(mexname, mexs, 'exact'))
errorStruct.identifier = 'MATLAB:MEX:mexFileLocked';
errorStruct.message = 'Your MEX-file is locked and must be unlocked before recompiling.';
rethrow(errorStruct);
end
function clear_mex(varargin)
% This will clear a MEX-file successfully, because it has no internal
% variables. varargin is a builtin function and is therefore not a
% valid MEX-file name.
clear(varargin{:});
function [cmd, rspfile] = make_rsp_file(cmdtool, cmdargs)
rspfile = [tempname '.rsp'];
[Frsp, errmsg] = fopen(rspfile, 'wt');
if Frsp == -1
errorStruct.identifier = 'MATLAB:MEX:RspFilePermissionOpen';
errorStruct.message = sprintf('Cannot open file "%s" for writing: %s.', rspfile, errmsg);
rethrow(errorStruct);
end
try
count = fprintf(Frsp, '%s', cmdargs);
if count < length(cmdargs)
errmsg = ferror(Frsp);
errorStruct.identifier = 'MATLAB:MEX:RspFilePermissionWrite';
errorStruct.message = sprintf('Cannot write to file "%s": %s.', rspfile, errmsg);
rethrow(errorStruct);
end
fclose(Frsp);
catch
fclose(Frsp);
delete(rspfile);
rethrow(lasterror);
end
cmd = [cmdtool ' @"' rspfile '"'];
|
github
|
imistyrain/SSH-Windows-master
|
evaluation.m
|
.m
|
SSH-Windows-master/lib/wider_eval_tools/evaluation.m
| 3,654 |
utf_8
|
1963726efb0cb4a054c23471317d67e8
|
function evaluation(norm_pred_list,gt_dir,setting_name,setting_class,legend_name)
load(gt_dir);
if ~exist(sprintf('./plot/baselines/Val/%s/%s',setting_class,legend_name),'dir')
mkdir(sprintf('./plot/baselines/Val/%s/%s',setting_class,legend_name));
end
IoU_thresh = 0.5;
event_num = 61;
thresh_num = 1000;
org_pr_cruve = zeros(thresh_num,2);
count_face = 0;
for i = 1:event_num
img_list = file_list{i};
gt_bbx_list = face_bbx_list{i};
pred_list = norm_pred_list{i};
sub_gt_list = gt_list{i};
img_pr_info_list = cell(length(img_list),1);
fprintf('%s, current event %d\n',setting_name,i);
for j = 1:length(img_list)
gt_bbx = gt_bbx_list{j};
pred_info = pred_list{j};
keep_index = sub_gt_list{j};
count_face = count_face + length(keep_index);
if isempty(gt_bbx) || isempty(pred_info)
continue;
end
ignore = zeros(size(gt_bbx,1),1);
if ~isempty(keep_index)
ignore(keep_index) = 1;
end
[pred_recall, proposal_list] = image_evaluation(pred_info, gt_bbx, ignore, IoU_thresh);
img_pr_info = image_pr_info(thresh_num, pred_info, proposal_list, pred_recall);
img_pr_info_list{j} = img_pr_info;
end
for j = 1:length(img_list)
img_pr_info = img_pr_info_list{j};
if ~isempty(img_pr_info)
org_pr_cruve(:,1) = org_pr_cruve(:,1) + img_pr_info(:,1);
org_pr_cruve(:,2) = org_pr_cruve(:,2) + img_pr_info(:,2);
end
end
end
pr_cruve = dataset_pr_info(thresh_num, org_pr_cruve, count_face);
save(sprintf('./plot/baselines/Val/%s/%s/wider_pr_info_%s_%s.mat',setting_class,legend_name,legend_name,setting_name),'pr_cruve','legend_name','-v7.3');
end
function [pred_recall,proposal_list] = image_evaluation(pred_info, gt_bbx, ignore, IoU_thresh)
pred_recall = zeros(size(pred_info,1),1);
recall_list = zeros(size(gt_bbx,1),1);
proposal_list = zeros(size(pred_info,1),1);
proposal_list = proposal_list + 1;
pred_info(:,3) = pred_info(:,1) + pred_info(:,3);
pred_info(:,4) = pred_info(:,2) + pred_info(:,4);
gt_bbx(:,3) = gt_bbx(:,1) + gt_bbx(:,3);
gt_bbx(:,4) = gt_bbx(:,2) + gt_bbx(:,4);
for h = 1:size(pred_info,1)
overlap_list = boxoverlap(gt_bbx, pred_info(h,1:4));
[max_overlap, idx] = max(overlap_list);
if max_overlap >= IoU_thresh
if (ignore(idx) == 0)
recall_list(idx) = -1;
proposal_list(h) = -1;
elseif (recall_list(idx)==0)
recall_list(idx) = 1;
end
end
r_keep_index = find(recall_list == 1);
pred_recall(h) = length(r_keep_index);
end
end
function img_pr_info = image_pr_info(thresh_num, pred_info, proposal_list, pred_recall)
img_pr_info = zeros(thresh_num,2);
for t = 1:thresh_num
thresh = 1-t/thresh_num;
r_index = find(pred_info(:,5)>=thresh,1,'last');
if (isempty(r_index))
img_pr_info(t,2) = 0;
img_pr_info(t,1) = 0;
else
p_index = find(proposal_list(1:r_index) == 1);
img_pr_info(t,1) = length(p_index);
img_pr_info(t,2) = pred_recall(r_index);
end
end
end
function pr_cruve = dataset_pr_info(thresh_num, org_pr_cruve, count_face)
pr_cruve = zeros(thresh_num,2);
for i = 1:thresh_num
pr_cruve(i,1) = org_pr_cruve(i,2)/org_pr_cruve(i,1);
pr_cruve(i,2) = org_pr_cruve(i,2)/count_face;
end
end
|
github
|
imistyrain/SSH-Windows-master
|
wider_eval.m
|
.m
|
SSH-Windows-master/lib/wider_eval_tools/wider_eval.m
| 1,301 |
utf_8
|
8613d27185c0343468233a87491b7fd0
|
% WIDER FACE Evaluation
% Conduct the evaluation on the WIDER FACE validation set.
%
% Shuo Yang Dec 2015
% Changed the interface for compatibility with the SSH face detector code
%
function wider_eval(pred_dir,legend_name,plot_out_path)
addpath(genpath('./plot'));
%Please specify your prediction directory.
gt_dir = './ground_truth/wider_face_val.mat';
%preprocessing
pred_list = read_pred(pred_dir,gt_dir);
norm_pred_list = norm_score(pred_list);
%evaluate on different settings
setting_name_list = {'easy_val';'medium_val';'hard_val'};
setting_class = 'setting_int';
%Please specify your algorithm name.
for i = 1:size(setting_name_list,1)
fprintf('Current evaluation setting %s\n',setting_name_list{i});
setting_name = setting_name_list{i};
gt_dir = sprintf('./ground_truth/wider_%s.mat',setting_name);
evaluation(norm_pred_list,gt_dir,setting_name,setting_class,legend_name);
end
fprintf('Plot pr curve under overall setting.\n');
dateset_class = 'Val';
% scenario-Int:
seting_class = 'int';
dir_int = sprintf('./plot/baselines/%s/setting_%s',dateset_class, seting_class);
wider_plot(setting_name_list,dir_int,seting_class,dateset_class,plot_out_path);
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
textprogressbar.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/textprogressbar/textprogressbar.m
| 9,929 |
utf_8
|
ae0af981548e7e074cce81ff5d0fb091
|
function upd = textprogressbar(n, varargin)
% UPD = TEXTPROGRESSBAR(N) initializes a text progress bar for monitoring a
% task comprising N steps (e.g., the N rounds of an iteration) in the
% command line. It returns a function handle UPD that is used to update and
% render the progress bar. UPD takes a single argument i <= N which
% corresponds to the number of tasks completed and renders the progress bar
% accordingly.
%
% TEXTPROGRESSBAR(...,'barlength',L) determines the length L of the
% progress bar in number of characters (see 'barsymbol' option). L must be
% a positive integer.
% (Default value is 20 characters.)
%
% TEXTPROGRESSBAR(...,'updatestep',S) determines the minimum number of update
% steps S between consecutive bar re-renderings. The option controls how
% frequently the bar is rendered and in turn controls the computational
% overhead that the bar rendering incurs to the monitored task. It is
% especially useful when bar is used for loops with large number of rounds
% and short execution time per round.
% (Default value is S=10 steps.)
%
% TEXTPROGRESSBAR(...,'startmsg',str) determines the message string to be
% displayed before the progress bar.
% (Default is str='Completed '.)
%
% TEXTPROGRESSBAR(...,'endmsg',str) determines the message string to be
% displayed after progress bar when the task is completed.
% (Default is str=' Done.')
%
% TEXTPROGRESSBAR(...,'showremtime',b) logical parameter that controls
% whether an estimate of the remaining time is displayed.
% (Default is b=true.)
%
% TEXTPROGRESSBAR(...,'showbar',b) logical parameter that controls whether
% the progress bar is displayed. (Default is b=true.)
%
% TEXTPROGRESSBAR(...,'showpercentage',b) logical parameter that controls
% whether to display the percentage of completed items.
% (Default is true.)
%
% TEXTPROGRESSBAR(...,'showactualnum',b) logical parameter that controls
% whether to display the actual number of completed items.
% (Default is false.)
%
% TEXTPROGRESSBAR(...,'showfinaltime',b) logical parameter that controls
% whether to display the total run-time when completed.
% (Default is true.)
%
% TEXTPROGRESSBAR(...,'barsymbol',c) determines the symbol (character) to
% be used for the progress bar. c must be a single character.
% (Default is c='='.)
%
% TEXTPROGRESSBAR(...,'emptybarsymbol',c) determines the symbol (character)
% that is used to fill the un-completed part of the progress bar. c must be
% a single character.
% (Default is c=' '.)
%
% Example:
%
% n = 150;
% upd = textprogressbar(n);
% for i = 1:n
% pause(0.05);
% upd(i);
% end
%
% Default Parameter values:
defaultbarCharLen = 20;
defaultUpdStep = 10;
defaultstartMsg = 'Completed ';
defaultendMsg = ' Done.';
defaultShowremTime = true;
defaultShowBar = true;
defaultshowPercentage = true;
defaultshowActualNum = false;
defaultshowFinalTime = true;
defaultbarCharSymbol = '=';
defaultEmptybarCharSymbol = ' ';
% Auxiliary functions for checking parameter values:
ischarsymbol = @(c) (ischar(c) && length(c) == 1);
ispositiveint = @(x) (isnumeric(x) && mod(x, 1) == 0 && x > 0);
% Register input parameters:
p = inputParser;
addRequired(p,'n', ispositiveint);
addParameter(p, 'barlength', defaultbarCharLen, ispositiveint)
addParameter(p, 'updatestep', defaultUpdStep, ispositiveint)
addParameter(p, 'startmsg', defaultstartMsg, @ischar)
addParameter(p, 'endmsg', defaultendMsg, @ischar)
addParameter(p, 'showremtime', defaultShowremTime, @islogical)
addParameter(p, 'showbar', defaultShowBar, @islogical)
addParameter(p, 'showpercentage', defaultshowPercentage, @islogical)
addParameter(p, 'showactualnum', defaultshowActualNum, @islogical)
addParameter(p, 'showfinaltime', defaultshowFinalTime, @islogical)
addParameter(p, 'barsymbol', defaultbarCharSymbol, ischarsymbol)
addParameter(p, 'emptybarsymbol', defaultEmptybarCharSymbol, ischarsymbol)
% Parse input arguments:
parse(p, n, varargin{:});
n = p.Results.n;
barCharLen = p.Results.barlength;
updStep = p.Results.updatestep;
startMsg = p.Results.startmsg;
endMsg = p.Results.endmsg;
showremTime = p.Results.showremtime;
showBar = p.Results.showbar;
showPercentage = p.Results.showpercentage;
showActualNum = p.Results.showactualnum;
showFinalTime = p.Results.showfinaltime;
barCharSymbol = p.Results.barsymbol;
emptybarCharSymbol = p.Results.emptybarsymbol;
% Initialize progress bar:
bar = ['[', repmat(emptybarCharSymbol, 1, barCharLen), ']'];
nextRenderPoint = 0;
startTime = tic;
% Initalize block for actual number of completed items:
ind = 1;
% Start message block:
startMsgLen = length(startMsg);
startMsgStart = ind;
startMsgEnd = startMsgStart + startMsgLen - 1;
ind = ind + startMsgLen;
% Bar block:
barLen = length(bar);
barStart = 0;
barEnd = 0;
if showBar
barStart = ind;
barEnd = barStart + barLen - 1;
ind = ind + barLen;
end
% Actual Num block:
actualNumDigitLen = numel(num2str(n));
actualNumFormat = sprintf(' %%%dd/%d', actualNumDigitLen, n);
actualNumStr = sprintf(actualNumFormat, 0);
actualNumLen = length(actualNumStr);
actualNumStart = 0;
actualNumEnd = 0;
if showActualNum
actualNumStart = ind;
actualNumEnd = actualNumStart + actualNumLen-1;
ind = ind + actualNumLen;
end
% Percentage block:
percentageFormat = sprintf(' %%3d%%%%');
percentageStr = sprintf(percentageFormat, 0);
percentageLen = length(percentageStr);
percentageStart = 0;
percentageEnd = 0;
if showPercentage
percentageStart = ind;
percentageEnd = percentageStart + percentageLen-1;
ind = ind + percentageLen;
end
% Remaining Time block:
remTimeStr = time2str(Inf);
remTimeLen = length(remTimeStr);
remTimeStart = 0;
remTimeEnd = 0;
if showremTime
remTimeStart = ind;
remTimeEnd = remTimeStart + remTimeLen - 1;
ind = ind + remTimeLen;
end
% End msg block:
endMsgLen = length(endMsg);
if showBar
endMsgStart = barEnd + 1; % Place end message right after bar;
else
endMsgStart = startMsgEnd + 1;
end
endMsgEnd = endMsgStart + endMsgLen - 1;
ind = max([ind, endMsgEnd]);
% Determine size of buffer:
arrayLen = ind - 1;
array = repmat(' ', 1, arrayLen);
% Initial render:
array(startMsgStart:startMsgEnd) = sprintf('%s', startMsg);
delAll = repmat('\b', 1, arrayLen);
% Function to update the status of the progress bar:
function update(i)
if i < nextRenderPoint
return;
end
if i > 0
fprintf(delAll);
end
%pause(1)
nextRenderPoint = min([nextRenderPoint + updStep, n]);
if showremTime
% Delete remaining time block:
array(remTimeStart:remTimeEnd) = ' ';
end
if showPercentage
% Delete percentage block:
array(percentageStart:percentageEnd) = ' ';
end
if showActualNum
% Delete actual num block:
array(actualNumStart:actualNumEnd) = ' ';
end
if showBar
% Update progress bar (only if needed):
barsToPrint = floor( i / n * barCharLen );
bar(2:1+barsToPrint) = barCharSymbol;
array(barStart:barEnd) = bar;
end
% Check if done:
if i >= n
array(endMsgStart:endMsgEnd) = endMsg;
array(endMsgEnd+1:end) = ' ';
if showFinalTime
finalTimeStr = ...
sprintf(' [%d seconds]', round(toc(startTime)));
finalTimeLen = length(finalTimeStr);
if endMsgEnd + finalTimeLen < arrayLen
array(endMsgEnd+1:endMsgEnd+finalTimeLen) = ...
finalTimeStr;
else
array = [array(1:endMsgEnd), finalTimeStr];
end
end
fprintf('%s', array);
fprintf('\n');
return;
end
if showActualNum
% Delete actual num block:
actualNumStr = sprintf(actualNumFormat, i);
array(actualNumStart:actualNumEnd) = actualNumStr;
end
if showPercentage
% Render percentage block:
percentage = floor(i / n * 100);
percentageStr = sprintf(percentageFormat, percentage);
array(percentageStart:percentageEnd) = percentageStr;
end
% Print remaining time block:
if showremTime
t = toc(startTime);
remTime = t/ i * (n-i);
remTimeStr = time2str(remTime);
array(remTimeStart:remTimeEnd) = remTimeStr;
end
fprintf('%s', array);
end
% Do the first render:
update(0);
upd = @update;
end
% Auxiliary functions
function timestr = time2str(t)
if t == Inf
timestr = sprintf(' --:--:--');
else
[hh, mm, tt] = sec2hhmmss(t);
timestr = sprintf(' %02d:%02d:%02d', hh, mm, tt);
end
end
function [hh, mm, ss] = sec2hhmmss(t)
hh = floor(t / 3600);
t = t - hh * 3600;
mm = floor(t / 60);
ss = round(t - mm * 60);
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
cod_sparse.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/cod_sparse.m
| 6,815 |
utf_8
|
1a4ce0b1b8b582cce43c74ce5ac13213
|
function [U, R, V, r] = cod_sparse (A, arg)
%COD_SPARSE complete orthogonal decomposition of a sparse matrix A = U*R*V'
%
% [U, R, V, r] = cod_sparse (A)
% [U, R, V, r] = cod_sparse (A, opts)
%
% The sparse m-by-n matrix A is factorized into U*R*V' where R is m-by-n and
% all zero except for R(1:r,1:r), which is upper triangular. The first r
% diagonal entries of R have magnitude greater than tol, where r is the
% estimated rank of A. All other diagonal entries are zero. The default tol
% of 20*(m+n)*eps(max(diag(R))) is used if tol is not present or if tol<0.
% Use COD for full matrices.
%
% By default, U and V are not returned as sparse matrices, but as structs that
% represent a sequence of Householder transformations (U of size m-by-m and V
% of size n-by-n). They can be passed to COD_QMULT to multiply them with other
% matrices or to convert them into matrices. Alternatively, you can have U and
% V returned as matrices with opts.Q='matrix'.
%
% If A has full rank and m >= n, then this function simply returns the QR
% factorization Q*R*P' = U*R*V' = A where V=P is the fill-reducing ordering.
% If m < n, then U is the fill-reducing ordering and V' the orthgonal factor in
% Householder form. If A is rank deficient, then both U and V contain
% non-trivial Householder transformations.
%
% If condest (R (1:r,1:r)) is large (> 1e12 or so) then the estimated rank of A
% might be incorrect. Try increasing tol in that case, which will make R
% better conditioned and reduce the estimated rank of A.
%
% If the opts input parameter is a scalar, then it is used as the value of tol.
% If it is a struct, it can contain non-default options:
%
% opts.tol the tolerance to be used. tol < 0 means the default is used.
% opts.Q 'Householder' to return U and V as structs (default), 'matrix'
% to return them as sparse matrices. In their matrix form, U and
% V can take a huge amount of memory, however.
%
% Example:
%
% A = sparse (magic (4))
% [U, R, V] = cod_sparse (A)
% norm (A - cod_qmult (U, cod_qmult (V, R, 2),1),1) % 1-norm of A - U*R*V'
% U = cod_qmult (U, speye (size (A,1)), 1) ; % convert U into a matrix
% V = cod_qmult (V, speye (size (A,2)), 1) ; % convert V into a matrix
% norm (A - U*R*V',1)
% opts.Q = 'matrix'
% [U, R, V] = cod_sparse (A,opts)
% norm (A - U*R*V',1)
%
% A = sparse (rand (4,3)), [U, R, V] = cod_sparse (A)
% norm (A - cod_qmult (U, cod_qmult (V, R, 2), 1), 1)
% A = sparse (rand (4,3)), [U, R, V] = cod_sparse (A)
% norm (A - cod_qmult (U, cod_qmult (V, R, 2), 1), 1)
%
% Requires the SPQR and SPQR_QMULT functions from SuiteSparse,
% http://www.suitesparse.com
%
% See also qr, cod, cod_qmult, spqr, spqr_qmult.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
%-------------------------------------------------------------------------------
% get the inputs
%-------------------------------------------------------------------------------
if (~issparse (A))
error ('FACTORIZE:cod_sparse', ...
'COD_SPARSE is not designed for full matrices. Use COD instead.') ;
end
[m, n] = size (A) ;
opts = struct ;
if (nargin > 1)
if (isreal (arg) && arg >= 0)
opts.tol = arg ;
else
if (isfield (arg, 'Q'))
opts.Q = arg.Q ;
end
if (isfield (arg, 'tol') && arg.tol >= 0)
opts.tol = arg.tol ;
end
end
end
if (~isfield (opts, 'Q'))
opts.Q = 'Householder' ; % return Q as a struct
end
ismatrix = isequal (opts.Q, 'matrix') ;
%-------------------------------------------------------------------------------
% compute the COD
%-------------------------------------------------------------------------------
if (m >= n)
%---------------------------------------------------------------------------
% A is square, or tall and thin
%---------------------------------------------------------------------------
% U*R*P1' = A where R is m-by-n, P1 is n-by-n, and U is a struct
% of Householder transformations representing an m-by-m matrix.
[U, R, P1, info] = spqr (A, opts) ;
r = info.rank_A_estimate ;
if (r < n)
% A is rank deficient. R is m-by-n and upper trapezoidal.
opts.tol = 0 ;
[V, R, P2] = spqr (R', opts) ; % R' is m-by-n and lower triangular
rn = reversal (r, n) ;
rm = reversal (r, m) ;
R = R (rn, rm)' ; % reverse and transpose R
if (ismatrix)
U = U * P2 (:, rm) ; % return U and V as sparse matrices
V = P1 * V ;
V = V (:, rn) ;
else
U.Pc = P2 (:, rm) ; % U = U * P2 (:,rm)
V.P = (P1 * V.P')' ; % V = P1 * V ;
V.Pc = sparse (1:n, rn, 1) ; % V = V (:,rn)
end
else
% the factorization is A = U*R*V' with R upper triangular
if (ismatrix)
V = P1 ; % return V as a matrix, P1
else
V = Qpermutation (P1) ; % V = P1, as a struct.
end
end
else
%---------------------------------------------------------------------------
% A is short and fat
%---------------------------------------------------------------------------
% V*R*P1' = A' where R is n-by-m, P1 is m-by-m, and V is a struct
% of Householder transformations representing an n-by-n matrix.
[V, R, P1, info] = spqr (A', opts) ;
r = info.rank_A_estimate ;
if (r < m)
% A is rank deficient. R is n-by-m and upper trapezoidal.
opts.tol = 0 ;
[U, R, P2] = spqr (R', opts) ; % R is m-by-n and upper triangular
if (ismatrix)
U = P1 * U ;
V = V * P2 ;
else
U.P = (P1 * U.P')' ; % U = P1 * U
V.Pc = P2 ; % V = V * P2
end
else
% A is full rank, with A = P1*R'*U'. Transpose and reverse R.
rm = reversal (m, m) ;
rn = reversal (m, n) ;
R = R (rn, rm)' ; % reverse and transpose R
if (ismatrix)
V = V (:, rn) ;
U = P1 (:, rm) ;
else
V.Pc = sparse (rn, 1:n, 1) ; % V = V (:,rn)
U = Qpermutation (P1 (:, rm)) ; % U = P1 (:,rm)
end
end
end
%-------------------------------------------------------------------------------
function p = reversal (r,n)
%REVERSAL return a vector that reverses the first r entries of 1:n
p = [(r:-1:1) (r+1:n)] ;
function Q = Qpermutation (P)
%QPERMUTATION convert a permutation matrix P into a struct for cod_qmult
% The output Q contains no Householder transformations.
n = size (P,1) ;
Q.H = sparse (n,0) ;
Q.Tau = zeros (1,0) ;
Q.P = (P * (1:n)')' ;
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
factorize.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/factorize.m
| 11,934 |
utf_8
|
21103fa9cb25c81819412ac23dcf8b00
|
function F = factorize (A,strategy,burble)
%FACTORIZE an object-oriented method for solving linear systems
% and least-squares problems, and for representing operations with the
% inverse of a square matrix or the pseudo-inverse of a rectangular matrix.
%
% F = factorize(A) returns an object F that holds the factorization of A.
% x=F\b then solves a linear system or a least-squares problem. S=inverse(F)
% or S=inverse(A) returns a factorized representation of the inverse of A so
% that inverse(A)*b is mathematically equivalent to pinv(A)*b, but the former
% does not actually compute the inverse or pseudo-inverse of A.
%
% Example
%
% F = factorize(A) ; % LU, QR, or Cholesky factorization of A
% x = F\b ; % solve A*x=b; same as x=A\b
% S = inverse (F) ; % S represents the factorization of inv(A)
% x = S*b ; % same as x = A\b.
% E = A-B*inverse(D)*C % efficiently computes the Schur complement
% E = A-B*inv(D)*C % bad method for computing the Schur complement
% S = inverse(A) ; S(:,1) % compute just the first column of inv(A),
% % without computing inv(A)
%
% F = factorize (A, strategy, burble) ; % optional 2nd and 3rd inputs
%
% A string can be specified as a second input parameter to select the strategy
% used to factorize the matrix. The first two are meta-strategies:
%
% 'default' if rectangular
% use QR for sparse A or A' (whichever is tall and thin);
% use COD for full A
% else
% if symmetric
% if positive real diagonal: try CHOL
% else (or if CHOL fails): try LDL
% end
% if not yet factorized: try LU (fails if rank-deficient)
% end
% if all else fails, or if QR or LU report that the matrix
% is singular (or nearly so): use COD
% This strategy mimics backslash, except that backslash never
% uses COD. Backslash also exploits other solvers, such as
% specialized tridiagonal and banded solvers.
%
% 'symmetric' as 'default' above, but assumes A is symmetric without
% checking, which is faster if you already know A is symmetric.
% Uses tril(A) and assumes triu(A) is its transpose. Results
% will be incorrect if A is not symmetric. If A is rectangular,
% the 'default' strategy is used instead.
%
% 'unsymmetric' as 'default', but assumes A is unsymmetric.
%
% The next "strategies" just select a single method, listed in decreasing order
% of generality and increasing order of speed and memory efficiency. All of
% them except the SVD can exploit sparsity.
%
% 'svd' use SVD. Never fails ... unless it runs out of time or memory.
% Coerces a sparse matrix A to full.
%
% 'cod' use COD. Almost as accurate as SVD, and much faster. Based
% on dense or sparse QR with rank estimation. Handles
% rank-deficient matrices, as long as it correctly estimates
% the rank. If the rank is ill-defined, use the SVD instead.
% Sparse COD requires the SPQR package to be installed
% (see http://www.suitesparse.com).
%
% 'qr' use QR. Reports a warning if A is singular.
%
% 'lu' use LU. Fails if A is rectangular; warning if A singular.
%
% 'ldl' use LDL. Fails if A is rank-deficient or not symmetric, or if
% A is sparse and complex. Uses tril(A) and assumes triu(A)
% is the transpose of tril(A).
%
% 'chol' use CHOL. Fails if A is rank-deficient or not symmetric
% positive definite. If A is sparse, it uses tril(A) and
% assumes triu(A) is the transpose of tril(A). If A is dense,
% triu(A) is used instead.
%
% A third input, burble, can be provided to tell this function to print what
% methods it tries (if burble is nonzero).
%
% For a demo type "fdemo" in the Demo directory or see the Doc/ directory.
%
% See also inverse, slash, linsolve, spqr.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
assert (ndims (A) == 2, 'Matrix must be 2D.') ;
if (nargin < 2 || isempty (strategy))
strategy = 'default' ;
end
if (nargin < 3)
burble = 0 ;
end
if (burble)
fprintf ('\nfactorize: strategy %s, A has size %d-by-%d, ', ...
strategy, size (A)) ;
if (issparse (A))
fprintf ('sparse with %d nonzeros.\n', nnz (A)) ;
else
fprintf ('full.\n') ;
end
end
switch strategy
case 'default'
[F, me] = backslash_mimic (A, burble, 0) ;
case 'symmetric'
[F, me] = backslash_mimic (A, burble, 1) ;
case 'unsymmetric'
[F, me] = backslash_mimic (A, burble, 2) ;
case 'svd'
[F, me] = factorize_svd (A, burble) ;
case 'cod'
[F, me] = factorize_cod (A, burble) ;
case 'qr'
[F, me] = factorize_qr (A, burble, 0) ;
case 'lu'
% do not report a failure if the matrix is singular
[F, me] = factorize_lu (A, burble, 0) ;
case 'ldl'
[F, me] = factorize_ldl (A, burble) ;
case 'chol'
[F, me] = factorize_chol (A, burble) ;
otherwise
error ('FACTORIZE:invalidStrategy', 'unrecognized strategy.') ;
end
if (~isobject (F))
throw (me) ;
end
%-------------------------------------------------------------------------------
function [F, me] = backslash_mimic (A, burble, strategy)
%BACKSLASH_MIMIC automatically select a method to factorize A.
F = [ ] ;
me = [ ] ;
[m, n] = size (A) ;
% If the following condition is true, then the QR, QRT, or LU factorizations
% will report a failure if A is singular (or nearly so). This allows COD
% or COD_SPARSE to then be used instead. COD_SPARSE relies on the SPQR
% mexFunction in SuiteSparse, which might not be installed. In this case,
% QR, QRT, and LU do not report failures for sparse matrices that are singular
% (or nearly so), since there is no COD_SPARSE to fall back on.
fail_if_singular = ~issparse (A) || (exist ('spqr') == 3) ; %#ok
try_cod = true ;
if (m ~= n)
if (issparse (A))
% Use QR for the sparse rectangular case (ignore 'strategy' argument).
[F, me] = factorize_qr (A, burble, fail_if_singular) ;
else
% Use COD for the full rectangular case (ignore 'strategy' argument).
% If this fails, there's no reason to retry the COD below. If A has
% full rank, then COD is the same as QR with column pivoting (with the
% same cost in terms of run time and memory). Backslash in MATLAB uses
% QR with column pivoting alone, so this is just as fast as x=A\b in
% the full-rank case, but gives a more reliable result in the rank-
% deficient case.
try_cod = false ;
[F, me] = factorize_cod (A, burble) ;
end
else
% square case: Cholesky, LDL, or LU factorization of A
switch strategy
case 0
is_symmetric = (nnz (A-A') == 0) ;
case 1
is_symmetric = true ;
case 2
is_symmetric = false ;
end
if (is_symmetric)
% A is symmetric (or assumed to be so)
d = diag (A) ;
if (all (d > 0) && nnz (imag (d)) == 0)
% try a Cholesky factorization
[F, me] = factorize_chol (A, burble) ;
end
if (~isobject (F) && (~issparse (A) || isreal (A)))
% try an LDL factorization.
% complex sparse LDL does not yet exist in MATLAB
[F, me] = factorize_ldl (A, burble) ;
end
end
if (~isobject (F))
% use LU if Cholesky and/or LDL failed, or were skipped.
[F, me] = factorize_lu (A, burble, fail_if_singular) ;
end
end
if (~isobject (F) && try_cod)
% everything else failed, matrix is rank-deficient. Use COD
[F, me] = factorize_cod (A, burble) ;
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_qr (A, burble, fail_if_singular)
% QR fails if the matrix is rank-deficient.
F = [ ] ;
me = [ ] ;
try
[m, n] = size (A) ;
if (m >= n)
if (burble)
fprintf ('factorize: try QR of A ... ') ;
end
if (issparse (A))
F = factorization_qr_sparse (A, fail_if_singular) ;
else
F = factorization_qr_dense (A, fail_if_singular) ;
end
else
if (burble)
fprintf ('factorize: try QR of A'' ... ') ;
end
if (issparse (A))
F = factorization_qrt_sparse (A, fail_if_singular) ;
else
F = factorization_qrt_dense (A, fail_if_singular) ;
end
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_chol (A, burble)
% LDL fails if the matrix is rectangular, rank-deficient, or not positive
% definite. Only the lower triangular part of A is used.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try CHOL ... ') ;
end
if (issparse (A))
F = factorization_chol_sparse (A) ;
else
F = factorization_chol_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_ldl (A, burble)
% LDL fails if the matrix is rectangular or rank-deficient.
% As of MATLAB R2012a, ldl does not work for complex sparse matrices.
% Only the lower triangular part of A is used.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try LDL ... ') ;
end
if (issparse (A))
F = factorization_ldl_sparse (A) ;
else
F = factorization_ldl_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_lu (A, burble, fail_if_singular)
% LU fails if the matrix is rectangular or rank-deficient.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try LU ... ') ;
end
if (issparse (A))
F = factorization_lu_sparse (A, fail_if_singular) ;
else
F = factorization_lu_dense (A, fail_if_singular) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_cod (A, burble)
% COD only fails when it runs out of memory.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try COD ... ') ;
end
if (issparse (A))
F = factorization_cod_sparse (A) ;
else
F = factorization_cod_dense (A) ;
end
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
%-------------------------------------------------------------------------------
function [F, me] = factorize_svd (A, burble)
% SVD only fails when it runs out of memory.
F = [ ] ;
me = [ ] ;
try
if (burble)
fprintf ('factorize: try SVD ... ') ;
end
F = factorization_svd (A) ;
if (burble)
fprintf ('OK.\n') ;
end
catch me
if (burble)
fprintf ('failed.\nfactorize: %s\n', me.message) ;
end
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
factorization.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/factorization.m
| 26,728 |
utf_8
|
55ffea84aab117fa3c5b7553af5c25be
|
classdef factorization
%FACTORIZATION a generic matrix factorization object
% Normally, this object is created via the F=factorize(A) function. Users
% do not need to use this method directly.
%
% This is an abstract class that is specialized into 13 different kinds of
% matrix factorizations:
%
% factorization_chol_dense dense Cholesky A = R'*R
% factorization_lu_dense dense LU A(p,:) = L*U
% factorization_qr_dense dense QR of A A = Q*R
% factorization_qrt_dense dense QR of A' A' = Q*R
% factorization_ldl_dense dense LDL A(p,p) = L*D*L'
% factorization_cod_dense dense COD A = U*R*V'
%
% factorization_chol_sparse sparse Cholesky P'*A*P = L*L'
% factorization_lu_sparse sparse LU P*(R\A)*Q = L*U
% factorization_qr_sparse sparse QR of A (A*P)'*(A*P) = R'*R
% factorization_qrt_sparse sparse QR of A' (P*A)*(P*A)' = R'*R
% factorization_ldl_sparse sparse LDL P'*A*P = L*D*L'
% factorization_cod_sparse sparse COD A = U*R*V'
%
% factorization_svd SVD A = U*S*V'
%
% The abstract class provides the following functions. In the descriptions,
% F is a factorization. The arguments b, y, and z may be factorizations or
% matrices. The output x is normally matrix unless it can be represented as a
% scaled factorization. For example, G=F\2 and G=inverse(F)*2 both return a
% factorization G. Below, s is always a scalar, and C is always a matrix.
%
% These methods return a matrix x, unless one argument is a scalar (in which
% case they return a scaled factorization object):
% x = mldivide (F, b) x = A \ b
% x = mrdivide (b, F) x = b / A
% x = mtimes (y, z) y * z
%
% These methods always return a factorization:
% F = uplus (F) +F
% F = uminus (F) -F
% F = inverse (F) representation of inv(A), without computing it
% F = ctranspose (F) F'
%
% These built-in methods return a scalar:
% s = isreal (F)
% s = isempty (F)
% s = isscalar (F)
% s = issingle (F)
% s = isnumeric (F)
% s = isfloat (F)
% s = isvector (F)
% s = issparse (F)
% s = isfield (F,f)
% s = isa (F, s)
% s = condest (F)
%
% This method returns the estimated rank from the factorization.
% s = rankest (F)
%
% These methods support access to the contents of a factorization object
% e = end (F, k, n)
% [m,n] = size (F, k)
% S = double (F)
% C = subsref (F, ij)
% S = struct (F)
% disp (F)
%
% The factorization_chol_dense object also provides cholupdate, which acts
% just like the builtin cholupdate.
%
% The factorization_svd object provides:
%
% c = cond (F,p) the p-norm condition number. p=2 is the default.
% cond(F,2) takes no time to compute, since it was
% computed when the SVD factorization was found.
% a = norm (F,p) the p-norm. see the cond(F,p) discussion above.
% r = rank (F) returns the rank of A, precomputed by the SVD.
% Z = null (F) orthonormal basis for the null space of A
% Q = orth (F) orthonormal basis for the range of A
% C = pinv (F) the pseudo-inverse, V'*(S\V).
% [U,S,V] = svd (F) SVD of A or pinv(A), regular, economy, or rank-sized
%
% See also mldivide, lu, chol, ldl, qr, svd.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
properties (SetAccess = protected)
% The abstract class holds a QR, LU, Cholesky factorization:
A = [ ] ; % a copy of the input matrix
Factors = [ ] ;
is_inverse = false ;% F represents the factorization of A or inv(A)
is_ctrans = false ; % F represents the factorization of A or A'
kind = '' ; % a string stating what kind of factorization F is
alpha = 1 ; % F represents the factorization of A or alpha*A.
A_rank = [ ] ; % rank of A, from SVD, or estimate from COD
A_cond = [ ] ; % 2-norm condition number of A, from SVD
A_condest = [ ] ; % quick and dirty estimate of the condition number
% If F is inverted, alpha doesn't change. For example:
% F = alpha*factorize(A) ; % F = alpha*A, in factorized form.
% G = inverse(F) ; % G = inv(alpha*A)
% H = beta*G % H = beta*inv(alpha*A)
% = inv((alpha/beta)*A)
% So to update alpha via scaling, beta*F, the new scale factor beta
% is multiplied with F.alpha if F.is_inverse is false. Otherwise,
% F.alpha is divided by beta to get the new scale factor.
end
methods (Abstract)
x = mldivide_subclass (F, b) ;
x = mrdivide_subclass (b, F) ;
e = error_check (F) ;
end
methods
%-----------------------------------------------------------------------
% mldivide and mrdivide: return a scaled factorization or a matrix
%-----------------------------------------------------------------------
% Let b be a double scalar, F a non-scalar factorization, and g a scalar
% factorization. Then these operations return scaled factorization
% objects (unless flatten is true, in which case a matrix is returned):
%
% F\b = inverse (F) * b | F/b = F / b
% F\g = inverse (F) * double (g) | F/g = F / double (g)
% b\F = F / b | b/F = b * inverse (F)
% g\F = F / double (g) | g/F = double (g) * inverse (F)
%
% Otherwise mldivide & mrdivide always return a matrix as their result.
function x = mldivide (y, z, flatten)
%MLDIVIDE x = y\z where either y or z or both are factorizations.
flatten = (nargin > 2 && flatten) ;
if (isobject (y) && isscalar (z) && ~flatten)
% x = y\z where y is an object and z is scalar (perhaps object).
% result is a scaled factorization object x.
x = scale_factor (inverse (y), ~(y.is_inverse), double (z)) ;
elseif (isscalar (y) && isobject (z) && ~flatten)
% x = y\z where y is scalar (perhaps object) and z is an object.
% result is a scaled factorization object x.
x = scale_factor (z, ~(z.is_inverse), double (y)) ;
else
% result x will be a matrix. b is coerced to be a matrix.
[F, b, first_arg_is_F] = getargs (y, z) ;
if (~first_arg_is_F)
% x = b\F where F is a factorization.
error_if_inverse (F, 1) ;
x = b \ F.A ; % use builtin backslash
elseif (F.is_ctrans)
% x = F\b where F represents (alpha*A)' or inv(alpha*A)'
if (F.is_inverse)
% x = inv(alpha*A)'\b = (A'*b)*alpha'
x = (F.A'*b) * F.alpha' ;
else
% x = (alpha*A)'\b = (b'/A)' / alpha'
x = mrdivide_subclass (b', F)' / F.alpha' ;
end
else
% x = F\b where F represents (alpha*A) or inv(alpha*A)
if (F.is_inverse)
% x = inv(alpha*A)\b = (A*b)*alpha
x = (F.A*b) * F.alpha ;
else
% x = (alpha*A)\b = (A\b) / alpha
x = mldivide_subclass (F, b) / F.alpha ;
end
end
end
end
function x = mrdivide (y, z, flatten)
%MRDIVIDE x = y/z where either y or z or both are factorizations.
flatten = (nargin > 2 && flatten) ;
if (isobject (y) && isscalar (z) && ~flatten)
% x = y/z where y is an object and z is scalar (perhaps object).
% result is a scaled factorization object x.
x = scale_factor (y, ~(y.is_inverse), double (z)) ;
elseif (isscalar (y) && isobject (z) && ~flatten)
% x = y/z where y is scalar (perhaps object) and z is an object.
% result is a scaled factorization object x.
x = scale_factor (inverse (z), ~(z.is_inverse), double (y)) ;
else
% result x will be a matrix. b is coerced to be a matrix.
[F, b, first_arg_is_F] = getargs (y, z) ;
if (first_arg_is_F)
% x = F/b where F is a factorization object
error_if_inverse (F, 2)
x = F.A / b ; % use builtin slash
elseif (F.is_ctrans)
% x = b/F where F represents (alpha*A)' or inv(alpha*A)'
if (F.is_inverse)
% x = b/inv(alpha*A)' = (b*A')*alpha'
x = (b*F.A') * F.alpha' ;
else
% x = b/(alpha*A)' = (A\b')' / alpha'
x = mldivide_subclass (F, b')' / F.alpha' ;
end
else
% x = b/F where F represents (alpha*A) or inv(alpha*A)
if (F.is_inverse)
% x = b/inv(alpha*A) = (b*A)*alpha
x = (b*F.A) * F.alpha ;
else
% x = b/(alpha*A) = (b/A) / alpha
x = mrdivide_subclass (b, F) / F.alpha ;
end
end
end
end
%-----------------------------------------------------------------------
% mtimes: a simple and clean wrapper for mldivide and mrdivide
%-----------------------------------------------------------------------
function x = mtimes (y, z)
%MTIMES x=y*z where y or z is a factorization object (or both).
% Since inverse(F) is so cheap, and does the right thing inside
% mldivide and mrdivide, this is just a simple wrapper.
if (isobject (y))
% A*b becomes inverse(A)\b
% inverse(A)*b becomes A\b
% A'*b becomes inverse(A)'\b
% inverse(A)'*b becomes A'\b
x = mldivide (inverse (y), z) ;
else
% b*A becomes b/inverse(A)
% b*inverse(A) becomes b/A
% b*A' becomes b/inverse(A)'
% b*inverse(A)' becomes b/A'
% y is a scalar or matrix, z must be an object
x = mrdivide (y, inverse (z)) ;
end
end
%-----------------------------------------------------------------------
% uplus, uminus, ctranspose, inverse: always return a factorization
%-----------------------------------------------------------------------
function F = uplus (F)
%UPLUS +F
end
function F = uminus (F)
%UMINUS -F
F.alpha = -(F.alpha) ;
end
function F = inverse (F)
%INVERSE "inverts" F by flagging it as factorization of inv(A)
F.is_inverse = ~(F.is_inverse) ;
end
function F = ctranspose (F)
%CTRANSPOSE "transposes" F by flagging it as factorization of A'
F.is_ctrans = ~(F.is_ctrans) ;
end
%-----------------------------------------------------------------------
% is* methods that return a scalar
%-----------------------------------------------------------------------
function s = isreal (F)
%ISREAL for F=factorize(A): same as isreal(A)
s = isreal (F.A) ;
end
function s = isempty (F)
%ISEMPTY for F=factorize(A): same as isempty(A)
s = any (size (F.A) == 0) ;
end
function s = isscalar (F)
%ISSCALAR for F=factorize(A): same as isscalar(A)
s = isscalar (F.A) ;
end
function s = issingle (F) %#ok
%ISSINGLE for F=factorize(A) is always false
s = false ;
end
function s = isnumeric (F) %#ok
%ISNUMERIC for F=factorize(A) is always true
s = true ;
end
function s = isfloat (F) %#ok
%ISFLOAT for F=factorize(A) is always true
s = true ;
end
function s = isvector (F)
%ISVECTOR for F=factorize(A): same as isvector(A)
s = isvector (F.A) ;
end
function s = issparse (F)
%ISSPARSE for F=factorize(A): same as issparse(A)
s = issparse (F.A) ;
end
function s = isfield (F, f) %#ok
%ISFIELD isfield(F,f) is true if F.f exists, false otherwise
s = (ischar (f) && (strcmp (f, 'A') ...
|| strcmp (f, 'Factors') || strcmp (f, 'kind') ...
|| strcmp (f, 'is_inverse') || strcmp (f, 'is_ctrans') ...
|| strcmp (f, 'alpha') || strcmp (f, 'A_rank') ...
|| strcmp (f, 'A_cond') || strcmp (f, 'A_condest'))) ;
end
function s = isa (F, s)
%ISA for F=factorize(A): 'double', 'numeric', 'float' are true.
% For other types, the builtin isa does the right thing.
s = strcmp (s, 'double') || strcmp (s, 'numeric') || ...
strcmp (s, 'float') || builtin ('isa', F, s) ;
end
%-----------------------------------------------------------------------
% condest, rankest
%-----------------------------------------------------------------------
function C = abs (F)
%ABS abs(F) returns abs(A) or abs(inverse(A)), as appropriate. The
% ONLY reason abs is included here is to support the builtin
% normest1 for small matrices (n <= 4). Computing abs(inverse(A))
% explicitly computes the inverse of A, so use with caution.
C = abs (double (F)) ;
end
function s = condest (F)
%CONDEST 1-norm condition number for square matrices.
% Does not require another factorization of A, so it's very fast.
% Does NOT explicitly compute the inverse of A. Instead, if F
% represents an inverse, F*x inside normest1 does the right thing,
% and does A\b using the factorization F.
A = F.A ; %#ok
[m, n] = size (A) ; %#ok
if (m ~= n)
error ('MATLAB:condest:NonSquareMatrix', ...
'Matrix must be square.') ;
end
if (n == 0)
s = 0 ;
elseif (F.is_inverse)
% F already represents the factorization of the inverse of A
s = F.alpha * norm (A,1) * normest1 (F) ; %#ok
else
% Note that the inverse is NOT explicitly computed.
s = F.alpha * norm (A,1) * normest1 (inverse (F)) ; %#ok
end
end
function r = rankest (F)
%RANKEST returns the estimated rank of A.
% It is a very rough estimate if Cholesky, LU, QR, or LDL succeeded
% (in which A is assumed to have full rank). COD finds a more
% accurate estimate, and SVD finds the exact rank.
r = F.A_rank ;
end
%-----------------------------------------------------------------------
% end, size
%-----------------------------------------------------------------------
function e = end (F, k, n)
%END returns index of last item for use in subsref
if (n == 1)
e = numel (F.A) ; % # of elements, for linear indexing
else
e = size (F, k) ; % # of rows or columns in A or pinv(A)
end
end
function [m, n] = size (F, k)
%SIZE returns the size of the matrix F.A in the factorization F
if (F.is_inverse ~= F.is_ctrans)
% swap the dimensions to match pinv(A)
if (nargout > 1)
[n, m] = size (F.A) ;
else
m = size (F.A) ;
m = m ([2 1]) ;
end
else
if (nargout > 1)
[m, n] = size (F.A) ;
else
m = size (F.A) ;
end
end
if (nargin > 1)
m = m (k) ;
end
end
%-----------------------------------------------------------------------
% double: a wrapper for subsref
%-----------------------------------------------------------------------
function S = double (F)
%DOUBLE returns the factorization as a matrix, A or inv(A)
ij.type = '()' ;
ij.subs = cell (1,0) ;
S = subsref (F, ij) ; % let factorize.subsref do all the work
end
%-----------------------------------------------------------------------
% subsref: returns a matrix
%-----------------------------------------------------------------------
function C = subsref (F, ij)
%SUBSREF A(i,j) or (i,j)th entry of inv(A) if F is inverted.
% Otherwise, explicit entries in the inverse are computed.
% This method also extracts the contents of F with F.whatever.
switch (ij (1).type)
case '.'
% F.A usage: extract one of the matrices from F
switch ij (1).subs
case 'A'
C = F.A ;
case 'Factors'
C = F.Factors ;
case 'is_inverse'
C = F.is_inverse ;
case 'is_ctrans'
C = F.is_ctrans ;
case 'kind'
C = F.kind ;
case 'alpha'
C = F.alpha ;
case 'A_cond'
C = F.A_cond ;
case 'A_condest'
C = F.A_condest ;
case 'A_rank'
C = F.A_rank ;
otherwise
error ('MATLAB:nonExistentField', ...
'Reference to non-existent field ''%s''.', ...
ij (1).subs) ;
end
% F.X(2,3) usage, return X(2,3), for component F.X
if (length (ij) > 1 && ~isempty (ij (2).subs))
C = subsref (C, ij (2)) ;
end
case '()'
C = subsref_paren (F, ij) ;
case '{}'
error ('MATLAB:cellRefFromNonCell', ...
'Cell contents reference from a non-cell array object.') ;
end
end
%-----------------------------------------------------------------------
% struct: extracts all contents of a factorization object
%-----------------------------------------------------------------------
function S = struct (F)
%STRUCT convert factorization F into a struct.
% S cannot be used for subsequent object methods here.
S.A = F.A ;
S.Factors = F.Factors ;
S.is_inverse = F.is_inverse ;
S.is_ctrans = F.is_ctrans ;
S.alpha = F.alpha ;
S.A_rank = F.A_rank ;
S.A_cond = F.A_cond ;
S.kind = F.kind ;
end
%-----------------------------------------------------------------------
% disp: displays the contents of F
%-----------------------------------------------------------------------
function disp (F)
%DISP displays a factorization object
fprintf (' class: %s\n', class (F)) ;
fprintf (' %s\n', F.kind) ;
fprintf (' A: [%dx%d double]\n', size (F.A)) ;
fprintf (' Factors:\n') ; disp (F.Factors) ;
fprintf (' is_inverse: %d\n', F.is_inverse) ;
fprintf (' is_ctrans: %d\n', F.is_ctrans) ;
fprintf (' alpha: %g', F.alpha) ;
if (~isreal (F.alpha))
fprintf (' + (%g)i', imag (F.alpha)) ;
end
fprintf ('\n') ;
if (~isempty (F.A_rank))
fprintf (' A_rank: %d\n', F.A_rank) ;
end
if (~isempty (F.A_condest))
fprintf (' A_condest: %d\n', F.A_condest) ;
end
if (~isempty (F.A_cond))
fprintf (' A_cond: %d\n', F.A_cond) ;
end
end
end
%---------------------------------------------------------------------------
% methods that are not user-callable
%---------------------------------------------------------------------------
methods (Access = protected)
function [F, b, first_arg_is_F] = getargs (y, z)
first_arg_is_F = isobject (y) ;
if (first_arg_is_F)
F = y ; % first argument is a factorization object
b = double (z) ; % 2nd one coerced to be a matrix
else
b = y ; % first argument is not an object
F = z ; % second one must be an object
end
end
function F = scale_factor (F, use_beta_inverse, beta)
%SCALE_FACTOR scales a factorization
if (use_beta_inverse)
% F = inv(alpha*A), so F*beta = inv((alpha/beta)*A)
if (F.is_ctrans)
F.alpha = F.alpha / beta' ;
else
F.alpha = F.alpha / beta ;
end
else
% F = alpha*A, so F*beta = (alpha*beta)*A
if (F.is_ctrans)
F.alpha = F.alpha * beta' ;
else
F.alpha = F.alpha * beta ;
end
end
end
end
end
%-------------------------------------------------------------------------------
% subsref_paren: support function for subsref
%-------------------------------------------------------------------------------
function C = subsref_paren (F, ij)
%SUBSREF_PAREN C = subsref_paren(F,ij) implements C=F(i,j) and C=F(i)
% F(2,3) usage, return A(2,3) or the (2,3) of inv(A).
assert (length (ij) == 1, 'Improper index matrix reference.') ;
A = F.A ;
is_ctrans = F.is_ctrans ;
if (is_ctrans && length (ij.subs) > 1) % swap i and j
ij.subs = ij.subs ([2 1]) ;
end
if (F.is_inverse)
% requesting explicit entries of the inverse
if (length (ij.subs) == 1)
% for linear indexing of the inverse (C=F(i)), first
% convert to double and then use builtin subsref
C = subsref (double (F), ij) ;
else
% standard indexing, C = F(i,j)
if (is_ctrans)
[n, m] = size (A) ;
else
[m, n] = size (A) ;
end
if (length (ij.subs) == 2)
ilen = length (ij.subs {1}) ;
if (strcmp (ij.subs {1}, ':'))
ilen = n ;
end
jlen = length (ij.subs {2}) ;
if (strcmp (ij.subs {2}, ':'))
jlen = m ;
end
j = ij ;
j.subs {1} = ':' ;
i = ij ;
i.subs {2} = ':' ;
if (jlen <= ilen)
% compute X=S(:,j) of S=inv(A) and return X(i,:)
C = subsref (mldivide (...
inverse (F), ...
subsref (identity (A, m), j), 1), i) ;
else
% compute X=S(i,:) of S=inv(A) and return X(:,j)
C = subsref (mrdivide (...
subsref (identity (A, n), i), ...
inverse (F), 1), j) ;
end
else
% the entire inverse has been explicitly computed
C = mldivide (inverse (F), identity (A, m), 1) ;
end
end
else
% F is not inverted, so just return A(i,j)
if (isempty (ij (1).subs))
C = A ;
else
C = subsref (A, ij) ;
end
C = C * F.alpha ;
if (is_ctrans)
C = C' ;
end
end
end
%-------------------------------------------------------------------------------
% identity: return a full or sparse identity matrix
%-------------------------------------------------------------------------------
function I = identity (A, n)
%IDENTITY return a full or sparse identity matrix. Not user-callable
if (issparse (A))
I = speye (n) ;
else
I = eye (n) ;
end
end
%-------------------------------------------------------------------------------
% throw an error if inv(A) is being inadvertently computed
%-------------------------------------------------------------------------------
function error_if_inverse (F, kind)
% x = b\F or F/b where F=inverse(A) and b is not a scalar is unsupported.
% It could be done by coercing F into an explicit matrix representation of
% inv(A), via x = b\double(F) or double(A)/b, but this is the same as
% b\inv(A) or inv(A)/b respectively. That is dangerous, and thus it is
% not done here automatically.
if (F.is_inverse)
if (kind == 1)
s1 = 'B\F' ;
s2 = 'B\double(F)' ;
else
s1 = 'F/B' ;
s2 = 'double(F)/B' ;
end
error ('FACTORIZE:unsupported', ...
['%s where F=inverse(A) requires the explicit computation of the ' ...
'inverse.\nThis is ill-advised, so it is never done automatically.'...
'\nTo force it, use %s instead of %s.\n'], s1, s2, s1) ;
end
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
test_factorize.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/Test/test_factorize.m
| 14,450 |
utf_8
|
9ac6e99f0fe01b551b2aa0cbdbdc17ed
|
function err = test_factorize (A, strategy)
%TEST_FACTORIZE test the accuracy of the factorization object
%
% Example
% test_factorize (A) ; % where A is square or rectangular, sparse or dense
% test_factorize (A, strategy) ; % forces a particular strategy;
% % works only if the matrix is compatible.
%
% See also test_all, factorize, inverse, mldivide
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
reset_rand ;
if (nargin < 1)
A = rand (100) ;
end
if (nargin < 2)
strategy = '' ;
end
% do not check the sparsity of the result when using the SVD
spcheck = ~(strcmp (strategy, 'svd')) ;
err = 0 ;
if (strcmp (strategy, 'ldl') && issparse (A) && ~isreal(A))
% do not test ldl on sparse complex matrices
return ;
end
[m, n] = size (A) ;
if (min (m,n) > 0)
anorm = norm (A,1) ;
else
anorm = 1 ;
end
is_symmetric = ((m == n) && (nnz (A-A') == 0)) ;
for nrhs = 1:3
for bsparse = 0:1
b = rand (m,nrhs) ;
if (bsparse)
b = sparse (b) ;
end
%-----------------------------------------------------------------------
% test backslash and related methods
%-----------------------------------------------------------------------
for a = [1 pi (pi+1i)]
% method 0:
x = (a*A)\b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
% method 1:
S = inverse (A)/a ;
x = S*b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
% method 3:
F = testfac (A, strategy) ;
S = inverse (F)/a ;
x = S*b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
% method 4:
F = a*testfac (A, strategy) ;
x = F\b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
% method 5:
S = inverse (F) ;
x = S*b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
% method 6:
if (m == n)
[L, U, p] = lu (A, 'vector') ;
x = a * (U \ (L \ (b (p,:)))) ;
err = check_resid (err, anorm, A/a, x, b, spcheck) ;
% method 7:
if (is_symmetric)
F = a*factorize (A, 'symmetric') ;
x = F\b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
else
F = a*factorize (A, 'unsymmetric') ;
x = F\b ;
err = check_resid (err, anorm, a*A, x, b, spcheck) ;
end
end
end
clear S F
%------------------------------------------------------------------
% test transposed backslash and related methods
%------------------------------------------------------------------
b = rand (n,nrhs) ;
if (bsparse)
b = sparse (b) ;
end
for a = [1 pi (pi+1i)]
% method 0:
x = (a*A)'\b ;
err = check_resid (err, anorm, (a*A)', x, b, spcheck) ;
% method 1:
S = inverse (A) / a ;
x = S'*b ;
err = check_resid (err, anorm, (a*A)', x, b, spcheck) ;
% method 2:
F = a*testfac (A, strategy) ;
x = F'\b ;
err = check_resid (err, anorm, (a*A)', x, b, spcheck) ;
% method 3:
S = inverse (F') ;
x = S*b ;
err = check_resid (err, anorm, (a*A)', x, b, spcheck) ;
end
clear S F
%------------------------------------------------------------------
% test mtimes, times, plus, minus, rdivide, and ldivide
%------------------------------------------------------------------
for a = [1 pi pi+2i]
F = a*testfac (A, strategy) ;
S = inverse (F) ;
B = a*A ; % F is the factorization of a*A
% test mtimes
d = rand (n,1) ;
x = F*d ;
y = B*d ;
z = S\d ;
err = check_error (err, norm (mtx(x)-mtx(y),1)) ;
err = check_error (err, norm (mtx(x)-mtx(z),1)) ;
% test mtimes transpose
d = rand (m,1) ;
x = F'*d ;
y = B'*d ;
z = S'\d ;
err = check_error (err, norm (mtx(x)-mtx(y),1)) ;
err = check_error (err, norm (mtx(x)-mtx(z),1)) ;
% test for scalars
for s = [1 42 3-2i]
E = s\B - double (s\F) ; err = check_error (err, norm (E,1)) ;
E = B/s - double (F/s) ; err = check_error (err, norm (E,1)) ;
% E = B.*s - F.*s ; err = check_error (err, norm (E,1)) ;
% E = s.*B - s.*F ; err = check_error (err, norm (E,1)) ;
% E = s.\B - s.\F ; err = check_error (err, norm (E,1)) ;
% E = B./s - F./s ; err = check_error (err, norm (E,1)) ;
E = B*s - double (F*s) ; err = check_error (err, norm (E,1)) ;
E = s*B - double (s*F) ; err = check_error (err, norm (E,1)) ;
end
end
clear S F C
%------------------------------------------------------------------
% test slash and related methods
%------------------------------------------------------------------
b = rand (nrhs,n) ;
if (bsparse)
b = sparse (b) ;
end
% method 0:
x = b/A ;
err = check_resid (err, anorm, A', x', b', spcheck) ;
% method 1:
S = inverse (A) ;
x = b*S ;
err = check_resid (err, anorm, A', x', b', spcheck) ;
% method 4:
F = testfac (A, strategy) ;
x = b/F ;
err = check_resid (err, anorm, A', x', b', spcheck) ;
% method 5:
S = inverse (F) ;
x = b*S ;
err = check_resid (err, anorm, A', x', b', spcheck) ;
% method 6:
if (m == n)
[L, U, p] = lu (A, 'vector') ;
x = (b / U) / L ; x (:,p) = x ;
err = check_resid (err, anorm, A', x', b', spcheck) ;
end
%------------------------------------------------------------------
% test transpose slash and related methods
%------------------------------------------------------------------
b = rand (nrhs,m) ;
if (bsparse)
b = sparse (b) ;
end
% method 0:
x = b/A' ;
err = check_resid (err, anorm, A, x', b', spcheck) ;
% method 1:
S = inverse (A)' ;
x = b*S ;
err = check_resid (err, anorm, A, x', b', spcheck) ;
% method 4:
F = testfac (A, strategy)' ;
x = b/F ;
err = check_resid (err, anorm, A, x', b', spcheck) ;
% method 5:
S = inverse (F) ;
x = b*S ;
err = check_resid (err, anorm, A, x', b', spcheck) ;
%------------------------------------------------------------------
% test double
%------------------------------------------------------------------
Y = double (inverse (A)) ;
if (m == n)
Z = inv (A) ;
else
Z = pinv (full (A)) ;
end
e = norm (Y-Z,1) ;
if (n > 0)
e = e / norm (Z,1) ;
end
err = check_error (e, err) ;
%------------------------------------------------------------------
% test subsref
%------------------------------------------------------------------
F = testfac (A, strategy) ;
Y = inverse (A) ;
if (numel (A) > 1)
if (F (end) ~= A (end))
error ('factorization subsref error') ;
end
if (F.A (end) ~= A (end))
error ('factorization subsref error') ;
end
end
if (n > 0)
if (F (1,1) ~= A (1,1))
error ('factorization subsref error') ;
end
if (F.A (1,1) ~= A (1,1))
error ('factorization subsref error') ;
end
e = abs (Y (1,1) - Z (1,1)) ;
err = check_error (e,err) ;
if (m > 1 && n > 1)
e = norm (Y (1:2,1:2) - Z (1:2,1:2), 1) ;
err = check_error (e,err) ;
end
end
if (m > 3 && n > 1)
if (any (F (2:end, 1:2) - A (2:end, 1:2)))
error ('factorization subsref error') ;
end
if (any (F (2:4, :) - A (2:4, :)))
error ('factorization subsref error') ;
end
if (any (F (:, 1:2) - A (:, 1:2)))
error ('factorization subsref error') ;
end
end
%------------------------------------------------------------------
% test transposed subsref
%------------------------------------------------------------------
FT = F' ;
YT = Y' ;
AT = A' ;
ZT = Z' ;
if (numel (AT) > 1)
if (FT (end) ~= AT (end))
error ('factorization subsref error') ;
end
if (F.A (end) ~= A (end))
error ('factorization subsref error') ;
end
end
if (n > 0)
if (FT (1,1) ~= AT (1,1))
error ('factorization subsref error') ;
end
if (F.A (1,1) ~= A (1,1))
error ('factorization subsref error') ;
end
e = abs (YT (1,1) - ZT (1,1)) ;
err = check_error (e,err) ;
if (m > 1 && n > 1)
e = norm (YT (1:2,1:2) - ZT (1:2,1:2), 1) ;
err = check_error (e,err) ;
end
end
if (m > 1 && n > 3)
if (any (FT (2:end, 1:2) - AT (2:end, 1:2)))
error ('factorization subsref error') ;
end
if (any (FT (2:4, :) - AT (2:4, :)))
error ('factorization subsref error') ;
end
if (any (FT (:, 1:2) - AT (:, 1:2)))
error ('factorization subsref error') ;
end
end
%------------------------------------------------------------------
% test update/downdate
%------------------------------------------------------------------
if (isa (F, 'factorization_chol_dense'))
w = rand (n,1) ;
b = rand (n,1) ;
% update
G = cholupdate (F,w) ;
x = G\b ;
err = check_resid (err, anorm, A+w*w', x, b, spcheck) ;
% downdate
G = cholupdate (G,w,'-') ;
x = G\b ;
err = check_resid (err, anorm, A, x, b, spcheck) ;
clear G
end
%------------------------------------------------------------------
% test size
%------------------------------------------------------------------
[m1, n1] = size (F) ;
[m, n] = size (A) ;
if (m1 ~= m || n1 ~= n)
error ('size error') ;
end
[m1, n1] = size (Y) ;
if (m1 ~= n || n1 ~= m)
error ('pinv size error') ;
end
if (size (Y,1) ~= n || size (Y,2) ~= m)
error ('pinv size error') ;
end
if (size (F,1) ~= m || size (F,2) ~= n)
error ('size error') ;
end
%------------------------------------------------------------------
% test mtimes
%------------------------------------------------------------------
clear S F Y
for a = [1 pi pi+2i]
F = a * testfac (A, strategy) ;
S = inverse (F) ;
d = rand (1,m) ;
x = d*F ;
y = d*(A*a) ;
z = d/S ;
err = check_error (err, norm (mtx(x)-mtx(y),1)) ;
err = check_error (err, norm (mtx(x)-mtx(z),1)) ;
d = rand (1,n) ;
x = d*F' ;
y = d*(A*a)' ;
z = d/S' ;
err = check_error (err, norm (mtx(x)-mtx(y),1)) ;
err = check_error (err, norm (mtx(x)-mtx(z),1)) ;
end
%------------------------------------------------------------------
% test inverse
%------------------------------------------------------------------
Y = double (inverse (inverse (A))) ;
e = norm (A-Y,1) ;
if (e > 0)
error ('inverse error') ;
end
%------------------------------------------------------------------
% test mldivide and mrdivide with a matrix b, transpose, etc
%------------------------------------------------------------------
if (max (m,n) < 100)
F = testfac (A, strategy) ;
B = rand (m,n) ;
err = check_error (err, norm (B\A - mtx(B\F), 1) / anorm) ;
err = check_error (err, norm (A/B - mtx(F/B), 1) / anorm) ;
err = check_error (err, norm (B*pinv(full(A))-mtx(B/F), 1) / anorm);
end
end
end
fprintf ('.') ;
%--------------------------------------------------------------------------
function err = check_resid (err, anorm, A, x, b, spcheck)
[m, n] = size (A) ;
x = mtx (x) ;
if (m <= n)
e = norm (A*x-b,1) / (anorm + norm (x,1)) ;
else
e = norm (A'*(A*x)-A'*b,1) / (anorm + norm (x,1)) ;
end
if (min (m,n) > 1 && spcheck)
if (issparse (A) && issparse (b))
if (~issparse (x))
error ('x must be sparse') ;
end
else
if (issparse (x))
error ('x must be full') ;
end
end
end
err = check_error (e, err) ;
%--------------------------------------------------------------------------
function x = mtx (x)
% make sure that x is a matrix. It might be a factorization.
if (isobject (x))
x = double (x) ;
end
%--------------------------------------------------------------------------
function err = check_error (err1, err2)
err = max (err1, err2) ;
if (err > 1e-8)
fprintf ('error: %8.3e\n', full (err)) ;
error ('error too high') ;
end
err = full (err) ;
%--------------------------------------------------------------------------
function F = testfac (A, strategy)
if (isempty (strategy))
F = factorize (A) ;
else
F = factorize (A, strategy) ;
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
test_disp.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/Test/test_disp.m
| 6,016 |
utf_8
|
457e71942dd7611721712b8b00e42ac2
|
function test_disp
%TEST_DISP test the display method of the factorize object
%
% Example
% test_disp
%
% See also factorize, test_all.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
reset_rand ;
tol = 1e-10 ;
err = 0 ;
%-------------------------------------------------------------------------------
% dense LU
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense LU factorization:\n') ;
A = rand (3) ;
[err,F] = test_factorization (A, tol, err, [ ], 'factorization_lu_dense') ;
fprintf ('\nDense LU With an imaginary F.alpha: ') ;
alpha = (pi + 2i) ;
F = alpha*F ;
display (F) ;
b = rand (3,1) ;
x = F\b ;
y = (alpha*A)\b ;
err = norm (x-y) ;
if (err > tol)
error ('error too high: %g\n', err) ;
end
fprintf ('error %g\n', err) ;
%-------------------------------------------------------------------------------
% sparse LU
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse LU factorization:\n') ;
A = sparse (A) ;
err = test_factorization (A, tol, err, [ ], 'factorization_lu_sparse') ;
%-------------------------------------------------------------------------------
% dense Cholesky
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense Cholesky factorization:\n') ;
A = A*A' + eye (3) ;
err = test_factorization (A, tol, err, [ ], 'factorization_chol_dense') ;
%-------------------------------------------------------------------------------
% sparse Cholesky
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse Cholesky factorization:\n') ;
A = sparse (A) ;
err = test_factorization (A, tol, err, [ ], 'factorization_chol_sparse') ;
%-------------------------------------------------------------------------------
% dense QR of A
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense QR factorization:\n') ;
A = rand (3,2) ;
err = test_factorization (A, tol, err, 'qr', 'factorization_qr_dense') ;
%-------------------------------------------------------------------------------
% dense COD of A
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense COD factorization:\n') ;
err = test_factorization (A, tol, err, [ ], 'factorization_cod_dense') ;
%-------------------------------------------------------------------------------
% sparse COD of A
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse COD factorization:\n') ;
A = sparse (A) ;
err = test_factorization (A, tol, err, 'cod', 'factorization_cod_sparse') ;
%-------------------------------------------------------------------------------
% dense QR of A'
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense QR factorization of A'':\n') ;
A = full (A) ;
err = test_factorization (A', tol, err, 'qr', 'factorization_qrt_dense') ;
%-------------------------------------------------------------------------------
% sparse QR of A
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse QR factorization:\n') ;
A = sparse (A) ;
err = test_factorization (A, tol, err, [ ], 'factorization_qr_sparse') ;
%-------------------------------------------------------------------------------
% sparse QR of A'
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse QR factorization of A'':\n') ;
err = test_factorization (A', tol, err, [ ], 'factorization_qrt_sparse') ;
%-------------------------------------------------------------------------------
% svd
%-------------------------------------------------------------------------------
fprintf ('\n----------SVD factorization:\n') ;
err = test_factorization (A, tol, err, 'svd', 'factorization_svd') ;
%-------------------------------------------------------------------------------
% dense LDL
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense LDL factorization:\n') ;
A = rand (3) ;
A = [zeros(3) A ; A' zeros(3)] ;
err = test_factorization (A, tol, err, 'ldl', 'factorization_ldl_dense') ;
%-------------------------------------------------------------------------------
% sparse LDL
%-------------------------------------------------------------------------------
fprintf ('\n----------Sparse LDL factorization:\n') ;
A = sparse (A) ;
err = test_factorization (A, tol, err, 'ldl', 'factorization_ldl_sparse') ;
%-------------------------------------------------------------------------------
% test QR and QR' with scalar A and sparse right-hand side
%-------------------------------------------------------------------------------
fprintf ('\n----------Dense QR and QR'' with scalar A and sparse b:\n') ;
b = sparse ([1 2]) ;
A = pi ;
F = factorization_qr_dense (A,0) ;
display (F) ;
x = F\b ;
err = max (err, norm (A\b - x)) ;
x = b'/F ;
err = max (err, norm (b'/A - x)) ;
F = factorization_qrt_dense (A,0) ;
display (F) ;
x = F\b ;
err = max (err, norm (A\b - x)) ;
x = b'/F ;
err = max (err, norm (b'/A - x)) ;
if (err > tol)
error ('error too high: %g\n', err) ;
end
fprintf ('\nAll disp tests passed, max error: %g\n', err) ;
%-------------------------------------------------------------------------------
function [err, F] = test_factorization (A, tol, err, option, kind)
%TEST_FACTORIZATION factorize a matrix and check its kind and error norm
F = factorize (A, option, 1) ;
display (F) ;
S = inverse (F) ;
display (S) ;
err2 = error_check (F) ;
fprintf ('error: %g\n', err2) ;
err = max (err, err2) ;
if (err > tol)
error ('error too high: %g\n', err) ;
end
if (F.is_inverse || ~isa (F, kind))
error ('invalid contents') ;
end
if (~(S.is_inverse) || ~isa (S, kind))
error ('invalid contents') ;
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
test_svd.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/Test/test_svd.m
| 6,212 |
utf_8
|
6302c745225348ed8b5a230f4441477b
|
function err = test_svd (A)
%TEST_SVD test factorize(A,'svd') and factorize(A,'cod') for a given matrix
%
% Example
% err = test_svd (A) ;
%
% See also test_all
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
fprintf ('.') ;
if (nargin < 1)
% has rank 3
A = magic (4) ;
end
[m, n] = size (A) ;
err = 0 ;
for st = 0:1
if (st == 0)
F = factorize (A, 'svd') ;
Acond = cond (F) ;
else
F = factorize (A, 'cod') ;
end
Apinv = pinv (full (A)) ;
if (st == 0)
assert (ismethod (F, 'norm')) ;
assert (ismethod (F, 'pinv')) ;
Anorm = norm (full (A)) ;
Ainvnorm = norm (pinv (full (A))) ;
Fnorm = norm (F) ;
e = abs (Anorm - Fnorm) ;
Anorm = max (Anorm, Fnorm) ;
if (Anorm > 0)
e = e / Anorm ;
end
err = check_err (err, e) ;
Anorm = max (Anorm, 1) ;
end
% if B=pinv(A), then A*B*A=A and B*A*B=B
B = inverse (F) ;
Bnorm = norm (double (B), 1) ;
err = check_err (err, ...
norm (double(A*B*A) - A, 1) / (Anorm^2 * Bnorm)) ;
err = check_err (err, ...
norm (double(B*A*B) - double(B), 1) / (Anorm * Bnorm^2)) ;
for bsparse = 0:1
b = rand (m, 1) ;
if (bsparse)
b = sparse (b) ;
end
x = Apinv*b ;
y = F\b ;
if (st == 0)
z = pinv(F)*b ;
else
z = inverse (F)*b ;
end
if (st == 0 || Acond < 1e13)
% skip this for COD for very ill-conditioned problems
x = double (x) ;
y = double (y) ;
z = double (z) ;
err = check_err (err, norm (x - y) / (Anorm * norm (x) + norm (b)));
err = check_err (err, norm (x - z) / (Anorm * norm (x) + norm (b)));
end
c = rand (1, n) ;
if (bsparse)
c = sparse (c) ;
end
x = c*Apinv ;
y = c/F ;
if (st == 0)
z = c*pinv(F) ;
else
z = c*inverse(F) ;
end
if (st == 0 || Acond < 1e13)
% skip this for COD for very ill-conditioned problems
x = double (x) ;
y = double (y) ;
z = double (z) ;
err = check_err (err, norm (x - y) / (Anorm * norm (x) + norm (b)));
err = check_err (err, norm (x - z) / (Anorm * norm (x) + norm (b)));
end
end
if (st == 0)
assert (ismethod (F, 'rank')) ;
arank = rank (full (A)) ;
if (arank ~= rank (F))
fprintf ('\nrank of A: %d, rank of F: %d\n', arank, rank (F)) ;
fprintf ('singular values:\n') ;
s1 = svd (A) ;
s2 = F.Factors.S ;
disp ([s1 s2])
error ('rank mismatch!') ;
end
assert (ismethod (F, 'cond')) ;
c1 = cond (full (A)) ;
c2 = cond (F) ;
if (rank (F) == min (m,n))
e = abs (c1 - c2) ;
if (max (c1, c2) > 0)
e = e / max (c1, c2) ;
end
% fprintf ('cond err: %g\n', e) ;
err = check_err (err, e) ;
else
% both c1 and c2 should be large
tol = max (m,n) * eps (norm (F)) ;
assert (c1 > norm (F) / tol) ;
assert (c2 > norm (F) / tol) ;
end
Z = null (F) ;
e = norm (A*Z) / Anorm ;
% fprintf ('null space err %g (%g)\n', e, err) ;
err = check_err (err, e) ;
[U1, S1, V1] = svd (F) ;
[U2, S2, V2] = svd (full (A)) ;
err = check_err (err, norm (U1-U2)) ;
err = check_err (err, norm (S1-S2) / Anorm) ;
err = check_err (err, norm (V1-V2)) ;
err = check_err (err, norm (U1*S1*V1'-U2*S2*V2') / Anorm) ;
[U1, S1, V1] = svd (inverse (F)) ;
[U2, S2, V2] = svd (pinv (full (A))) ;
err = check_err (err, norm (S1-S2) / Ainvnorm) ;
err = check_err (err, norm (U1*S1*V1'-U2*S2*V2') / Ainvnorm) ;
[U1, S1, V1] = svd (F, 0) ;
[U2, S2, V2] = svd (full (A), 0) ;
err = check_err (err, norm (U1-U2)) ;
err = check_err (err, norm (S1-S2) / Anorm) ;
err = check_err (err, norm (V1-V2)) ;
err = check_err (err, norm (U1*S1*V1'-U2*S2*V2') / Anorm) ;
[U1, S1, V1] = svd (F, 'econ') ;
[U2, S2, V2] = svd (full (A), 'econ') ;
err = check_err (err, norm (U1-U2)) ;
err = check_err (err, norm (S1-S2) / Anorm) ;
err = check_err (err, norm (V1-V2)) ;
err = check_err (err, norm (U1*S1*V1'-U2*S2*V2') / Anorm) ;
[U1, S1, V1] = svd (F, 'rank') ;
err = check_err (err, norm (U1*S1*V1'-U2*S2*V2') / Anorm) ;
% fprintf ('svd err %g (%g)\n', e, err) ;
% test the p-norm
for k = 0:3
if (k == 0)
p = 'inf' ;
elseif (k == 3)
p = 'fro' ;
else
p = k ;
end
n1 = norm (full (A), p) ;
n2 = norm (F, p) ;
e = abs (n1 - n2) ;
if (n1 > 1)
e = e / n1 ;
end
% fprintf ('norm (A,%d): %g\n', k, e) ;
err = check_err (err, e) ;
n1 = norm (full (A'), p) ;
n2 = norm (F', p) ;
e = abs (n1 - n2) ;
if (n1 > 1)
e = e / n1 ;
end
% fprintf ('norm (A'',%d): %g\n', k, e) ;
err = check_err (err, e) ;
n1 = norm (Apinv, p) ;
n2 = norm (pinv (F), p) ;
e = abs (n1 - n2) ;
if (n1 > 1)
e = e / n1 ;
end
% fprintf ('norm (pinv(A),%d): %g\n', k, e) ;
err = check_err (err, e) ;
n1 = norm (Apinv', p) ;
n2 = norm (pinv (F)', p) ;
e = abs (n1 - n2) ;
if (n1 > 1)
e = e / n1 ;
end
% fprintf ('norm (pinv(A)'',%d): %g\n', k, e) ;
err = check_err (err, e) ;
end
end
end
function err = check_err (err, e)
err = max (err, e) ;
if (err > 1e-6)
error ('%g error too high!\n', err) ;
end
|
github
|
twhughes/Accelerator_Inverse_Design-master
|
test_accuracy.m
|
.m
|
Accelerator_Inverse_Design-master/dependencies/Factorize/Test/test_accuracy.m
| 2,952 |
utf_8
|
5d41ae00bdefd11f286352bff8500c20
|
function err = test_accuracy
%TEST_ACCURACY test the accuracy of the factorize object
%
% Example
% err = test_accuracy
%
% See also test_all, test_factorize.
% Copyright 2011-2012, Timothy A. Davis, http://www.suitesparse.com
fprintf ('\nTesting accuracy:\n') ;
reset_rand ;
A = [ 0.1482 0.3952 0.1783 1.1601
0.3952 0.3784 0.2811 0.4893
0.1783 0.2811 1.1978 1.3837
1.1601 0.4893 1.3837 0.7520 ] ;
F = factorize (A, 'ldl', 1) ; %#ok
err = test_factorize (sparse (A)) ;
err = max (err, test_factorize (A)) ;
rect = {'', 'qr', 'cod', 'svd' } ; % methods for rectangular matrices
square = [{'lu'} rect] ; % for square matrices
sym = [{'ldl', 'symmetric'} square] ; % for symmetric
spd = [{'chol'} sym] ; % for symmetric positive definite
square = [{'unsymmetric'} square] ;
% rect
% square
% sym
% spd
% pause
fprintf ('please wait\n') ;
% small matrices: full and sparse
for n = 0:6
for im = 0:1
fprintf ('test %2d of 14 ', 2*n+im+1) ;
% unsymmetric
A = rand (n) ;
if (im == 1)
A = A + 1i * rand (n) ;
end
err = tfac (A, err, square) ;
% dense, symmetric but not always positive definite
A = A+A' ;
err = tfac (A, err, sym) ;
% symmetric positive definite
A = A'*A + eye (n) ;
err = tfac (A, err, spd) ;
% least-squares problem
A = rand (2*n,n) ;
err = tfac (A, err, rect) ;
% under-determined problem
A = A' ;
err = tfac (A, err, rect) ;
fprintf ('\n') ;
end
end
% default dense 100-by-100 matrix
err = max (err, test_factorize) ;
fprintf ('\nerr so far: %g\nplease wait ', err) ;
for im = 0:1
% sparse rectangular
A = sprandn (5,10,0.6) + speye (5,10) ;
if (im == 1)
A = A + 1i * sprandn (5,10,0.2) ;
end
err = tfac (A, err, rect) ;
err = tfac (A', err, rect) ;
% sparse, unsymmetric
load west0479
A = west0479 ;
if (im == 1)
A = A + 1i * sprand (A) ;
end
err = tfac (A, err, square) ;
% sparse, symmetric, but not positive definite
A = abs (A+A') + eps * speye (size (A,1)) ;
err = tfac (A, err, sym) ;
% sparse symmetric positive definite
A = delsq (numgrid ('L', 8)) ;
if (im == 1)
A = A + 1i * sprand (A) ;
A = A'*A ;
end
err = tfac (A, err, spd) ;
end
if (err > 1e-6)
error ('error to high! %g\n', err) ;
end
fprintf ('\nmax error is OK: %g\n', err) ;
%-------------------------------------------------------------------------------
function err = tfac (A, err, list)
for k = 1 : length (list)
method = list {k} ;
err = max (err, test_factorize (A, method)) ;
if (~issparse (A))
err = max (err, test_factorize (sparse (A), method)) ;
end
end
|
github
|
unsky/FPN-master
|
classification_demo.m
|
.m
|
FPN-master/caffe-fpn/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
|
unsky/FPN-master
|
voc_eval.m
|
.m
|
FPN-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
| 1,332 |
utf_8
|
3ee1d5373b091ae4ab79d26ab657c962
|
function res = voc_eval(path, comp_id, test_set, output_dir)
VOCopts = get_voc_opts(path);
VOCopts.testset = test_set;
for i = 1:length(VOCopts.classes)
cls = VOCopts.classes{i};
res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir);
end
fprintf('\n~~~~~~~~~~~~~~~~~~~~\n');
fprintf('Results:\n');
aps = [res(:).ap]';
fprintf('%.1f\n', aps * 100);
fprintf('%.1f\n', mean(aps) * 100);
fprintf('~~~~~~~~~~~~~~~~~~~~\n');
function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir)
test_set = VOCopts.testset;
year = VOCopts.dataset(4:end);
addpath(fullfile(VOCopts.datadir, 'VOCcode'));
res_fn = sprintf(VOCopts.detrespath, comp_id, cls);
recall = [];
prec = [];
ap = 0;
ap_auc = 0;
do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test');
if do_eval
% Bug in VOCevaldet requires that tic has been called first
tic;
[recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true);
ap_auc = xVOCap(recall, prec);
% force plot limits
ylim([0 1]);
xlim([0 1]);
print(gcf, '-djpeg', '-r0', ...
[output_dir '/' cls '_pr.jpg']);
end
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc);
res.recall = recall;
res.prec = prec;
res.ap = ap;
res.ap_auc = ap_auc;
save([output_dir '/' cls '_pr.mat'], ...
'res', 'recall', 'prec', 'ap', 'ap_auc');
rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
|
github
|
david-perez/annu-master
|
funceuler.m
|
.m
|
annu-master/functions/funceuler.m
| 174 |
iso_8859_13
|
4a2e673c31a7714183c840a267f48e59
|
% La ecuación diferencial x'(t) = x(t) tiene como solución x(t) = ce^t.
function f = funceuler(~, x, ~) % La t se declara como ~ porque no la usamos.
f = x(1);
end
|
github
|
mbrossar/FUSION2018-master
|
rukfUpdate.m
|
.m
|
FUSION2018-master/filters/rukfUpdate.m
| 1,788 |
utf_8
|
24325b68cd25a2d02a2b35e7dd34f88d
|
function [chi,omega_b,a_b,S] = rukfUpdate(chi,omega_b,a_b,...
S,y,param,R,ParamFilter)
param.Pi = ParamFilter.Pi;
param.chiC = ParamFilter.chiC;
k = length(y);
q = length(S);
N_aug = q+k;
Rc = chol(kron(eye(k/2),R));
S_aug = blkdiag(S,Rc);
% scaled unsented transform
W0 = 1-N_aug/3;
Wj = (1-W0)/(2*N_aug);
gamma = sqrt(N_aug/(1-W0));
alpha = 1;
beta = 2;
% Compute transformed measurement
X = gamma*[zeros(N_aug,1) S_aug' -S_aug'];% sigma-points
Y = zeros(k,2*N_aug+1);
Y(:,1) = h(chi,zeros(q-6,1),param,zeros(N_aug-q,1));
for j = 2:2*N_aug+1
xi_j = X([1:9 16:q],j);
v_j = X(q+1:N_aug,j);
Y(:,j) = h(chi,xi_j,param,v_j);
end
ybar = W0*Y(:,1) + Wj*sum(Y(:,2:end),2);% Measurement mean
Y(:,1) = sqrt(abs(W0+(1-alpha^2+beta)))*(Y(:,1)-ybar);
YY = sqrt(Wj)*(Y(:,2:2*N_aug+1)-ybar*ones(1,2*N_aug));
[~,Rs] = qr(YY');
Ss = Rs(1:k,1:k);
[Sy,~] = cholupdate(Ss,Y(:,1),'-'); % Sy'*Sy = Pyy
Pxy = zeros(q,k);
for j = 2:2*N_aug+1
Pxy = Pxy + Wj*X(1:q,j)*(Y(:,j)-ybar)';
end
K = Pxy*Sy^-1*Sy'^-1; % Gain
xibar = K*(y-ybar);
omega_b = omega_b + xibar(10:12);
a_b = a_b + xibar(13:15);
xibar = xibar([1:9 16:q]);
% Covariance update
A = K*Sy';
for n = 1:k
S = cholupdate(S,A(:,n),'-');
end
% Update mean state
chi = exp_multiSE3(xibar)*chi;
J = xi2calJl(xibar);
S = S*J;
end
%--------------------------------------------------------------------------
function y = h(chi,xi,param,v)
Pi = param.Pi;
chiC = param.chiC;
RotC = chiC(1:3,1:3);
xC = chiC(1:3,4);
yAmers = param.yAmers;
NbAmers = length(yAmers);
chi_j = exp_multiSE3(xi)*chi;
Rot = chi_j(1:3,1:3);
x = chi_j(1:3,5);
PosAmers = chi_j(1:3,6:end);
posAmers = PosAmers(:,yAmers);
z = Pi*( (Rot*RotC)'*(posAmers-kron(x,ones(1,NbAmers))) ...
- kron(xC,ones(1,NbAmers)));
y = z(1:2,:)./z(3,:);
y = y(:) + v;
end
|
github
|
mbrossar/FUSION2018-master
|
EsimatePosAmers.m
|
.m
|
FUSION2018-master/filters/EsimatePosAmers.m
| 2,093 |
utf_8
|
98a1882400a96d76ab9789928887664e
|
function [points3d, errors] = EsimatePosAmers(pointTracks, ...
camPoses, cameraParams)
numTracks = numel(pointTracks);
points3d = zeros(numTracks, 3);
numCameras = size(camPoses, 2);
cameraMatrices = containers.Map('KeyType', 'uint32', 'ValueType', 'any');
for i = 1:numCameras
id = camPoses(i).ViewId;
R = camPoses(i).Orientation;
t = camPoses(i).Location;
size_t = size(t);
if size_t(1) == 3
t = t';
end
cameraMatrices(id) = cameraMatrix(cameraParams, R', -t*R');
end
for i = 1:numTracks
track = pointTracks(i);
points3d(i, :) = triangulateOnePoint(track, cameraMatrices);
end
if nargout > 1
[~, errors] = reprojectionErrors(points3d, cameraMatrices, pointTracks);
end
%--------------------------------------------------------------------------
function point3d = triangulateOnePoint(track, cameraMatrices)
% do the triangulation
numViews = numel(track.ViewIds);
A = zeros(numViews * 2, 4);
for i = 1:numViews
id = track.ViewIds(i);
P = cameraMatrices(id)';
A(2*i - 1, :) = track.Points(i, 1) * P(3,:) - P(1,:);
A(2*i , :) = track.Points(i, 2) * P(3,:) - P(2,:);
end
[~,~,V] = svd(A);
X = V(:, end);
X = X/X(end);
point3d = X(1:3)';
%--------------------------------------------------------------------------
function [errors, meanErrorsPerTrack] = reprojectionErrors(points3d, ...
cameraMatrices, tracks)
numPoints = size(points3d, 1);
points3dh = [points3d, ones(numPoints, 1)];
meanErrorsPerTrack = zeros(numPoints, 1);
errors = [];
for i = 1:numPoints
p3d = points3dh(i, :);
reprojPoints2d = reprojectPoint(p3d, tracks(i).ViewIds, cameraMatrices);
e = sqrt(sum((tracks(i).Points - reprojPoints2d).^2, 2));
meanErrorsPerTrack(i) = mean(e);
errors = [errors; e];
end
%--------------------------------------------------------------------------
function points2d = reprojectPoint(p3dh, viewIds, cameraMatrices)
numPoints = numel(viewIds);
points2d = zeros(numPoints, 2);
for i = 1:numPoints
p2dh = p3dh * cameraMatrices(viewIds(i));
points2d(i, :) = p2dh(1:2) ./ p2dh(3);
end
|
github
|
mbrossar/FUSION2018-master
|
manageAmers.m
|
.m
|
FUSION2018-master/filters/manageAmers.m
| 5,456 |
utf_8
|
bf85aa3a6e9c58d710fe3434db202d1f
|
function [S,PosAmers,ParamFilter,trackerBis,myTracks,PosAmersNew,...
IdxAmersNew,trackCov,pointsMain,validityMain] = manageAmers(S,...
PosAmers,ParamFilter,ParamGlobal,trackerBis,trajFilter,I,...
pointsMain,validityMain,IdxImage,myTracks,pointsBis)
PosAmersNew = [];
IdxAmersNew = [];
trackCov = [];
MaxAmersNew = 10;
if sum(validityMain) < ParamFilter.NbAmersMin && I>120
P = S'*S; %not computianny efficient
NbAmersNew = min(sum(validityMain == 0),MaxAmersNew);
[PosAmersNew,trackPoints,trackerBis,myTracks,trackCov] = ObserveAmersNew(ParamFilter,ParamGlobal,...
trajFilter,I,IdxImage,trackerBis,myTracks,NbAmersNew,pointsMain,pointsBis,S);
j = 1;
IdxAmersNew = zeros(length(trackCov),1);
IdxAmersOld = find(validityMain == 0);
%if number of new landmarks is small
IdxAmersOld = IdxAmersOld(1:length(trackCov));
for ii = 1:length(IdxAmersOld)
idxAmersOld = IdxAmersOld(ii);
idxP = 15+(3*idxAmersOld-2:3*idxAmersOld);
P(:,idxP) = 0;
P(idxP,:) = 0;
P(idxP,idxP) = trackCov{j};
PosAmers(:,idxAmersOld) = PosAmersNew(j,:)';
pointsMain(idxAmersOld,:) = trackPoints(:,j);
validityMain(idxAmersOld) = 1;
IdxAmersNew(j) = idxAmersOld;
j = j+1;
end
if sum(pointsMain(:) < 0) > 0
validityMain(pointsMain(:,1)<0) = 0;
validityMain(pointsMain(:,2)<0) = 0;
pointsMain(pointsMain(:)<0) = 1;
end
S = chol(P); %not computianny efficient
end
end
%--------------------------------------------------------------------------
function [posAmersNew,trackPoints,trackerBis,myTracks,trackCov] = ...
ObserveAmersNew(ParamFilter,ParamGlobal,trajFilter,...
I,IdxImage,trackerBis,myTracks,NbAmersNew,pointsMain,pointsBis,S)
% compute estimated locations for new landmarks
cameraParams = ParamFilter.cameraParams;
dirImage = ParamGlobal.dirImage;
fileImages = ParamGlobal.fileImages;
image = strcat(dirImage,int2str(fileImages(IdxImage)),'.png');
image = undistortImage(imread(image),cameraParams);
Newpoints = detectMinEigenFeatures(image);
Newpoints = selectUniform(Newpoints,NbAmersNew+150,size(image));
%number of views of candidate points
nbViews = zeros(1,length(myTracks));
for i = 1:length(myTracks)
nbViews(i) = length(myTracks(i).ViewIds);
end
% tracking new points
posAmersNew = zeros(NbAmersNew,3);
trackPoints = ones(2,NbAmersNew);
trackCov = cell(NbAmersNew,1);
i = 1;
nbViewsMin = 7;
errorMax = 0.5;
PixelMin = 30;
while i <= NbAmersNew
ok = 0;
% find possible new point
while ok == 0
nbViews2 = find(nbViews>nbViewsMin);
if isempty(nbViews2)
if(nbViewsMin > 3)
nbViewsMin = nbViewsMin - 1;
end
[trackerBis,myTracks] = razTrackerBis(ParamGlobal,ParamFilter,I,IdxImage,myTracks);
for ii = 1:length(myTracks)
nbViews(ii) = length(myTracks(ii).ViewIds);
end
errorMax = errorMax+1;
nbViews2 = find(nbViews>nbViewsMin);
end
idx = randsample(nbViews2,1);
ok = 1;
pNew = myTracks(idx).Points(end,:);
idxViewNew = myTracks(idx).ViewIds(end);
for ii = 1:ParamFilter.NbAmers
if norm(pNew-pointsMain(ii,:)) < PixelMin || idxViewNew < I
ok = 0;
break
end
end
nbIdx = nbViews(idx);
nbViews(idx) = 0;
end
% estimate location
iReal = myTracks(idx).ViewIds(1);
Rot = squeeze(trajFilter.Rot(:,:,iReal));
x = trajFilter.x(:,iReal);
camPoses = struct('ViewId',myTracks(idx).ViewIds(1),...
'Orientation',Rot,'Location',x,'S',S);
try
for ii = 2:nbViewsMin% to be more time efficient (else use 2:nbIdx)
iReal = myTracks(idx).ViewIds(round(ii/nbViewsMin*nbIdx));
Rot = squeeze(trajFilter.Rot(:,:,iReal));
x = trajFilter.x(:,iReal);
camPoses(ii).ViewId = iReal;
camPoses(ii).Orientation = Rot;
camPoses(ii).Location = x;
camPoses(ii).S = S;
end
myTracks(idx).ViewIds = myTracks(idx).ViewIds([1 round((2:nbViewsMin)*nbIdx/nbViewsMin)]);
myTracks(idx).Points = myTracks(idx).Points([1 round((2:nbViewsMin)*nbIdx/nbViewsMin)],:);
[xyzPoint,covariance] = myEsimatePosAmers(myTracks(idx),camPoses,cameraParams,ParamFilter);
errors = sum(diag(covariance(end-2:end,end-2:end)));
catch
xyzPoint = ones(1,3);
errorMax = errorMax*2;
errors = errorMax+1;
for iii = 1:length(myTracks)
nbViews(iii) = length(myTracks(iii).ViewIds);
end
PixelMin = PixelMin/2;
end
% add is error is suficiently small
if isempty(Newpoints)
Newpoints = detectMinEigenFeatures(image);
Newpoints = selectUniform(Newpoints,NbAmersNew+150,size(image));
end
idxNew = randi(length(Newpoints),1);
if (errors < errorMax)
posAmersNew(i,:) = xyzPoint';
trackPoints(:,i) = myTracks(idx).Points(end,:)';
trackCov{i} = 3*10^-3*eye(3);%covariance(end-2:end,end-2:end);%2*10^-3*eye(3);
myTracks(idx).ViewIds = I;
myTracks(idx).Points = Newpoints(idxNew).Location;
pointsBis(idx,:) = Newpoints(idxNew).Location;
Newpoints(idxNew) = [];
i = i+1;
end
end
pointsBis(pointsBis(:)<=0) = 1;
trackerBis.setPoints(pointsBis);
end
|
github
|
mbrossar/FUSION2018-master
|
ukfRefUpdate.m
|
.m
|
FUSION2018-master/filters/ukfRefUpdate.m
| 2,508 |
utf_8
|
0ffab5e57239a98e26302370a16c3f8c
|
function [chi,v,PosAmers,omega_b,a_b,S,xidot] = ukfRefUpdate(chi,v,omega_b,a_b,...
S,y,param,R,ParamFilter,PosAmers,xidot)
param.Pi = ParamFilter.Pi;
param.chiC = ParamFilter.chiC;
k = length(y);
q = length(S);
N_aug = q+k;
Rc = chol(kron(eye(k/2),R));
S_aug = blkdiag(S,Rc);
% scaled unsented transform
W0 = 1-N_aug/3;
Wj = (1-W0)/(2*N_aug);
gamma = sqrt(N_aug/(1-W0));
alpha = 1;
beta = 2;
% Compute transformed measurement
X = gamma*[zeros(N_aug,1) S_aug' -S_aug'];% sigma-points
Y = zeros(k,2*N_aug+1);
Y(:,1) = h(chi,zeros(q-9,1),param,zeros(N_aug-q,1));
for j = 2:2*N_aug+1
xi_j = X([1:3 7:9 16:q],j);
v_j = X(q+1:N_aug,j);
Y(:,j) = h(chi,xi_j,param,v_j);
end
ybar = W0*Y(:,1) + Wj*sum(Y(:,2:end),2);% Measurement mean
Y(:,1) = sqrt(abs(W0+(1-alpha^2+beta)))*(Y(:,1)-ybar);
YY = sqrt(Wj)*(Y(:,2:2*N_aug+1)-ybar*ones(1,2*N_aug));
[~,Rs] = qr(YY');
Ss = Rs(1:k,1:k);
[Sy,~] = cholupdate(Ss,Y(:,1),'-'); % Sy'*Sy = Pyy
Pxy = zeros(q,k);
for j = 2:2*N_aug+1
Pxy = Pxy + Wj*X(1:q,j)*(Y(:,j)-ybar)';
end
K = Pxy*Sy^-1*Sy'^-1; % Gain
xibar = K*(y-ybar);
omega_b = omega_b + xibar(10:12);
a_b = a_b + xibar(13:15);
xibar = xibar([1:9 16:q]);
% Covariance update
A = K*Sy';
for n = 1:k
[S,~] = cholupdate(S,A(:,n),'-');
end
PosAmers = PosAmers + reshape(xibar(10:end),[3 length(xibar(10:end))/3]);
% Update mean state
v = v + xibar(4:6);
chi = [chi(1:3,1:3) chi(1:3,5);0 0 0 1]*expSE3(xibar([1:3 7:9]));
% Parallel transport
B = vecto(xidot(1:3));
C = vecto(xidot(4:6));
alphaB = norm(xidot(1:3));
alphaC = 1/2*norm(xidot(4:6));
B = (eye(3) +1/(alphaC^2)*(1-cos(alphaB))*C + 1/(alphaC^3)*C^2)*B;
C = eye(3) + 1/(alphaC^2)*(1-cos(alphaC))*C^2 + sin(alphaB)/alphaC*C;
expA = [C zeros(3);
B eye(3)];
P = S'*S;
P([1:3 7:9],[1:3 7:9]) = expA*P([1:3 7:9],[1:3 7:9])*expA';
P([1:3 7:9],[4:6,10:end]) = expA*P([1:3 7:9],[4:6,10:end]);
P([4:6,10:end],[1:3 7:9]) = P([1:3 7:9],[4:6,10:end])';
S = chol(P);
xidot = zeros(6,1);
end
%--------------------------------------------------------------------------
function y = h(chi,xi,param,v)
Pi = param.Pi;
chiC = param.chiC;
RotC = chiC(1:3,1:3);
xC = chiC(1:3,4);
yAmers = param.yAmers;
NbAmers = length(yAmers);
chi_j = chi([1:3 5],[1:3 5])*expSE3(xi(1:6));
Rot = chi_j(1:3,1:3);
x = chi_j(1:3,4);
PosAmers = chi(1:3,6:end) + reshape(xi(7:end),[3 length(xi(7:end))/3]);
posAmers = PosAmers(:,yAmers);
z = Pi*( (Rot*RotC)'*(posAmers-kron(x,ones(1,NbAmers))) ...
- kron(xC,ones(1,NbAmers)));
y = z(1:2,:)./z(3,:);
y = y(:) + v;
end
|
github
|
mbrossar/FUSION2018-master
|
ukfUpdate.m
|
.m
|
FUSION2018-master/filters/ukfUpdate.m
| 1,933 |
utf_8
|
0c034d87cb979ce37c640d5fdf9a74b4
|
function [Rot,v,x,PosAmers,omega_b,a_b,S] = ukfUpdate(Rot,v,x,omega_b,a_b,...
S,y,param,R,ParamFilter,PosAmers)
param.Pi = ParamFilter.Pi;
param.chiC = ParamFilter.chiC;
k = length(y);
q = length(S);
N_aug = q+k;
Rc = chol(kron(eye(k/2),R));
S_aug = blkdiag(S,Rc);
% scaled unsented transform
W0 = 1-N_aug/3;
Wj = (1-W0)/(2*N_aug);
gamma = sqrt(N_aug/(1-W0));
alpha = 1;
beta = 2;
% Compute transformed measurement
X = gamma*[zeros(N_aug,1) S_aug' -S_aug'];% sigma-points
Y = zeros(k,2*N_aug+1);
Y(:,1) = h(Rot,x,zeros(q-9,1),param,zeros(N_aug-q,1));
for j = 2:2*N_aug+1
xi_j = X([1:3 7:9 16:q],j);
v_j = X(q+1:N_aug,j);
Y(:,j) = h(Rot,x,xi_j,param,v_j);
end
ybar = W0*Y(:,1) + Wj*sum(Y(:,2:end),2);% Measurement mean
Y(:,1) = sqrt(abs(W0+(1-alpha^2+beta)))*(Y(:,1)-ybar);
YY = sqrt(Wj)*(Y(:,2:2*N_aug+1)-ybar*ones(1,2*N_aug));
[~,Rs] = qr(YY');
Ss = Rs(1:k,1:k);
[Sy,~] = cholupdate(Ss,Y(:,1),'-'); % Sy'*Sy = Pyy
Pxy = zeros(q,k);
for j = 2:2*N_aug+1
Pxy = Pxy + Wj*X(1:q,j)*(Y(:,j)-ybar)';
end
K = Pxy*Sy^-1*Sy'^-1; % Gain
xibar = K*(y-ybar);
omega_b = omega_b + xibar(10:12);
a_b = a_b + xibar(13:15);
xibar = xibar([1:9 16:q]);
% Covariance update
A = K*Sy';
for n = 1:k
[S,~] = cholupdate(S,A(:,n),'-');
end
% Update mean state
Rot = Rot*expSO3(xibar(1:3));
v = v + xibar(4:6);
x = x + xibar(7:9);
PosAmers = PosAmers + reshape(xibar(10:end),[3 length(xibar(10:end))/3]);
end
%--------------------------------------------------------------------------
function y = h(Rot,x,xi,param,v)
Pi = param.Pi;
chiC = param.chiC;
RotC = chiC(1:3,1:3);
xC = chiC(1:3,4);
yAmers = param.yAmers;
NbAmers = length(yAmers);
Rot = Rot*expSO3(xi(1:3));
x = x + xi(4:6);
PosAmers = param.PosAmers + reshape(xi(7:end),[3 length(xi(7:end))/3]);
posAmers = PosAmers(:,yAmers);
z = Pi*( (Rot*RotC)'*(posAmers-kron(x,ones(1,NbAmers))) ...
- kron(xC,ones(1,NbAmers)));
y = z(1:2,:)./z(3,:);
y = y(:) + v;
end
|
github
|
mbrossar/FUSION2018-master
|
lukfUpdate.m
|
.m
|
FUSION2018-master/filters/lukfUpdate.m
| 1,788 |
utf_8
|
9b390dc82185a8f43fa24167dcce1816
|
function [chi,omega_b,a_b,S] = lukfUpdate(chi,omega_b,a_b,...
S,y,param,R,ParamFilter)
param.Pi = ParamFilter.Pi;
param.chiC = ParamFilter.chiC;
k = length(y);
q = length(S);
N_aug = q+k;
Rc = chol(kron(eye(k/2),R));
S_aug = blkdiag(S,Rc);
% scaled unsented transform
W0 = 1-N_aug/3;
Wj = (1-W0)/(2*N_aug);
gamma = sqrt(N_aug/(1-W0));
alpha = 1;
beta = 2;
% Compute transformed measurement
X = gamma*[zeros(N_aug,1) S_aug' -S_aug'];% sigma-points
Y = zeros(k,2*N_aug+1);
Y(:,1) = h(chi,zeros(q-6,1),param,zeros(N_aug-q,1));
for j = 2:2*N_aug+1
xi_j = X([1:9 16:q],j);
v_j = X(q+1:N_aug,j);
Y(:,j) = h(chi,xi_j,param,v_j);
end
ybar = W0*Y(:,1) + Wj*sum(Y(:,2:end),2);% Measurement mean
Y(:,1) = sqrt(abs(W0+(1-alpha^2+beta)))*(Y(:,1)-ybar);
YY = sqrt(Wj)*(Y(:,2:2*N_aug+1)-ybar*ones(1,2*N_aug));
[~,Rs] = qr(YY');
Ss = Rs(1:k,1:k);
[Sy,~] = cholupdate(Ss,Y(:,1),'-'); % Sy'*Sy = Pyy
Pxy = zeros(q,k);
for j = 2:2*N_aug+1
Pxy = Pxy + Wj*X(1:q,j)*(Y(:,j)-ybar)';
end
K = Pxy*Sy^-1*Sy'^-1; % Gain
xibar = K*(y-ybar);
omega_b = omega_b + xibar(10:12);
a_b = a_b + xibar(13:15);
xibar = xibar([1:9 16:q]);
% Covariance update
A = K*Sy';
for n = 1:k
S = cholupdate(S,A(:,n),'-');
end
% Update mean state
chi = chi*exp_multiSE3(xibar);
J = xi2calJr(xibar);
S = S*J;
end
%--------------------------------------------------------------------------
function y = h(chi,xi,param,v)
Pi = param.Pi;
chiC = param.chiC;
RotC = chiC(1:3,1:3);
xC = chiC(1:3,4);
yAmers = param.yAmers;
NbAmers = length(yAmers);
chi_j = chi*exp_multiSE3(xi);
Rot = chi_j(1:3,1:3);
x = chi_j(1:3,5);
PosAmers = chi_j(1:3,6:end);
posAmers = PosAmers(:,yAmers);
z = Pi*( (Rot*RotC)'*(posAmers-kron(x,ones(1,NbAmers))) ...
- kron(xC,ones(1,NbAmers)));
y = z(1:2,:)./z(3,:);
y = y(:) + v;
end
|
github
|
sremes/nonstationary-spectral-kernels-master
|
nlogp_kronecker.m
|
.m
|
nonstationary-spectral-kernels-master/matlab/nlogp_kronecker.m
| 4,732 |
utf_8
|
7045f460bbba9f2b83a5d9e1287f2885
|
function [l,g,K] = nlogp_kronecker(hyp, u, x, hyp_kernel)
% Negative marginal likelihood and gradients for the generalized spectral
% mixture product (GSM-P) kernel using Kronecker inference on a multidimensional grid.
% x: cell array of length P containing the input points along all P axes
% u: P-dimensional array of output values
% hyp: {P,A} cell array for parameters of each P dimensions and A mixture
% components
% hyp_kernels: kernels for latent functions mu(x), ell(x), sigma(x)
[P,A] = size(hyp.log_w);
% compute kernels
noise = exp(2*hyp.log_noise);
hyp.log_noise = -inf; % without noise
K = cell(P,1); dK = cell(P,1);
for p = 1:P
% unwhiten
for a = 1:A
hyp.log_mu{p,a} = hyp_kernel{p}.Lmu * (hyp.log_mu{p,a}) + (hyp_kernel{p}.mu_mu);
hyp.log_w{p,a} = hyp_kernel{p}.Lw * (hyp.log_w{p,a}) + (hyp_kernel{p}.mu_w);
hyp.log_sigma{p,a} = hyp_kernel{p}.Lsigma * (hyp.log_sigma{p,a}) + (hyp_kernel{p}.mu_sigma);
end
hyp_p = hyp;
hyp_p.log_mu = hyp.log_mu(p,:);
hyp_p.log_w = hyp.log_w(p,:);
hyp_p.log_sigma = hyp.log_sigma(p,:);
if nargout == 1
K{p} = inputdep_gibbs(x{p}, x{p}, hyp_p);
else
[K{p},~,dK{p}] = inputdep_gibbs(x{p}, x{p}, hyp_p);
end
K{p} = (K{p} + K{p}') / 2 + 1e-8*eye(numel(x{p}));
end
% compute MLL = log N(vec(u)|0, K{1} x ... x K{P} + sigma^2 I)
% following notation of GPatt of Wilson (2014) / Saatchi (2011)
Q = cell(P,1); V = cell(P,1); Qt = Q; %Vinv = V;
eig_vals = 1;
for p = 1:P
[Q{p}, V{p}] = eig(K{p} + 1e-8*eye(numel(x{p})));
Qt{p} = Q{p}';
assert(all(isreal(V{p})),'non-real eigen values');
assert(all(isreal(Q{p})),'non-real eigen vectors');
eig_vals = kron(eig_vals, diag(V{p}));
end
eig_vals = real(eig_vals + noise);
Kinv_u = kron_mv(Q, kron_mv(Qt,u(:)) ./ eig_vals);
l = 0.5 * (sum(log(eig_vals)) + u(:)'*Kinv_u(:));
% add prior terms
for p = 1:P
for a = 1:A
l = l - sum(logmvnpdf(hyp.log_mu{p,a}', hyp_kernel{p}.mu_mu*ones(1,length(x{p})), hyp_kernel{p}.K_mu)) ...
- logmvnpdf(hyp.log_sigma{p,a}', hyp_kernel{p}.mu_sigma*ones(1,length(x{p})), hyp_kernel{p}.K_sigma) ...
- logmvnpdf(hyp.log_w{p,a}', hyp_kernel{p}.mu_w*ones(1,length(x{p})), hyp_kernel{p}.K_w);
end
end
% GRADIENTS (Saatci's Thesis)
if nargout > 1
diag_QtKQs = cell(P,1);
for p = 1:P % precompute
diag_QtKQs{p} = diag(Qt{p} * K{p} * Q{p});
end
for p = 1:P
d_kernel = K;
d_diag = diag_QtKQs;
for a = 1:A
g.log_w{p,a} = zeros(length(x{p}),1);
g.log_mu{p,a} = zeros(length(x{p}),1);
g.log_sigma{p,a} = zeros(length(x{p}),1);
for n = 1:length(x{p})
% log_w
d_kernel{p} = dK{p}.log_w{a}(:,:,n);
d_diag{p} = diag(Qt{p} * d_kernel{p} * Q{p});
g.log_w{p,a}(n) = kron_deriv(d_kernel, d_diag, Kinv_u, eig_vals);
% log_mu
d_kernel{p} = dK{p}.log_mu{a}(:,:,n);
d_diag{p} = diag(Qt{p} * d_kernel{p} * Q{p});
g.log_mu{p,a}(n) = kron_deriv(d_kernel, d_diag, Kinv_u, eig_vals);
% log_sigma
d_kernel{p} = dK{p}.log_sigma{a}(:,:,n);
d_diag{p} = diag(Qt{p} * d_kernel{p} * Q{p});
g.log_sigma{p,a}(n) = kron_deriv(d_kernel, d_diag, Kinv_u, eig_vals);
end
% add prior terms and whitening
g.log_w{p,a} = hyp_kernel{p}.Lw' * (g.log_w{p,a} + hyp_kernel{p}.Kw_inv * (hyp.log_w{p,a} - hyp_kernel{p}.mu_w));
g.log_mu{p,a} = hyp_kernel{p}.Lmu' * (g.log_mu{p,a} + hyp_kernel{p}.Kmu_inv * (hyp.log_mu{p,a} - hyp_kernel{p}.mu_mu));
g.log_sigma{p,a} = hyp_kernel{p}.Lsigma' * (g.log_sigma{p,a} + hyp_kernel{p}.Ksigma_inv * (hyp.log_sigma{p,a} - hyp_kernel{p}.mu_sigma));
end
end
g.log_noise = 0.5*(-Kinv_u'*Kinv_u + sum(1./eig_vals)) * (2*noise);
end
function g = kron_deriv(d_kernel, d_diag, alpha, eig_vals)
kron_diag = 1;
for d = 1:length(d_kernel) %fliplr(1:length(d_kernel))
kron_diag = kron(kron_diag, d_diag{d});
end
trace_term = sum(kron_diag ./ eig_vals);
norm_term = alpha' * kron_mv(d_kernel, alpha);
g = -0.5*norm_term + 0.5*trace_term;
% g = -g;
% function logdet = kron_logdet(V,noise_var)
% eigen_values = diag(V{1});
% for p=2:length(V)
% v2 = diag(V{p});
% tmp = eigen_values*v2';
% eigen_values = tmp(:);
% end
% logdet = sum(log(eigen_values + noise_var));
%
% function mv = kron_mvprod(K,v)
% P = length(K);
% mv = reshape(v(:),size(K{P},1),[])' * K{P};
% for p = fliplr(1:P-1)
% mv = reshape(mv(:),size(K{p},1),[])' * K{p};
% end
% mv = mv(:);
|
github
|
sremes/nonstationary-spectral-kernels-master
|
minimize_v2.m
|
.m
|
nonstationary-spectral-kernels-master/matlab/minimize_v2.m
| 11,952 |
utf_8
|
d8aad9cf50639371a892fbcc202eed7c
|
% minimize.m - minimize a smooth differentiable multivariate function using
% LBFGS (Limited memory LBFGS) or CG (Conjugate Gradients)
% Usage: [X, fX, i] = minimize(X, F, p, other, ... )
% where
% X is an initial guess (any type: vector, matrix, cell array, struct)
% F is the objective function (function pointer or name)
% p parameters - if p is a number, it corresponds to p.length below
% p.length allowed 1) # linesearches or 2) if -ve minus # func evals
% p.method minimization method, 'BFGS', 'LBFGS' or 'CG'
% p.verbosity 0 quiet, 1 line, 2 line + warnings (default), 3 graphical
% p.mem number of directions used in LBFGS (default 100)
% other, ... other parameters, passed to the function F
% X returned minimizer
% fX vector of function values showing minimization progress
% i final number of linesearches or function evaluations
% The function F must take the following syntax [f, df] = F(X, other, ...)
% where f is the function value and df its partial derivatives. The types of X
% and df must be identical (vector, matrix, cell array, struct, etc).
%
% Copyright (C) 1996 - 2011 by Carl Edward Rasmussen, 2011-10-13.
% Permission is hereby granted, free of charge, to any person OBTAINING A COPY
% OF THIS SOFTWARE AND ASSOCIATED DOCUMENTATION FILES (THE "SOFTWARE"), TO DEAL
% IN THE SOFTWARE WITHOUT RESTRICTION, INCLUDING WITHOUT LIMITATION THE RIGHTS
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
% SOFTWARE.
function [X, fX, i] = minimize(X, F, p, varargin)
if isnumeric(p), p = struct('length', p); end % convert p to struct
if p.length > 0, p.S = 'linesearch #'; else p.S = 'function evaluation #'; end;
x = unwrap(X); % convert initial guess to vector
if ~isfield(p,'method'), if length(x) > 1000, p.method = @LBFGS;
else p.method = @BFGS; end; end % set default method
if ~isfield(p,'verbosity'), p.verbosity = 2; end % default 1 line text output
if ~isfield(p,'MFEPLS'), p.MFEPLS = 10; end % Max Func Evals Per Line Search
if ~isfield(p,'MSR'), p.MSR = 100; end % Max Slope Ratio default
f(F, X, varargin{:}); % set up the function f
[fx, dfx] = f(x); % initial function value and derivatives
if p.verbosity, printf('Initial Function Value %4.6e\r', fx); end
if p.verbosity > 2,
clf; subplot(211); hold on; xlabel(p.S); ylabel('function value');
plot(p.length < 0, fx, '+'); drawnow;
end
[x, fX, i] = feval(p.method, x, fx, dfx, p); % minimize using direction method
X = rewrap(X, x); % convert answer to original representation
if p.verbosity, printf('\n'); end
function [x, fx, i] = CG(x0, fx0, dfx0, p)
if ~isfield(p, 'SIG'), p.SIG = 0.1; end % default for line search quality
i = p.length < 0; ok = 0; % initialize resource counter
r = -dfx0; s = -r'*r; b = -1/(s-1); bs = -1; fx = fx0; % steepest descent
while i < abs(p.length)
b = b*bs/min(b*s,bs/p.MSR); % suitable initial step size using slope ratio
[x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p);
if i < 0 % if line search failed
i = -i; if ok, ok = 0; r = -dfx; else break; end % try steepest or stop
else
ok = 1; bs = b*s; % record step times slope (for slope ratio method)
r = (dfx'*(dfx-dfx0))/(dfx0'*dfx0)*r - dfx; % Polack-Ribiere CG
end
s = r'*dfx; if s >= 0, r = -dfx; s = r'*dfx; ok = 0; end % slope must be -ve
x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace old values with new ones
end
function [x, fx, i] = BFGS(x0, fx0, dfx0, p)
if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality
i = p.length < 0; ok = 0; % initialize resource counter
x = x0; fx = fx0; r = -dfx0; s = -r'*r; b = -1/(s-1); H = eye(length(x0));
while i < abs(p.length)
[x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p);
if i < 0
i = -i; if ok, ok = 0; else break; end; % try steepest or stop
else
ok = 1; t = x - x0; y = dfx - dfx0; ty = t'*y; Hy = H*y;
H = H + (ty+y'*Hy)/ty^2*t*t' - 1/ty*Hy*t' - 1/ty*t*Hy'; % BFGS update
end
r = -H*dfx; s = r'*dfx; x0 = x; dfx0 = dfx; fx = [fx; fx0];
end
function [x, fx, i] = LBFGS(x0, fx0, dfx0, p)
if ~isfield(p, 'SIG'), p.SIG = 0.5; end % default for line search quality
n = length(x0); k = 0; ok = 0; x = x0; fx = fx0; bs = -1/p.MSR;
if isfield(p, 'mem'), m = p.mem; else m = min(100, n); end % set memory size
a = zeros(1, m); t = zeros(n, m); y = zeros(n, m); % allocate memory
i = p.length < 0; % initialize resource counter
while i < abs(p.length)
q = dfx0;
for j = rem(k-1:-1:max(0,k-m),m)+1
a(j) = t(:,j)'*q/rho(j); q = q-a(j)*y(:,j);
end
if k == 0, r = -q/(q'*q); else r = -t(:,j)'*y(:,j)/(y(:,j)'*y(:,j))*q; end
for j = rem(max(0,k-m):k-1,m)+1
r = r-t(:,j)*(a(j)+y(:,j)'*r/rho(j));
end
s = r'*dfx0; if s >= 0, r = -dfx0; s = r'*dfx0; k = 0; ok = 0; end
b = bs/min(bs,s/p.MSR); % suitable initial step size (usually 1)
if isnan(r) | isinf(r) % if nonsense direction
i = -i; % try steepest or stop
else
[x, b, fx0, dfx, i] = lineSearch(x0, fx0, dfx0, r, s, b, i, p);
end
if i < 0 % if line search failed
i = -i; if ok, ok = 0; k = 0; else break; end % try steepest or stop
else
j = rem(k,m)+1; t(:,j) = x-x0; y(:,j) = dfx-dfx0; rho(j) = t(:,j)'*y(:,j);
ok = 1; k = k+1; bs = b*s;
end
x0 = x; dfx0 = dfx; fx = [fx; fx0]; % replace and add values
end
function [x, a, fx, df, i] = lineSearch(x0, f0, df0, d, s, a, i, p)
if p.length < 0, LIMIT = min(p.MFEPLS, -i-p.length); else LIMIT = p.MFEPLS; end
p0.x = 0.0; p0.f = f0; p0.df = df0; p0.s = s; p1 = p0; % init p0 and p1
j = 0; p3.x = a; wp(p0, p.SIG, 0); % set step & Wolfe-Powell conditions
if p.verbosity > 2
A = [-a a]/5; nd = norm(d);
subplot(212); hold off; plot(0, f0, 'k+'); hold on; plot(nd*A, f0+s*A, 'k-');
xlabel('distance in line search direction'); ylabel('function value');
end
while 1 % keep extrapolating as long as necessary
ok = 0; while ~ok & j < LIMIT
try % try, catch and bisect to safeguard extrapolation evaluation
j = j+1; [p3.f p3.df] = f(x0+p3.x*d); p3.s = p3.df'*d; ok = 1;
if isnan(p3.f+p3.s) | isinf(p3.f+p3.s)
error('Objective function returned Inf or NaN','');
end;
catch
if p.verbosity > 1, printf('\n'); warning(lasterr); end % warn or silence
p3.x = (p1.x+p3.x)/2; ok = 0; p3.f = NaN; % bisect, and retry
end
end
if p.verbosity > 2
plot(nd*p3.x, p3.f, 'b+'); plot(nd*(p3.x+A), p3.f+p3.s*A, 'b-'); drawnow
end
if wp(p3) | j >= LIMIT, break; end % done?
p0 = p1; p1 = p3; % move points back one unit
p3.x = p0.x + minCubic(p1.x-p0.x, p1.f-p0.f, p0.s, p1.s, 1); % cubic extrap
end
while 1 % keep interpolating as long as necessary
if p1.f > p3.f, p2 = p3; else p2 = p1; end % make p2 the best so far
if wp(p2) > 1 | j >= LIMIT, break; end % done?
p2.x = p1.x + minCubic(p3.x-p1.x, p3.f-p1.f, p1.s, p3.s, 0); % cubic interp
j = j+1; [p2.f p2.df] = f(x0+p2.x*d); p2.s = p2.df'*d;
if p.verbosity > 2
plot(nd*p2.x, p2.f, 'r+'); plot(nd*(p2.x+A), p2.f+p2.s*A, 'r'); drawnow
end
if wp(p2) > -1 & p2.s > 0 | wp(p2) < -1, p3 = p2; else p1 = p2; end % bracket
end
x = x0+p2.x*d; fx = p2.f; df = p2.df; a = p2.x; % return the value found
if p.length < 0, i = i+j; else i = i+1; end % count func evals or line searches
if p.verbosity, printf('%s %6i; value %4.6e\r', p.S, i, fx); end
if wp(p2) < 2, i = -i; end % indicate faliure
if p.verbosity > 2
if i>0, plot(norm(d)*p2.x, fx, 'go'); end
subplot(211); plot(abs(i), fx, '+'); drawnow;
end
function z = minCubic(x, df, s0, s1, extr) % minimizer of approximating cubic
INT = 0.1; EXT = 5.0; % interpolate and extrapolation limits
A = -6*df+3*(s0+s1)*x; B = 3*df-(2*s0+s1)*x;
if B<0, z = s0*x/(s0-s1); else z = -s0*x*x/(B+sqrt(B*B-A*s0*x)); end
if extr % are we extrapolating?
if ~isreal(z) | ~isfinite(z) | z < x | z > x*EXT, z = EXT*x; end % fix bad z
z = max(z, (1+INT)*x); % extrapolate by at least INT
else % else, we are interpolating
if ~isreal(z) | ~isfinite(z) | z < 0 | z > x, z = x/2; end; % fix bad z
z = min(max(z, INT*x), (1-INT)*x); % at least INT away from the boundaries
end
function y = wp(p, SIG, RHO)
persistent a b c sig rho;
if nargin == 3 % if three arguments, then set up the Wolfe-Powell conditions
a = RHO*p.s; b = p.f; c = -SIG*p.s; sig = SIG; rho = RHO; y= 0;
else
if p.f > a*p.x+b % function value too large?
if a > 0, y = -1; else y = -2; end
else
if p.s < -c, y = 0; elseif p.s > c, y = 1; else y = 2; end
% if sig*abs(p.s) > c, a = rho*p.s; b = p.f-a*p.x; c = sig*abs(p.s); end
end
end
function [fx, dfx] = f(varargin)
persistent F p;
if nargout == 0
p = varargin; if ischar(p{1}), F = str2func(p{1}); else F = p{1}; end
else
[fx, dfx] = F(rewrap(p{2}, varargin{1}), p{3:end}); dfx = unwrap(dfx);
end
function v = unwrap(s) % extract num elements of s (any type) into v (vector)
v = [];
if isnumeric(s)
v = s(:); % numeric values are recast to column vector
elseif isstruct(s)
v = unwrap(struct2cell(orderfields(s))); % alphabetize, conv to cell, recurse
elseif iscell(s) % cell array elements are
for i = 1:numel(s), v = [v; unwrap(s{i})]; end % handled sequentially
end % other types are ignored
function [s v] = rewrap(s, v) % map elements of v (vector) onto s (any type)
if isnumeric(s)
if numel(v) < numel(s)
error('The vector for conversion contains too few elements')
end
s = reshape(v(1:numel(s)), size(s)); % numeric values are reshaped
v = v(numel(s)+1:end); % remaining arguments passed on
elseif isstruct(s)
[s p] = orderfields(s); p(p) = 1:numel(p); % alphabetize, store ordering
[t v] = rewrap(struct2cell(s), v); % convert to cell, recurse
s = orderfields(cell2struct(t,fieldnames(s),1),p); % conv to struct, reorder
elseif iscell(s)
for i = 1:numel(s) % cell array elements are handled sequentially
[s{i} v] = rewrap(s{i}, v);
end
end % other types are not processed
function printf(varargin)
fprintf(varargin{:}); if exist('fflush','builtin'), fflush(stdout); end
|
github
|
sremes/nonstationary-spectral-kernels-master
|
init_inputdep.m
|
.m
|
nonstationary-spectral-kernels-master/matlab/init_inputdep.m
| 1,722 |
utf_8
|
38d3396e051fdbc067e65354747ad7bf
|
function hyp = init_inputdep(u,x,A,ell)
% Init the GSM kernel by fitting GMM's on the spectrogram of the data.
% u: signal values
% x: input points (regularly spaced!)
% A: number of mixture components in GSM
% ell: length-scale of gaussian kernel to be used for interpolating from spectrogram -> x
N = length(x); dt = max(x) - min(x);
Fs = N/dt;
% compute spectrogram at frequencies F and time points T
[S,F,T] = spectrogram(u,[],[],[],Fs);
idx = (F < 0.5 | F > (Fs/4)); % remove very small/big freqs
S = S(~idx,:); F = F(~idx);
spectrogram(u,[],[],[],Fs)
% find A peaks at the first time point, and find the closest peaks at next
% the time points, interpolate linearly between the time points
[mu(:,1),sigma(:,1),w(:,1),prev] = fit_gmm_spec_density(F,S(:,1),A);
for t = 2:length(T)
[mu(:,t),sigma(:,t),w(:,t),prev] = fit_gmm_spec_density(F,S(:,t),A,prev);
end
Kxt = gausskernel(x,T'-1,ell);
Ktt = gausskernel(T'-1,T'-1,ell,1,1e-1);
for a = 1:A
hyp.log_mu{a} = Kxt*(Ktt \ logit(mu(a,:)',Fs/2));
hyp.log_sigma{a} = Kxt*(Ktt \ log(2./sqrt(sigma(a,:)')));
hyp.log_w{a} = Kxt*(Ktt \ log(std(u)*sqrt(w(a,:)')));
end
hyp.log_noise = 0;
function [mu,sigma,w,gm] = fit_gmm_spec_density(F,S,A,prev)
%% fit GMM on a spectral density
% create a fake dataset from the density
lS = max(0,log(abs(S(:,1)).^2));
area = trapz(F,lS);
cdf = cumtrapz(F,lS) / area;
nsamp = 1e5;
[cdf,idx] = unique(cdf);
X = interp1(cdf,F(idx),rand(nsamp,1),'linear',0);
% fit gmm
if ~exist('prev','var')
gm = fitgmdist(X,A);% plot((0:.01:50),pdf(gm,(0:.01:50)'));
else
gm = fitgmdist(X,A,'Start',prev);% plot((0:.01:50),pdf(gm,(0:.01:50)'));
end
mu = gm.mu; sigma = gm.Sigma(:); w = gm.ComponentProportion;
gm = struct(gm);
|
github
|
sremes/nonstationary-spectral-kernels-master
|
inputdep_gibbs.m
|
.m
|
nonstationary-spectral-kernels-master/matlab/inputdep_gibbs.m
| 4,002 |
utf_8
|
f5db007b932baecce70edf9cf6df0838
|
function [K,dhyp,dKdt] = inputdep_gibbs(x, y, hyp, hyp_kernels)
%% Generalized spectral mixture (GSM) kernel
% x, y: input points
% hyp: kernel hyperparameters (latent functions mu(x), ell(x) and sigma(x))
% hyp_kernels: kernels for latent functions mu(x), ell(x), sigma(x)
K = zeros(size(x,1),size(y,1));
A = length(hyp.log_w);
N = size(x,1);
Ny = size(y,1);
P = size(x,2);
for a = 1:A
l = exp(hyp.log_sigma{a}); l_y = l;
% limit mu by half the Nyquist frequency
Fs = N ./ (max(x(:)) - min(x(:))); Fn = Fs/2;
mu = Fn ./ (1+exp(-hyp.log_mu{a})); mu_y = mu;
w = exp(hyp.log_w{a}); w_y = w;
if nargin == 4 % test data case, interpolate the latent functions
Kxy = gausskernel(x,y,hyp_kernels.ell,hyp_kernels.sigma,hyp_kernels.omega);
l_y = exp(hyp_kernels.mu_sigma+Kxy'*(hyp_kernels.K_sigma\(hyp.log_sigma{a}-hyp_kernels.mu_sigma)));
mu_y = Fn ./ (1+exp(-hyp_kernels.mu_mu-Kxy'*(hyp_kernels.K_mu\(hyp.log_mu{a}-hyp_kernels.mu_mu))));
w_y = exp(hyp_kernels.mu_w+Kxy'*(hyp_kernels.K_w\(hyp.log_w{a}-hyp_kernels.mu_w)));
end
l2 = l.^2*ones(Ny,1)' + ones(N,1)*l_y.^2';
D = pdist2(x,y,'squaredeuclidean');
E = sqrt(2*(l*l_y')./(l2)).*exp(-D./l2);
phi1 = [cos(2*pi*sum(mu.*x,2)) 1*sin(2*pi*sum(mu.*x,2))];
phi2 = [cos(2*pi*sum(mu_y.*y,2)) 1*sin(2*pi*sum(mu_y.*y,2))];
Ka = (w*w_y') .* E .* (phi1*phi2');
K = K + Ka;
if nargout > 1 % compute gradients as well
% w
oneN = ones(N,1);
tmp = (oneN*w' + w*oneN') .* E .* (phi1*phi2');
dK.log_w{a} = @(R) diag(R * tmp) .* w; % Seems OK (checkgrad)
if nargout > 2
dKdt.log_w{a} = zeros([ N N N ]);
for n = 1:N
n1 = zeros(N,1); n1(n) = 1;
dKdt.log_w{a}(:,:,n) = (oneN*n1' + n1*oneN') .* tmp * w(n) * .5;
end
end
% mu
const = (w*w') .* E;
temp_funs = cell(N,P);
phi1 = sparse(phi1);
phi2 = sparse(phi2);
for d = 1:P
dphi1 = [-2*pi*x(:,d).*sin(2*pi*sum(mu.*x,2)), 2*pi*x(:,d).*cos(2*pi*sum(mu.*x,2))];
dKdt.log_mu{a} = zeros([N N N]);
for n=1:N
dphi = sparse(N,2); dphi(n,:) = dphi1(n,:);
tmp = full(const .* (dphi*phi2' + phi1*dphi'));
temp_funs{n,d} = @(R) sum(R(:) .* tmp(:)) * mu(n,d) * (1-mu(n,d)/Fn);
if nargout > 2
dKdt.log_mu{a}(:,:,n) = tmp * mu(n,d) * (1-mu(n,d)/Fn);
end
end
end
dK.log_mu{a} = @(R) cellfun(@(f) f(R), temp_funs); % seems good!
phi1 = full(phi1);
phi2 = full(phi2);
% sigma
const = (w*w') .* (phi1*phi2');
temp_funs = cell(N,1);
dKdt.log_sigma{a} = zeros([N N N]);
for n = 1:N
tmp = zeros(N,N);
for i = 1:N
for j = 1:N
if (i==n) || (j==n)
XX = l(i); YY = l(j);
tmp(i,j) = -YY.*(XX.^4 - YY.^4 -4*XX.^2.*D(i,j))./(sqrt(2*XX.*YY./(XX.^2+YY.^2)).*(XX.^2+YY.^2).^3).*E(i,j);
tmp(j,i) = tmp(i,j);
end
end
end
temp_funs{n} = @(R) sum(R(:).*const(:).*tmp(:)) * (l(n));
if nargout > 2
dKdt.log_sigma{a}(:,:,n) = const .* tmp * l(n);
end
end
dK.log_sigma{a} = @(R) cellfun(@(f) f(R), temp_funs);
end
end
if nargin < 4
K = K + exp(hyp.log_noise)*eye(N);
end
if nargout > 1
dK.log_noise = @(R) sum(R(:)) * exp(hyp.log_noise);
dhyp = @(R) dirder(R,dK);
end
function dhyp = dirder(R,dK)
A = length(dK.log_w);
for field = fieldnames(dK)'
tmp = cell(A,1);
fs = dK.(field{1});
if iscell(fs)
for a = 1:A
f = fs{a};
tmp{a} = f(R);
end
dhyp.(field{1}) = tmp;
else
dhyp.(field{1}) = fs(R);
end
end
|
github
|
mitkof6/opensim-task-space-master
|
save2pdf.m
|
.m
|
opensim-task-space-master/matlab/printSimulationResults/save2pdf.m
| 2,129 |
utf_8
|
c3cd2d01c93be3193fe80d7c4d72978c
|
%SAVE2PDF Saves a figure as a properly cropped pdf
%
% save2pdf(pdfFileName,handle,dpi)
%
% - pdfFileName: Destination to write the pdf to.
% - handle: (optional) Handle of the figure to write to a pdf. If
% omitted, the current figure is used. Note that handles
% are typically the figure number.
% - dpi: (optional) Integer value of dots per inch (DPI). Sets
% resolution of output pdf. Note that 150 dpi is the Matlab
% default and this function's default, but 600 dpi is typical for
% production-quality.
%
% Saves figure as a pdf with margins cropped to match the figure size.
% (c) Gabe Hoffmann, [email protected]
% Written 8/30/2007
% Revised 9/22/2007
% Revised 1/14/2007
function save2pdf(pdfFileName,handle,dpi)
% Verify correct number of arguments
error(nargchk(0,3,nargin));
% If no handle is provided, use the current figure as default
if nargin<1
[fileName,pathName] = uiputfile('*.pdf','Save to PDF file:');
if fileName == 0; return; end
pdfFileName = [pathName,fileName];
end
if nargin<2
handle = gcf;
end
if nargin<3
dpi = 150;
end
% Backup previous settings
prePaperType = get(handle,'PaperType');
prePaperUnits = get(handle,'PaperUnits');
preUnits = get(handle,'Units');
prePaperPosition = get(handle,'PaperPosition');
prePaperSize = get(handle,'PaperSize');
% Make changing paper type possible
set(handle,'PaperType','<custom>');
% Set units to all be the same
set(handle,'PaperUnits','inches');
set(handle,'Units','inches');
% Set the page size and position to match the figure's dimensions
paperPosition = get(handle,'PaperPosition');
position = get(handle,'Position');
set(handle,'PaperPosition',[0,0,position(3:4)]);
set(handle,'PaperSize',position(3:4));
% Save the pdf (this is the same method used by "saveas")
print(handle,'-dpdf',pdfFileName,sprintf('-r%d',dpi))
% Restore the previous settings
set(handle,'PaperType',prePaperType);
set(handle,'PaperUnits',prePaperUnits);
set(handle,'Units',preUnits);
set(handle,'PaperPosition',prePaperPosition);
set(handle,'PaperSize',prePaperSize);
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/08_gui_equalization/gui.m
| 3,839 |
utf_8
|
c0d9ae1e216da5ea81090b92e31d724a
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 30-Aug-2017 10:42:43
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in histogramButton.
function histogramButton_Callback(hObject, eventdata, handles)
% hObject handle to histogramButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set ( handles.histogramButton, 'BackgroundColor', 'g' )
axes(handles.imageAxes)
img = imread('tulips.jpg');
imshow(img)
axis off
% axis image
axes(handles.histogramAxes)
histogram = get_histogram(rgb2gray(img));
bar(histogram)
% axis bar
% --- Executes on button press in equalizationButton.
function equalizationButton_Callback(hObject, eventdata, handles)
% hObject handle to equalizationButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set ( handles.equalizationButton, 'BackgroundColor', 'r')
axes(handles.imageAxes)
img = rgb2gray(imread('tulips.jpg'));
equalized_image = equalize_image(img);
imshow(equalized_image);
axis off
% axis image
axes(handles.histogramAxes)
histogram = get_histogram(equalized_image);
bar(histogram)
% axis bar
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/13_gui_filters/gui.m
| 5,331 |
utf_8
|
7ea5de5ff311db43a42b861d7259b27d
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 01-Oct-2017 17:18:20
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
set(findobj(gcf, 'type', 'axes'), 'xtick', [], 'ytick', []);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in loadImageButton.
function loadImageButton_Callback(hObject, eventdata, handles)
% hObject handle to loadImageButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('*.jpg', 'Select an image');
if ~isequal(filename, 0)
image = imread(strcat(pathname, filename));
handles.image = rgb2gray(image);
guidata(hObject, handles);
axes(handles.imageAxes)
imshow(image);
end
% --- Executes on button press in medianButton.
function medianButton_Callback(hObject, eventdata, handles)
% hObject handle to medianButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = medfilt2(handles.image);
axes(handles.imageAxes);
imshow(filtered_image);
% --- Executes on button press in maximumButton.
function maximumButton_Callback(hObject, eventdata, handles)
% hObject handle to maximumButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = ordfilt2(handles.image, 9, ones(3, 3));
axes(handles.imageAxes);
imshow(filtered_image);
% --- Executes on button press in minimumButton.
function minimumButton_Callback(hObject, eventdata, handles)
% hObject handle to minimumButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = ordfilt2(handles.image, 1, ones(3, 3));
axes(handles.imageAxes);
imshow(filtered_image);
% --- Executes on button press in gaussianButton.
function gaussianButton_Callback(hObject, eventdata, handles)
% hObject handle to gaussianButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = imgaussfilt(handles.image);
axes(handles.imageAxes);
imshow(filtered_image);
% --- Executes on button press in noiseButton.
function noiseButton_Callback(hObject, eventdata, handles)
% hObject handle to noiseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
image = handles.image;
noise_image = imnoise(image, 'salt & pepper', 0.05);
handles.image = noise_image;
guidata(hObject, handles);
axes(handles.imageAxes);
imshow(noise_image);
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/16_prewitt_sobel_gui/gui.m
| 4,381 |
utf_8
|
8bfa0a4f98ac392c7af4aeb93a08cc4e
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 04-Oct-2017 11:07:59
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('*.jpg', 'Select an image');
if ~isequal(filename, 0)
image = imread(strcat(pathname, filename));
handles.image = rgb2gray(image);
guidata(hObject, handles);
axes(handles.imageAxes)
imshow(image);
end
% --- Executes on button press in prewittButton.
function prewittButton_Callback(hObject, eventdata, handles)
% hObject handle to prewittButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = filter_image(handles.image, 'prewitt', 1);
axes(handles.imageAxes)
imshow(filtered_image);
% --- Executes on button press in sobelButton.
function sobelButton_Callback(hObject, eventdata, handles)
% hObject handle to sobelButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = filter_image(handles.image, 'sobel', 1);
axes(handles.imageAxes)
imshow(filtered_image);
% --- Executes on button press in edgeButton.
function edgeButton_Callback(hObject, eventdata, handles)
% hObject handle to edgeButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
filtered_image = edge(handles.image);
axes(handles.imageAxes)
imshow(filtered_image);
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/extras/gui_color_segmentation/gui.m
| 6,785 |
utf_8
|
f09f8077984d0169e7cbde86110e315e
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 30-Oct-2017 09:55:07
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% Remove existent axis from axes
set(findobj(gcf, 'type', 'axes'), 'xtick', [], 'ytick', []);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in startButton.
function startButton_Callback(hObject, eventdata, handles)
% hObject handle to startButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vid = videoinput('winvideo', 1, 'YUY2_640x480');
vid.ReturnedColorspace = 'rgb';
handles.vid = vid;
handles.output = hObject;
guidata(hObject, handles);
axes(handles.videoAxes);
% hImage = image(zeros(640, 480, 3), 'Parent', handles.videoAxes);
hImage = image(zeros(320, 240, 3), 'Parent', handles.videoAxes);
setappdata(hImage,'UpdatePreviewWindowFcn',@rotate_video);
preview(handles.vid, hImage);
% --- Executes on button press in stopButton.
function stopButton_Callback(hObject, eventdata, handles)
% hObject handle to stopButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% closePreview(handles.cam);
% delete(handles.cam);
% guidata(hObject, handles);
stoppreview(handles.vid);
delete(handles.vid);
clear handles.vid;
% cla(handles.videoAxes, 'reset');
% --- Executes on button press in snapshotButton.
function snapshotButton_Callback(hObject, eventdata, handles)
% hObject handle to snapshotButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
frame = flip(getsnapshot(handles.vid), 2);
handles.frame = frame;
guidata(hObject, handles);
axes(handles.snapshotAxes);
image(frame);
% --- Executes on button press in saveSnapshotButton.
function saveSnapshotButton_Callback(hObject, eventdata, handles)
% hObject handle to saveSnapshotButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
imwrite(handles.frame, 'image.jpg');
figure, imshow(handles.frame);
function rotate_video(obj, event, himage)
rot_image = flip(event.Data, 2);
set(himage, 'cdata', rot_image);
% --- Executes on button press in markButton.
function markButton_Callback(hObject, eventdata, handles)
% hObject handle to markButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
image = handles.image;
gray_image = rgb2gray(image);
[rows, cols] = size(gray_image);
[rows, cols, ~] = size(image);
output = uint8(zeros(rows, cols, 3));
c = 0;
x = 0;
for i = 1:rows
for j = 1:cols
if image(i, j, 1) >= 130 && image(i, j, 2) >= 40 && image(i, j, 3) >= 10 && image(i, j, 1) <= 180 && image(i, j, 2) <= 100 && image(i, j, 3) <= 80
% c = c + image(i, j, 1) - 136;
% x = x + 1;
output(i, j, 1) = image(i, j, 1);
output(i, j, 2) = image(i, j, 2);
output(i, j, 3) = image(i, j, 3);
end
end
end
% c
% x
% figure, imshow(image);
threshold = imbinarize(rgb2gray(output), 50/255);
threshold = im_dilation(threshold);
% figure, imshow(threshold);
segmented = gray_image(:, :, [1, 1, 1]);
for i = 1:rows
for j = 1:cols
pixel = threshold(i, j);
if(pixel == 1)
segmented(i, j, 1) = 136;
segmented(i, j, 2) = 0;
segmented(i, j, 3) = 21;
end
end
end
% Show image in axes
axes(handles.snapshotAxes);
imshow(segmented);
% figure, imshow(segmented);
% --- Executes on button press in loadButton.
function loadButton_Callback(hObject, eventdata, handles)
% hObject handle to loadButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('*.jpg', 'Select an image');
if ~isequal(filename, 0)
image = imread(strcat(pathname, filename));
% Store image in a property on handles to share it across functions
handles.image = image;
guidata(hObject, handles);
% Show image in axes
axes(handles.videoAxes);
imshow(image);
end
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/extras/final_project_01/gui.m
| 6,901 |
utf_8
|
2b583a90aba00a96b55959d2385c3ef5
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 11-Nov-2017 23:31:11
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% Remove existent axis from axes
set(findobj(gcf, 'type', 'axes'), 'xtick', [], 'ytick', []);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in startButton.
function startButton_Callback(hObject, eventdata, handles)
% hObject handle to startButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
vid = videoinput('winvideo', 1, 'YUY2_640x480');
vid.ReturnedColorspace = 'rgb';
handles.vid = vid;
handles.output = hObject;
guidata(hObject, handles);
axes(handles.videoAxes);
hImage = image(zeros(640, 480, 3), 'Parent', handles.videoAxes);
setappdata(hImage,'UpdatePreviewWindowFcn',@rotate_video);
preview(handles.vid, hImage);
% --- Executes on button press in stopButton.
function stopButton_Callback(hObject, eventdata, handles)
% hObject handle to stopButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% closePreview(handles.cam);
% delete(handles.cam);
% guidata(hObject, handles);
stoppreview(handles.vid);
delete(handles.vid);
clear handles.vid;
% cla(handles.videoAxes, 'reset');
% --- Executes on button press in snapshotButton.
function snapshotButton_Callback(hObject, eventdata, handles)
% hObject handle to snapshotButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
frame = flip(getsnapshot(handles.vid), 2);
handles.frame = frame;
guidata(hObject, handles);
axes(handles.snapshotAxes);
image(frame);
% --- Executes on button press in faceDetectionButton.
function faceDetectionButton_Callback(hObject, eventdata, handles)
% hObject handle to faceDetectionButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
image = handles.frame;
faceDetector = vision.CascadeObjectDetector;
bbox = step(faceDetector, image);
if ~ isempty(bbox)
% image_faces = insertObjectAnnotation(image, 'rectangle', bbox, 'Face');
imface = imcrop(image, bbox);
axes(handles.snapshotAxes);
% imshow(image_faces);
imshow(imface);
handles.imface = imface;
guidata(hObject, handles);
end
% --- Executes on button press in detectEyeButton.
function detectEyeButton_Callback(hObject, eventdata, handles)
% hObject handle to detectEyeButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
image = handles.imface;
eyeDetector = vision.CascadeObjectDetector('LeftEyeCART');
bbox = step(eyeDetector, image);
[~, loc] = max(bbox(:, 1));
bbox = bbox(loc, :);
if ~ isempty(bbox)
eyeimage = rgb2gray(imcrop(image, bbox));
axes(handles.snapshotAxes);
imshow(eyeimage);
handles.imeye = eyeimage;
handles.leye = bbox;
guidata(hObject, handles);
end
function rotate_video(obj, event, himage)
rot_image = flip(event.Data, 2);
set(himage, 'cdata', rot_image);
% --- Executes on button press in detectGazeButton.
function detectGazeButton_Callback(hObject, eventdata, handles)
% hObject handle to detectGazeButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
bbox = handles.leye;
image = handles.imface;
if ~ isempty(bbox)
border = 2;
x1 = bbox(1);
y1 = bbox(2);
x2 = x1 + bbox(3);
y2 = y1 + bbox(4);
% horizontal lines
image(y1:y1+border, x1:x2, 1) = 255;
image(y2-border:y2, x1:x2, 1) = 255;
% vertical lines
image(y1:y2, x1:x1+border, 1) = 255;
image(y1:y2, x2-border:x2, 1) = 255;
eyeFrame = image(y1:y2, x1:x2, :);
[centers, ~] = imfindcircles(eyeFrame,[10 30], 'ObjectPolarity', 'dark', 'Sensitivity', 0.8, 'Method', 'twostage', 'EdgeThreshold', .05);
if ~ isempty(centers)
center = centers(1, :) + [x1, y1];
center = round(center);
image(center(2) - 1 : center(2) + 1, center(1) - 7 : center(1) + 7, 1) = 255;
image(center(2) - 7 : center(2) + 7, center(1) - 1 : center(1) + 1, 1) = 255;
end
axes(handles.snapshotAxes);
imshow(image);
end
|
github
|
warborn/matlab-ai02-master
|
cursor.m
|
.m
|
matlab-ai02-master/extras/final_project_01/cursor.m
| 7,266 |
utf_8
|
f430a0819efbdb99db2c78b8d5acf9fc
|
function varargout = cursor(varargin)
% CURSOR MATLAB code for cursor.fig
% CURSOR, by itself, creates a new CURSOR or raises the existing
% singleton*.
%
% H = CURSOR returns the handle to a new CURSOR or the handle to
% the existing singleton*.
%
% CURSOR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CURSOR.M with the given input arguments.
%
% CURSOR('Property','Value',...) creates a new CURSOR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before cursor_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to cursor_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help cursor
% Last Modified by GUIDE v2.5 24-Oct-2017 20:46:13
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @cursor_OpeningFcn, ...
'gui_OutputFcn', @cursor_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before cursor is made visible.
function cursor_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to cursor (see VARARGIN)
% Choose default command line output for cursor
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes cursor wait for user response (see UIRESUME)
% uiwait(handles.figure);
% Custom Code
% Clear console
clc
% Import Java Robot class for mouse cursor manipulation
import java.awt.Robot;
mouse = Robot;
handles.mouse = mouse;
% Get laptop's screen width and height
screenSize = get(0, 'screensize');
handles.screenWidth = screenSize(3);
handles.screenHeight = screenSize(4);
% Set cursor default speed to two pixels per movement
handles.speed = get(handles.speedSlider, 'Value');
set(handles.speedText, 'String', string(handles.speed));
handles.currentPoint = struct;
% Save new handles properties
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = cursor_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in upButton.
function upButton_Callback(hObject, eventdata, handles)
% hObject handle to upButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in downButton.
function downButton_Callback(hObject, eventdata, handles)
% hObject handle to downButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in rightButton.
function rightButton_Callback(hObject, eventdata, handles)
% hObject handle to rightButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in leftButton.
function leftButton_Callback(hObject, eventdata, handles)
% hObject handle to leftButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on key press with focus on figure or any of its controls.
function figure_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.FIGURE)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% Get current pointer location
pointerLocation = get(0, 'PointerLocation');
% Store the X coordinate
handles.currentPoint.x = pointerLocation(1);
% Store the Y coordinate
handles.currentPoint.y = handles.screenHeight - pointerLocation(2);
% Extract a string with the name of the pressed arrow key
direction = regexprep(eventdata.Key, 'arrow$', '');
if strcmp(direction, 'up') || strcmp(direction, 'down') || strcmp(direction, 'right') || strcmp(direction, 'left')
paintbutton(handles, direction, 'g');
mousemove(handles.mouse, handles.currentPoint, direction, handles.speed);
end
% --- Executes on key release with focus on figure or any of its controls.
function figure_WindowKeyReleaseFcn(hObject, eventdata, handles)
% hObject handle to figure (see GCBO)
% eventdata structure with the following fields (see MATLAB.UI.FIGURE)
% Key: name of the key that was released, in lower case
% Character: character interpretation of the key(s) that was released
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) released
% handles structure with handles and user data (see GUIDATA)
direction = regexprep(eventdata.Key, 'arrow$', '');
paintbutton(handles, direction, [0.94, 0.94, 0.94]);
% --- Executes on slider movement.
function speedSlider_Callback(hObject, eventdata, handles)
% hObject handle to speedSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% Change cursor default speed
handles.speed = get(handles.speedSlider, 'Value');
set(handles.speedText, 'String', string(handles.speed));
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function speedSlider_CreateFcn(hObject, eventdata, handles)
% hObject handle to speedSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
|
github
|
warborn/matlab-ai02-master
|
gui.m
|
.m
|
matlab-ai02-master/10_gui_thresholding/gui.m
| 6,249 |
utf_8
|
b8affc5df1d971111b01b820435d60a4
|
function varargout = gui(varargin)
% GUI MATLAB code for gui.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help gui
% Last Modified by GUIDE v2.5 15-Sep-2017 16:20:55
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gui_OpeningFcn, ...
'gui_OutputFcn', @gui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before gui is made visible.
function gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to gui (see VARARGIN)
% Choose default command line output for gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% set(findobj(gcf, 'type', 'axes'), 'Visible', 'off');
set(findobj(gcf, 'type', 'axes'), 'xtick', [], 'ytick', []);
% --- Outputs from this function are returned to the command line.
function varargout = gui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in loadImageButton.
function loadImageButton_Callback(hObject, eventdata, handles)
% hObject handle to loadImageButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Read image from user's computer
[filename, pathname] = uigetfile('*.jpg', 'Select an image');
if ~isequal(filename, 0)
image = imread(strcat(pathname, filename));
% Store image in a property on handles to share it across functions
handles.image = image;
guidata(hObject, handles);
% Show image in axes
axes(handles.imageAxes);
imshow(image);
end
% --- Executes on button press in thresholdImageButton.
function thresholdImageButton_Callback(hObject, eventdata, handles)
% hObject handle to thresholdImageButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Retrieve image from handles
try
image = rgb2gray(handles.image);
% Threshold image
otsu_level = graythresh(image);
thresholded_image = threshold_image(image, otsu_level);
% Show image in axes
axes(handles.thresholdImageAxes);
imshow(thresholded_image);
catch ME
if(strcmp(ME.identifier, 'MATLAB:nonExistentField'))
'File not selected'
end
end
% --- Executes on slider movement.
function thresholdSlider_Callback(hObject, eventdata, handles)
% hObject handle to thresholdSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
try
image = handles.image2;
threshold_value = round(get(handles.thresholdSlider, 'Value'));
thresholded_image = threshold_image(image, threshold_value);
axes(handles.gradualThresholdImageAxes);
imshow(thresholded_image);
catch ME
if(strcmp(ME.identifier, 'MATLAB:nonExistentField'))
'File not selected'
end
end
% --- Executes during object creation, after setting all properties.
function thresholdSlider_CreateFcn(hObject, eventdata, handles)
% hObject handle to thresholdSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on button press in loadImageButton2.
function loadImageButton2_Callback(hObject, eventdata, handles)
% hObject handle to loadImageButton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename pathname] = uigetfile('*.jpg', 'Select an image');
if ~isequal(filename, 0)
image = imread(strcat(pathname, filename));
gray_image = rgb2gray(image);
otsu_level = graythresh(gray_image);
thresholded_image = threshold_image(gray_image, otsu_level);
set(handles.thresholdSlider, 'Value', round(otsu_level * 255));
handles.image2 = gray_image;
guidata(hObject, handles);
axes(handles.imageAxes2);
imshow(image);
axes(handles.gradualThresholdImageAxes)
imshow(thresholded_image);
end
|
github
|
Tympan/Tympan_Audio_Design_Tool-master
|
getCommentLines.m
|
.m
|
Tympan_Audio_Design_Tool-master/scripts/functions/getCommentLines.m
| 2,436 |
utf_8
|
20c215d91928c5dac08e8ee86e5f67a3
|
function comment_lines = getCommentLines(all_lines,Iline)
%let's just grab the file header comment. That's simplest, though maybe wrong
comment_lines = grabFileHeaderComment(all_lines);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function comment_lines = grabFileHeaderComment(all_lines)
%default to grabbing all the first lines that are comments
Ikeep = [];
Iline = 0;
done = 0;
NOT_STARTED = 0;
STARTED_LINE_BY_LINE = 1;
STARTED_BLOCK = 2;
DONE = 3;
state = NOT_STARTED;
comment_lines = {};
while state ~= DONE
Iline=Iline+1;
if Iline > length(all_lines)
state = DONE;
else
foo = deblank(all_lines{Iline});
switch state
case NOT_STARTED
if length(foo) >= 2
if strcmpi(foo(1:2),'//')
state = STARTED_LINE_BY_LINE;
comment_lines{end+1} = foo(3:end);
elseif strcmpi(foo(1:2),'/*')
state = STARTED_BLOCK;
comment_lines{end+1} = foo(3:end);
end
end
case STARTED_LINE_BY_LINE
if length(foo) < 2
state = DONE;
elseif strcmpi(foo(1:2),'//')
comment_lines{end+1} = foo(3:end);
else
state = DONE;
end
case STARTED_BLOCK
if length(foo) == 0
comment_lines{end+1} = '';
elseif length(foo) == 1
if foo == '*'
comment_lines{end+1} = '';
else
comment_lines{end+1} = foo;
end
elseif strcmpi(foo(1:2),'*/')
state = DONE;
elseif strcmpi(foo(1:2),' *')
if length(foo) >= 3
if strcmpi(foo(2:3),'*/')
state = DONE;
else
comment_lines{end+1} = foo(3:end);
end
else
comment_lines{end+1} = foo(3:end);
end
elseif strcmpi(foo(1),'*')
comment_lines{end+1} = foo(2:end);
else
comment_lines{end+1} = foo;
end
end
end
end
return
|
github
|
Tympan/Tympan_Audio_Design_Tool-master
|
parseAudioObjectHTML.m
|
.m
|
Tympan_Audio_Design_Tool-master/scripts/functions/parseAudioObjectHTML.m
| 1,858 |
utf_8
|
7ae025bcdaddf66d6b97b31101b60060
|
function all_docs = parseAudioObjectHTML(fname,outpname);
if nargin < 2
outpname = 'NodeDocs\';
if nargin < 1
fname = 'Temp\node_docs.txt';
end
end
%% get the data
if iscell(fname)
% we're already given the text, so no need to load it
all_lines = fname;
else
% read file
fid=fopen(fname,'r');
all_lines=[];
tline=fgetl(fid);
while ischar(tline)
all_lines{end+1} = tline;
tline=fgetl(fid);
end
fclose(fid);
end
%% parse the file into subfiles
all_data=[];
targ_str = '<script type="text/x-red" data-help-name=';
row_inds = find(contains(all_lines,targ_str));
if isempty(row_inds)
disp(['*** ERROR ***: parseDocsFile: could not find any node docs. returning...']);
return;
end
%add an entry at the end to ensure that the last doc is included
row_inds(end+1) = length(all_lines)+1;
%loop over each doc and save
for Idoc = 1:length(row_inds)-1
%get indices for this doc and extract
inds = [row_inds(Idoc) row_inds(Idoc+1)-1];
node_doc = all_lines(inds(1):inds(2));
%extract the name of the doc
name_str = node_doc{1};
targ_str = 'data-help-name=';
I=strfind(name_str,targ_str);
name_str = name_str((I(1)+length(targ_str)):end);
I=find(name_str=='"');
name_str = name_str((I(1)+1):(I(2)-1));
%write doc
outfname = [outpname name_str '.html'];
writeText(outfname,node_doc);
%add to data structure
data=[];
data.name = name_str;
data.doc = node_doc;
if isempty(all_data)
all_data = data;
else
all_data(end+1) = data;
end
end
all_docs = all_data;
%% %%%%%%%%%%%%%%%%55
function []=writeText(outfname,textToWrite);
disp(['writing text to ' outfname]);
fid=fopen(outfname,'w');
for I=1:length(textToWrite)
fprintf(fid,'%s\n',textToWrite{I});
end
fclose(fid);
|
github
|
Tympan/Tympan_Audio_Design_Tool-master
|
createDefaultDoc.m
|
.m
|
Tympan_Audio_Design_Tool-master/scripts/functions/createDefaultDoc.m
| 3,864 |
utf_8
|
0172b39b5a95726f76418960ddbe6d81
|
function all_lines = createEmptyDoc(name,class_comment_lines)
name = deblank(name);
all_lines={};
if ~isempty(class_comment_lines)
all_lines = addHelpText(name,class_comment_lines,all_lines);
end
all_lines = addTemplateText(name,all_lines);
return
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function all_lines = addHelpText(name,my_text,all_lines)
if iscell(my_text)
my_text = strvcat(my_text);
end
all_lines{end+1} = ['<script type="text/x-red" data-help-name="' name '">'];
if (1)
%use html paragraph format for each line
for Iline=1:size(my_text,1)
all_lines{end+1} = ['<p>' deblank(my_text(Iline,:)) '</p>'];
end
else
%use html code dag
%all_lines{end+1} = '<code>';
for Iline=1:size(my_text,1)
all_lines{end+1} = ['<code>' deblank(my_text(Iline,:)) '</code>'];
end
%all_lines{end+1} = '</code>';
end
% <h3>Summary</h3>
% <div class=tooltipinfo>
% <p>Finite impulse response filter, useful for all sorts of filtering.
% </p>
% <p align=center><img src="img/fir_filter.png"></p>
% </div>
% <h3>Audio Connections</h3>
% <table class=doc align=center cellpadding=3>
% <tr class=top><th>Port</th><th>Purpose</th></tr>
% <tr class=odd><td align=center>In 0</td><td>Signal to be filtered</td></tr>
% <tr class=odd><td align=center>Out 0</td><td>Filtered Signal Output</td></tr>
% </table>
% <h3>Functions</h3>
% <p class=func><span class=keyword>begin</span>(filter_coeff, filter_length, block_size);</p>
% <p class=desc>Initialize the filter. The filter_coeff must be an array of 32-bit floats (the
% filter's impulse response), the filter_length indicates the number of points in the array,
% and block_size is the length of the audio block that will be passed to this filtering
% object during operation. The filter_coeff array may also be set as
% FIR_PASSTHRU (with filter_length = 0), to directly pass the input to output without
% filtering.
% </p>
% <p class=func><span class=keyword>end</span>();</p>
% <p class=desc>Turn the filter off.
% </p>
% <!--
% <h3>Examples</h3>
% <p class=exam>File > Examples > Audio > Effects > Filter_FIR
% </p>
% -->
% <h3>Known Issues</h3>
% <p>Your filter's impulse response array must have an even length. If you have
% add odd number of taps, you must add an extra zero to increase the length
% to an even number.
% </p>
% <p>The minimum number of taps is 4. If you use less, add extra zeros to increase
% the length to 4.
% </p>
% <p>The impulse response must be given in reverse order. Many filters have
% symetrical impluse response, making this a non-issue. If your filter has
% a non-symetrical response, make sure the data is in reverse time order.
% </p>
% <h3>Notes</h3>
% <p>FIR filters requires more CPU time than Biquad (IIR), but they can
% implement filters with better phase response.
% </p>
% <p>The free
% <a href="http://t-filter.engineerjs.com/" target="_blank"> TFilter Design Tool</a>
% can be used to create the impulse response array. Be sure to choose the desired sampling
% frequency (the tool defaults to only 2000 Hz whereas Tympan defaults to 44117) and
% the output type to "float" (32 bit).
% </p>
all_lines{end+1} = '</script>';
return
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function all_lines = addTemplateText(name,all_lines)
all_lines{end+1} = ['<script type="text/x-red" data-template-name="' name ' ">'];
all_lines{end+1} = [sprintf('\t') '<div class="form-row">'];
all_lines{end+1} = [sprintf('\t\t') '<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>'];
all_lines{end+1} = [sprintf('\t\t') '<input type="text" id="node-input-name" placeholder="Name">'];
all_lines{end+1} = [sprintf('\t') '</div>'];
all_lines{end+1} = '</script>';
return
|
github
|
Tympan/Tympan_Audio_Design_Tool-master
|
buildNewNodes.m
|
.m
|
Tympan_Audio_Design_Tool-master/scripts/functions/buildNewNodes.m
| 12,891 |
utf_8
|
1a7be649ce3469a7d5cdbc3f862882f6
|
function [headings,new_node_data]=buildNewNodes(source_pname)
%Look into directory of objects and build node info from the contents
if nargin < 1
%source_pname = 'C:\Users\wea\Documents\Arduino\libraries\OpenAudio_ArduinoLibrary\';
source_pname = 'C:\Users\wea\Documents\Arduino\libraries\Tympan_Library\';
end
%get all header files
fnames = dir([source_pname '*.h']);
%now look into each header file and find all class definitions
all_class_names={};
all_num_inputs=[];
all_class_lines={};
all_comment_lines={};
for Ifile=1:length(fnames)
[class_names,class_lines, comment_lines] = findClassNames(fnames(Ifile));
all_class_names(end+[1:length(class_names)]) = class_names;
%all_num_inputs(end+[1:length(class_names)]) = num_class_inputs;
all_class_lines(end+[1:length(class_lines)]) = class_lines;
all_comment_lines(end+[1:length(comment_lines)]) = comment_lines;
end
%guess a shortname for each one
all_short_names = guessShortName(all_class_names);
%read (or estimate) the number of inputs and outputs
[all_num_inputs, all_num_outputs]= getNumberOfInputsOutputs(all_class_names,all_class_lines);
%guess the number of outputs
%all_num_outputs = guessNumOutputs(all_class_names,all_num_inputs);
%guess the category
all_categories = guessCategory(all_class_names);
%choose icon based on categories
all_icons = chooseIcon(all_class_names,all_categories);
%display results
%headings = {'type';'shortName';'inputs';'outputs';'category';'color';'icon'};new_node_data={};
headings = {'type';'shortName';'inputs';'outputs';'category';'color';'icon';'comment_lines'};new_node_data={};
for Iclass=1:length(all_class_names)
new_node_data{Iclass,1} = all_class_names{Iclass};
new_node_data{Iclass,2} = all_short_names{Iclass};
new_node_data{Iclass,3} = all_num_inputs(Iclass);
new_node_data{Iclass,4} = all_num_outputs(Iclass);
new_node_data{Iclass,5} = all_categories{Iclass};
new_node_data{Iclass,6} = '#E6E0F8'; %default color
new_node_data{Iclass,7} = all_icons{Iclass}; %default icon
str=[];
for I=1:length(new_node_data(Iclass,:))
val = new_node_data{Iclass,I};
if isnumeric(val)
str = [str num2str(val)];
else
str = [str val];
end
if I<length(new_node_data(Iclass,:))
str = [str ','];
end
end
disp(str);
%add in the comment lines
new_node_data{Iclass,8} = strvcat(all_comment_lines{Iclass});
end
if nargout == 0
disp(' ');
disp(['Copy the text above into a spreadsheet (like myNodes.xlsx)']);
end
end
%% %%%%%%%%%%%%%%%%%%555
function [names, class_lines, comment_lines] = findClassNames(fname)
if isstruct(fname)
%assume it is output from Matlab's "dir"
fname = [fname.folder '\' fname.name];
end
%load the file
all_lines = readAllLines(fname);
%find all of the class names
targ_str = 'class ';
names = {};
row_ind_class = [];
comment_lines={};
for Iline = 1:length(all_lines)
line = all_lines{Iline};
if length(line) >= length(targ_str)
if strcmpi(line(1:length(targ_str)),targ_str)
%this is a "class" statment
%strip off the "class" part
I=strfind(line,targ_str);
line = line((I(1)+length(targ_str)):end);
%find the end of the name, white or ':'
I=find((line == ' ') | (line == ':'));
if isempty(I); I=length(line); end
name = line(1:I(1));
%strip off leading/trailing white space
while (name(1) == ' ') %strip off leading white space
name = name(2:end);
end
while (name(end) == ' ') %strip off trailing white space
name = name(1:end-1);
end
while (name(end) == ';') %strip off trailing semicolon
name = name(1:end-1);
end
while (name(end) == ':') %strip off trailing colon
name = name(1:end-1);
end
%skip if class itself is AudioStream_F32 or AudioConnection_F32
if (strcmpi(name,'AudioStream_F32') | strcmpi(name,'AudioConnection_F32'))
%ignore
else
%save the class name
names{end+1} = name;
row_ind_class(end+1) = Iline;
%get the comment info for this class
comment_lines{end+1} = getCommentLines(all_lines,Iline);
%disp(['************** NAME: ' name]);
%for I=1:length(comment_lines)
% strvcat(comment_lines{I})
%end
end
end
end
end
%find the constructor for each class to find the number of inputs
class_lines={};
num_class_inputs=zeros(length(row_ind_class),1);
for Iclass = 1:length(row_ind_class)
%extract the lines just for this class
line_inds = row_ind_class(Iclass);
if (Iclass < length(row_ind_class))
line_inds(2) = row_ind_class(Iclass+1);
else
line_inds(2) = length(all_lines);
end
class_lines{Iclass} = all_lines(line_inds(1):line_inds(2));
end
end %end function
%% %%%%%%%%%%%%%%%%%%% fu
function [all_num_inputs, all_num_outputs]= getNumberOfInputsOutputs(all_class_names,all_class_lines)
%first, look for comment that is a directive to the "GUI" about number of ins and outs
all_num_inputs = NaN*ones(length(all_class_names),1);
all_num_outputs = NaN*ones(length(all_class_names),1);
for Iclass = 1:length(all_class_names)
lines = all_class_lines{Iclass};
targ_str = '//GUI:';
GUI_lines = find(contains(lines,targ_str));
do_test = 1;
for Iline=1:length(GUI_lines)
if do_test
line = lines{GUI_lines(Iline)};
targ_str = 'inputs:';
I=strfind(line,targ_str);
if ~isempty(I)
line = line((I(1)+length(targ_str)):end);
I = strfind(line,',');
all_num_inputs(Iclass) = str2num(line(1:I(1)-1));
line = line(I(1)+1:end);
targ_str = 'outputs:';
I=strfind(line,targ_str);
if ~isempty(I)
line = line((I(1)+length(targ_str)):end);
I = find((line == ',') | (line == '/'));
line = line(1:I(1)-1);
all_num_outputs(Iclass) = str2num(line);
do_test = 0; %we've got our answer.
end
end
end
end
end
%now, do the old method if an answer is missing...look at constructor for inputs
for Iclass = 1:length(all_class_names)
if isnan(all_num_inputs(Iclass))
class_lines = all_class_lines{Iclass};
%find the constructor
targ_str = all_class_names{Iclass};
I=find(contains(class_lines,targ_str));
if length(I) < 2
%disp(['*** WARNING ***: buildNewNodes: could not find constructor for ' names{Iclass}]);
%disp([' : Number of audio inputs is unknown. Continuing...']);
else
constuctor_str = class_lines{I(2)}; %constructor should be first one after the name of the class
%find the number of inputs...after AudioStream or AudioStream_F32
targ_str = 'AudioStream_F32(';
I=strfind(constuctor_str,targ_str);
if isempty(I)
targ_str = 'AudioStream(';
I=strfind(constuctor_str,targ_str);
end
if isempty(I)
%disp(['*** WARNING ***: buildNewNodes: could not find inputs for ' names{Iclass}]);
%disp([' : Number of audio inputs is unknown. Continuing...']);
else
str = constuctor_str((I(1)+length(targ_str)):end);
I=find(str==',');
all_num_inputs(Iclass) = str2num(str(1:I(1)-1));
end
end
end
end
%look for missing outputs, set equal to inputs
for Iclass = 1:length(all_class_names)
if isnan(all_num_outputs(Iclass))
all_num_outputs(Iclass) = all_num_inputs(Iclass);
end
end
end %end function
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%55
function short_names = guessShortName(class_names)
short_names={};
for Iname=1:length(class_names)
name = class_names{Iname};
if strcmpi(name(1:5),'Audio')
name = name(6:end);
end
if strcmpi(name(end-3:end),'_F32')
name = name(1:end-4);
end
%strip off known pre-fixes
strs = {'Control' 'Convert' 'Effect' 'Filter' 'Synth'};
for Istr=1:length(strs)
str = strs{Istr};
if length(name) >= length(str)
if strcmpi(name(1:length(str)),str)
name = name((length(str)+1):end);
end
end
end
%handle special cases
targ_str='Waveform'; %remove "Waveform" from "WaveformSine"
if (length(name) > length(targ_str))
if strcmpi(name(1:length(targ_str)),targ_str)
name = name((length(targ_str)+1):end);
end
end
if strcmpi(name,'sgtl5000_extended')
name = 'sgtl5000ext';
end
if strcmpi(name,'inputI2S')
name = 'audioInI2S';
end
if strcmpi(name,'outputI2S')
name = 'audioOutI2S';
end
if strcmpi(name,'computeEnvelope')
name = 'envelope';
end
if strcmpi(name,'inputUSB');
name = 'audioInUSB';
end
if strcmpi(name,'outputUSB');
name = 'audioOutUSB';
end
if strcmpi(name,'freqWeighting');
name = 'freqWeight';
end
if strcmpi(name,'timeWeighting');
name = 'timeWeight';
end
if strcmpi(name,'FFT_Overlapped');
name = 'blockwiseFFT';
end
if strcmpi(name,'IFFT_Overlapped');
name = 'blockwiseIFFT';
end
%strip off leading space or underscore
while( (name(1) == ' ') | (name(1) == '_')); name=name(2:end); end
%strop off trailing space or underscore
while( (name(end) == ' ') | (name(end) == '_')); name=name(1:end-1); end
%adjust the case
if strcmpi(name(1:3),'I16') | strcmpi(name(1:3),'F32') | strcmpi(name(1:3),'FFT') | strcmpi(name(1:3),'IFF');
%don't change the case
else
%do change the case
name(1) = lower(name(1)); %remove any leading capital letter
if strcmpi(name(1:3),'SGT') | strcmpi(name(1:3),'TLV') | strcmpi(name(1:3),'FIR') | strcmpi(name(1:3),'IIR')
name=lower(name); %go all lower case;
end
end
%save the name
short_names{Iname} = name;
end
end %end function
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function num_outputs = guessNumOutputs(class_names,num_inputs)
num_outputs = num_inputs; %default rule
% apply corrections
for Iclass=1:length(class_names)
name = class_names{Iclass};
if contains(name,'Mixer')
num_outputs(Iclass) = 1;
end
end
end %end function
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5
function all_categories = guessCategory(class_names)
all_categories={};
for Iname=1:length(class_names)
name = class_names{Iname};
%strip off leading 'Audio'
if strcmpi(name(1:5),'Audio')
name = name(6:end);
end
%find the first capital letter *after* the leading capital
expr = '[A-Z]'; capStartIndex = regexp(name,expr);
if isempty(capStartIndex);
Icap=length(name)+1;
else
if capStartIndex(1) == 1;
Icap = capStartIndex(2);
else
Icap = capStartIndex(1);
end;
end
expr = '[0-9]'; numStartIndex = regexp(name,expr);
if isempty(numStartIndex)
Inum = length(name)+1;
else
Inum = numStartIndex(1);
end
I = find(name == '_');
if isempty(I)
Iund = length(name)+1;
else
Iund = I(1);
end
%get the category
name = name(1:(min([Icap Inum Iund])-1));
name = lower(name); %convert to lower case
%translate the category name to an existing one
switch lower(name)
case 'synth'
name = 'synth';
case 'multiply'
name = 'effect';
case 'divide'
name = 'effect';
end
%append "function"
name = [name '-function'];
%save the name
all_categories{Iname} = name;
end
end %end function
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function all_icons = chooseIcon(all_class_names,all_categories)
all_icons = {};
for Iclass = 1:length(all_class_names)
category = all_categories(Iclass);
icon = 'arrow-in.png'; %default
if strcmpi(lower(category),'control-function')
icon = 'debug.png';
end
all_icons{end+1} = icon;
end
end %end function
|
github
|
Tympan/Tympan_Audio_Design_Tool-master
|
parseNodeFile.m
|
.m
|
Tympan_Audio_Design_Tool-master/scripts/functions/parseNodeFile.m
| 3,249 |
utf_8
|
5dc42133c06e830772ea9f78b60bc88b
|
function all_data = parseNodeFile(fname)
if nargin < 1
fname = 'Temp\nodes.txt';
end
%% read file
fid=fopen(fname,'r');
all_lines=[];
tline=fgetl(fid);
while ischar(tline)
all_lines{end+1} = tline;
tline=fgetl(fid);
end
fclose(fid);
%% parse the file
all_data=[];
for Iline=1:length(all_lines)
data=[];
line = all_lines{Iline};
%find start
I=find(line == '{');
if ~isempty(I);
line=line(I(1)+1:end);
%find end of field
I=find(line == ',');
field_count = 0;
while ~isempty(I)
%get entry and remove from line
entry = line(1:I(1)-1);
line = line(I(1)+1:end);
%parse entry
I=find(entry == ':');
if ~isempty(I)
field_count = field_count+1;
fieldname = entry(1:I(1)-1);
fieldname = fieldname(2:end-1); %remove quotes
value = entry(I(1)+1:end);
if (field_count == 2) & (fieldname == 'data')
expected_value = '{"defaults":{"name":{"value":"new"}}';
if (value(2+[1:length('defaults')])=='defaults')
%this is good. "line" is OK.
else
%push value back onto line
line = [value(2:end) ',' line];
end
value = expected_value;
else
value = stripOffStartEndQuotes(value);
end
%make correction if this was the last entry
if isempty(line)
%strip off the curly braces
while (value(end) == '}'); value = value(1:end-1); end;
value = stripOffStartEndQuotes(value);
end
%save this value
data.(fieldname) = value;
end
I=find(line == ',');
if ~isempty(I)
J=find(line == '"');
if isempty(J)
%I is the comma at the end of the line, not a seperator of entries.
%reject it
I=[];
end
end
end
%get the last entry
I=find(line == '}');
if ~isempty(I);
entry = line(1:I(1)-1);
I=find(entry == ':');
fieldname = entry(1:I(1)-1);
fieldname = fieldname(2:end-1); %remove quotes
value = entry(I(1)+1:end);
I = find(value == '"');
if (length(I) >= 2)
value = value(2:end-1); %remove quotes;
end
data.(fieldname) = value;
end
%save the data
if isempty(all_data)
all_data = data;
else
all_data(end+1) = data;
end
end
end
return
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%5555
function value = stripOffStartEndQuotes(value)
I = find(value == '"');
if length(I) >= 2
if (I(1) == 1) & (I(end)==length(value))
value = value(2:end-1); %remove quotes;
end
end
|
github
|
SFlannigan/Tensor_Network_Methods-master
|
ncon.m
|
.m
|
Tensor_Network_Methods-master/Kernel/ncon.m
| 28,306 |
utf_8
|
3a36e8cec73f13af312918d0f8daeae2
|
function tensor = ncon(tensorList,legLinks,sequence,finalOrder)
% ncon v1.01 (c) R. N. C. Pfeifer, 2014.
% ==========
% Network CONtractor: NCON
% function A = ncon(tensorList,legLinks,sequence,finalOrder)
% Contracts a single tensor network.
%
% Supports disjoint networks, trivial (dimension 1) indices, 1D objects, traces, and outer products (both through the zero-in-sequence notation and
% through labelling an implicit trailing index of dimension 1).
% v1.01
% =====
% Added ability to disable input checking for faster performance
if ~exist('finalOrder','var')
% finalOrder not specified - use default: Negative indices in descending order, consecutive and starting from -1
finalOrder = [];
end
% Check inputs, generate default contraction sequence if required
if ~exist('sequence','var')
[sequence legLinks] = checkInputs(tensorList,legLinks,finalOrder);
else
[sequence legLinks] = checkInputs(tensorList,legLinks,finalOrder,sequence);
end
if ~isempty(finalOrder)
% Apply final ordering request
legLinks = applyFinalOrder(legLinks,finalOrder);
end
[tensor legs] = performContraction(tensorList,legLinks,sequence);
tensor = tensor{1};
legs = legs{1};
% Arrange legs of final output
if numel(legs)>1 && ~isequal(legs,-1:-1:numel(legs))
perm(-legs) = 1:numel(legs);
tensor = permute(tensor,perm);
end
end
function legLinks = applyFinalOrder(legLinks,finalOrder)
% Applies final leg ordering
for a=1:numel(legLinks)
for b=find(legLinks{a}<0)
legLinks{a}(b) = -find(finalOrder==legLinks{a}(b),1);
end
end
end
function [tensorList legLinks] = performContraction(tensorList,legLinks,sequence)
% Performs tensor contraction
warnedLegs = []; % Legs for which a warning has been generated
while numel(tensorList)>1 || any(legLinks{1}>0)
% Ensure contraction sequence is not empty - converts implicit outer products into zeros-in-sequence outer products
if isempty(sequence)
sequence = zeros(1,numel(tensorList)-1);
end
% Check first entry in contraction sequence
if sequence(1)==0
% It's a zero: Perform an outer product according to the rules of zeros-in-sequence notation and update contraction sequence
[tensorList legLinks sequence warnedLegs] = zisOuterProduct(tensorList,legLinks,sequence,warnedLegs);
else
% It's a number: Identify and perform tensor contraction
% Find the tensors on which this index appears
tensors = zeros(1,2);
for a=1:numel(legLinks)
if any(legLinks{a}==sequence(1))
tensors(1+(tensors(1)~=0)) = a;
end
end
if tensors(2)==0
% Index appears on one tensor only: It's a trace
% Find all traced indices on this tensor
tracedIndices = sort(legLinks{tensors(1)});
tracedIndices = tracedIndices([tracedIndices(1:end-1)==tracedIndices(2:end) false]);
% Check which traced indices actually appear at the beginning of the sequence. Update contraction list.
[doingTraces sequence] = findInSequence(tracedIndices,sequence,tensorList,legLinks,tensors);
if ~isequal(sort(doingTraces),sort(tracedIndices))
warnedLegs = warn_suboptimal(doingTraces,tracedIndices,0,warnedLegs,legLinks{tensors(1)},[size(tensorList{tensors(1)}) ones(1,numel(legLinks{tensors(1)})-ndims(tensorList{tensors(1)}))]);
end
% Perform traces
tensorList{tensors(1)} = doTrace(tensorList{tensors(1)},legLinks{tensors(1)},doingTraces);
% Update leg list
for a=1:numel(doingTraces)
legLinks{tensors(1)}(legLinks{tensors(1)}==doingTraces(a)) = [];
end
else
% Index appears on two tensors: It's a contraction
% Find all indices common to the tensors being contracted
commonIndices = legLinks{tensors(1)};
for a=numel(commonIndices):-1:1
if ~any(legLinks{tensors(2)}==commonIndices(a))
commonIndices(a) = [];
end
end
% Check which contracted indices actually appear at the beginning of the sequence. Update contraction list.
[contractionIndices sequence] = findInSequence(commonIndices,sequence,tensorList,legLinks,tensors);
if ~isequal(sort(contractionIndices),sort(commonIndices))
tdims = [size(tensorList{tensors(1)}) ones(1,numel(legLinks{tensors(1)})-ndims(tensorList{tensors(1)}))];
tdims = tdims(1:numel(legLinks{tensors(1)}));
tdims = [tdims size(tensorList{tensors(2)}) ones(1,numel(legLinks{tensors(2)})-ndims(tensorList{tensors(2)}))]; %#ok<AGROW>
warnedLegs = warn_suboptimal(contractionIndices,commonIndices,1,warnedLegs,[legLinks{tensors(1)} legLinks{tensors(2)}],tdims);
end
% Are there any (non-trivial) traced indices on either of these tensors? If so, warn sequence is suboptimal
traces1 = sort(legLinks{tensors(1)});
traces1 = traces1([traces1(1:end-1)==traces1(2:end) false]);
traces2 = sort(legLinks{tensors(2)});
traces2 = traces2([traces2(1:end-1)==traces2(2:end) false]);
if ~isempty([traces1 traces2])
tdims = [size(tensorList{tensors(1)}) ones(1,numel(legLinks{tensors(1)})-ndims(tensorList{tensors(1)}))];
tdims = tdims(1:numel(legLinks{tensors(1)}));
tdims = [tdims size(tensorList{tensors(2)}) ones(1,numel(legLinks{tensors(2)})-ndims(tensorList{tensors(2)}))]; %#ok<AGROW>
warnedLegs = warn_suboptimal(contractionIndices,[traces1 traces2],2,warnedLegs,[legLinks{tensors(1)} legLinks{tensors(2)}],tdims);
end
% Contract over these indices and update leg list
[tensorList{tensors(1)} legLinks{tensors(1)}] = tcontract(tensorList{tensors(1)},tensorList{tensors(2)},legLinks{tensors(1)},legLinks{tensors(2)},contractionIndices);
tensorList(tensors(2)) = [];
legLinks(tensors(2)) = [];
end
end
end
end
function [rtnIndices sequence] = findInSequence(indices,sequence,tensorList,legLinks,tensors)
% Check how many of the supplied indices appear at the beginning of "sequence" - these are the indices to return
ptr = 1;
while ptr<=numel(sequence) && any(indices==sequence(ptr))
ptr = ptr + 1;
end
rtnIndices = sequence(1:ptr-1);
% If not contracting all possible non-trivial indices at once, warn that sequence is suboptimal
% - remove uncontracted trivial indices from comparison list as postponing these is unimportant
for a=numel(indices):-1:1
if ~any(rtnIndices==indices(a)) && size(tensorList{tensors(1)},find(legLinks{tensors(1)}==indices(a),1))==1
indices(a) = []; % Not doing this trace yet, but is trivial so postponing it is not a concern
end
end
% Update contraction sequence
sequence = sequence(ptr:end);
end
function B = doTrace(A,legLabels,tracedIndices)
% Trace over all indices listed in tracedIndices, each of which occurs twice on tensor A
sz = size(A);
sz = [sz ones(1,numel(legLabels)-numel(sz))];
tpos = [];
% Find positions of tracing indices
for a=1:numel(tracedIndices)
tpos = [tpos find(legLabels==tracedIndices(a))]; %#ok<AGROW>
end
% Reorder list of tracing index positions so that they occur in two equivalent blocks
sztrace = prod(sz(tpos(1:2:end)));
tpos = [tpos(1:2:end) tpos(2:2:end)];
% Identify non-tracing index positions
ind = 1:numel(legLabels);
ind(tpos) = [];
% Collect non-tracing and tracing indices
A = reshape(permute(A,[ind tpos]),prod(sz(ind)),sztrace,sztrace); % Separate indices to be traced and not to be traced
B = 0;
% Perform trace
for a=1:sztrace
B = B + A(:,a,a); % Perform trace
end
B = reshape(B,[sz(ind) 1 1]);
end
function [tensor legs] = tcontract(T1,T2,legs1,legs2,contractLegs)
% Contract T1 with T2 over indices listed in contractLegs
% If either tensor is a number (no legs), add a trivial leg to contract over.
if numel(legs1)==0
legs1 = max(abs(legs2))+1;
legs2 = [legs2 legs1];
contractLegs = legs1;
else
if numel(legs2)==0
legs2 = max(abs(legs1))+1;
legs1 = [legs1 legs2];
contractLegs = legs2;
end
end
% Find uncontracted legs
freeLegs1 = legs1;
freeLegs2 = legs2;
posFreeLegs1 = 1:numel(legs1);
posFreeLegs2 = 1:numel(legs2);
for a=1:numel(contractLegs)
posFreeLegs1(freeLegs1==contractLegs(a)) = [];
freeLegs1(freeLegs1==contractLegs(a)) = [];
posFreeLegs2(freeLegs2==contractLegs(a)) = [];
freeLegs2(freeLegs2==contractLegs(a)) = [];
end
% Find contracted legs; match ordering of contracted legs on tensors T1 and T2
posContLegs1 = 1:numel(legs1);
posContLegs1(posFreeLegs1) = [];
posContLegs2 = zeros(1,numel(posContLegs1));
for a=1:numel(posContLegs1)
posContLegs2(a) = find(legs2==legs1(posContLegs1(a)),1);
end
sz1 = [size(T1) ones(1,numel(legs1)-ndims(T1))];
sz2 = [size(T2) ones(1,numel(legs2)-ndims(T2))];
if numel(legs1)>1
T1 = permute(T1,[posFreeLegs1 posContLegs1]);
end
if numel(legs2)>1
T2 = permute(T2,[posContLegs2 posFreeLegs2]);
end
linkSize = prod(sz1(posContLegs1)); % NB prod([]) = 1 if no contracted legs
T1 = reshape(T1,prod(sz1(posFreeLegs1)),linkSize);
T2 = reshape(T2,linkSize,prod(sz2(posFreeLegs2)));
tensor = T1 * T2;
tensor = reshape(tensor,[sz1(posFreeLegs1) sz2(posFreeLegs2) 1 1]);
% Return uncontracted index list. Uncontracted legs are in order [unrearranged uncontracted legs off tensor 1, unrearranged uncontracted legs off tensor 2].
legs = [legs1(posFreeLegs1) legs2(posFreeLegs2)];
end
function warnedLegs = warn_suboptimal(doing,couldDo,mode,warnedLegs,legList,legDims)
% Generate warning for detected suboptimal contraction sequence
% Mode 0: Doing traces on a tensor, did not do all at once
% Mode 1: Contracting two tensors, missed some connecting legs
% Mode 2: Contracting two tensors, one carries a traced index which has not yet been evaluated
% Let couldDo be the list of indices which should be contracted but which weren't
for a=1:numel(doing)
couldDo(couldDo==doing(a)) = [];
end
% Check if warning has already been generated for these legs
for a=1:numel(warnedLegs)
couldDo(couldDo==warnedLegs(a)) = [];
end
% Check if legs are trivial (do not warn for trivial legs as the contraction of these is unimportant)
for a=numel(couldDo):-1:1
if legDims(find(legList==couldDo(a),1))==1
warnedLegs = [warnedLegs couldDo(a)]; %#ok<AGROW>
couldDo(a) = [];
end
end
if ~isempty(couldDo)
if mode == 2
t = 'Sequence suboptimal: Before contracting over ind';
if numel(doing)==1
t = [t 'ex ' num2str(doing) ' please trace over ind'];
else
t = [t 'ices ' num2str(doing) ' please trace over ind'];
end
if numel(couldDo)==1
t = [t 'ex ' num2str(couldDo) '.'];
else
t = [t 'ices ' num2str(couldDo) '.'];
end
else
if ~isempty(doing)
t = 'Sequence suboptimal: When contracting ind';
if numel(doing)==1
t = [t 'ex ' num2str(doing) ' please also contract ind'];
else
t = [t 'ices ' num2str(doing) ' please also contract ind'];
end
if numel(couldDo)==1
t = [t 'ex ' num2str(couldDo) ' as these indices appear on the same '];
else
t = [t 'ices ' num2str(couldDo) ' as these indices connect the same '];
end
if mode == 0
t = [t 'tensor.'];
else
t = [t 'two tensors.'];
end
else
t = 'Sequence suboptimal: Instead of performing an outer product and tracing later, please contract ind';
if numel(couldDo)==1
t = [t 'ex ' num2str(couldDo) '. This index connects the same two tensors and is non-trivial.'];
else
t = [t 'ices ' num2str(couldDo) '. These indices connect the same two tensors and are non-trivial.'];
end
end
end
warning('ncon:suboptimalsequence',t);
warnedLegs = [warnedLegs couldDo];
end
end
function [sequence legLinks] = checkInputs(tensorList,legLinks,finalOrder,sequence)
% Checks format of input data and returns separate lists of positive and negative indices
global ncon_skipCheckInputs;
if isequal(ncon_skipCheckInputs,true)
for a=1:numel(legLinks)
if isempty(legLinks{a})
legLinks{a} = zeros(1,0);
end
end
if ~exist('sequence','var')
sequence = cell2mat(legLinks);
sequence = sort(sequence(sequence>0));
sequence = sequence(1:2:end);
end
else
% Check data sizes
if size(tensorList,1)~=1 || size(tensorList,2)~=numel(tensorList)
error('Array of tensors has incorrect dimension - should be 1xn')
end
if ~isequal(size(legLinks),size(tensorList))
error('Array of links should be the same size as the array of tensors')
end
for a=1:numel(legLinks)
if size(legLinks{a},1)~=1 || size(legLinks{a},2)~=numel(legLinks{a})
if isempty(legLinks{a})
legLinks{a} = zeros(1,0);
else
error(['Leg link entry ' num2str(a) ' has wrong dimension - should be 1xn']);
end
end
tsize = size(tensorList{a});
if numel(tsize)==2 && tsize(2)==1
tsize = tsize(tsize~=1);
end
if numel(legLinks{a}) < numel(tsize)
if numel(legLinks{a})==1
error(['Leg link entry ' num2str(a) ' is too short: Tensor size is [' num2str(size(tensorList{a})) '] and legLinks{' num2str(a) '} has only ' num2str(numel(legLinks{a})) ' entry.']);
else
error(['Leg link entry ' num2str(a) ' is too short: Tensor size is [' num2str(size(tensorList{a})) '] and legLinks{' num2str(a) '} has only ' num2str(numel(legLinks{a})) ' entries.']);
end
end
end
% Check all tensors are numeric
for a=1:numel(tensorList)
if ~isnumeric(tensorList{a})
error('Tensor list must be a 1xn cell array of numerical objects')
end
end
% If finalOrder is provided, check it is a list of unique negative integers
if ~isempty(finalOrder)
if ~isnumeric(finalOrder)
error('finalOrder must be a list of unique negative integers')
elseif any(imag(finalOrder)~=0) || any(real(finalOrder)>0)
error('finalOrder must be a list of unique negative integers')
end
t1 = sort(finalOrder,'descend');
if any(t1(1:end-1)==t1(2:end))
error('finalOrder must be a list of unique negative integers')
end
end
% Get list of positive indices
allindices = cell2mat(legLinks);
if any(allindices==0)
error('Zero entry in legLinks')
elseif any(imag(allindices)~=0)
error('Complex entry in legLinks')
elseif any(int32(allindices)~=allindices)
error('Non-integer entry in legLinks');
end
[posindices ix] = sort(allindices(allindices>0),'ascend');
% Test all positive indices occur exactly twice
if mod(numel(posindices),2)~=0
maxposindex = posindices(end);
posindices = posindices(1:end-1);
end
flags = (posindices(1:2:numel(posindices))-posindices(2:2:numel(posindices)))~=0;
if any(flags)
errorpos = 2*find(flags~=0,1,'first')-1;
if errorpos>1 && posindices(errorpos-1)==posindices(errorpos)
error(['Error in index list: Index ' num2str(posindices(errorpos)) ' appears more than twice']);
else
error(['Error in index list: Index ' num2str(posindices(errorpos)) ' only appears once']);
end
end
if exist('maxposindex','var')
if isempty(posindices)
error(['Error in index list: Index ' num2str(maxposindex) ' only appears once']);
end
if posindices(end)==maxposindex
error(['Error in index list: Index ' num2str(maxposindex) ' appears more than twice']);
else
error(['Error in index list: Index ' num2str(maxposindex) ' only appears once']);
end
end
altposindices = posindices(1:2:numel(posindices));
flags = altposindices(1:end-1)==altposindices(2:end);
if any(flags)
errorpos = find(flags,1,'first');
error(['Error in index list: Index ' num2str(altposindices(errorpos)) ' appears more than twice']);
end
% Check positive index sizes match
sizes = ones(size(allindices));
ptr = 1;
for a=1:numel(tensorList)
sz = size(tensorList{a});
if numel(legLinks{a})==1 % Is a vector (1D)
sz = max(sz);
end
sizes(ptr:ptr+numel(sz)-1) = sz;
ptr = ptr + numel(legLinks{a});
end
sizes = sizes(allindices>0); % Remove negative legs
sizes = sizes(ix); % Sort in ascending positive leg sequence
flags = sizes(1:2:end)~=sizes(2:2:end);
if any(flags)
errorpos = find(flags,1,'first');
error(['Leg size mismatch on index ' num2str(altposindices(errorpos))]);
end
% Check negative indices are unique and consecutive, or unique and correspond to entries in finalOrder
negindices = sort(allindices(allindices<0),'descend');
if any(negindices(1:end-1)==negindices(2:end))
error('Negative indices must be unique');
end
if isempty(finalOrder)
if ~isequal(negindices,-1:-1:-numel(negindices))
error('If finalOrder is not specified, negative indices must be consecutive starting from -1');
end
else
if ~isequal(negindices,sort(finalOrder,'descend'))
error('Negative indices must match entries in finalOrder')
end
end
if exist('sequence','var')
% Check sequence is a row vector of positive real integers, each occurring only once, and zeros.
% Check they match the positive leg labels.
if any(uint32(sequence)~=sequence)
error('All entries in contraction sequence must be real positive integers or zero');
end
if numel(altposindices)~=sum(sequence>0)
error('Each positive index must appear once and only once in the contraction sequence, and each index in the sequence must appear on the tensors.');
end
if ~isempty(altposindices)
if any(altposindices~=sort(sequence(sequence>0)))
error('Each positive index must appear once and only once in the contraction sequence');
end
end
else
sequence = altposindices;
end
end
if numel(sequence)==0
sequence = zeros(1,0);
end
end
function [tensorList legLinks sequence warnedLegs] = zisOuterProduct(tensorList,legLinks,sequence,warnedLegs)
% This function provides support for the zeros-in-sequence notation described in arXiv:1304.6112
% Perform one or more outer products described by zeros in the contraction sequence
if all(sequence==0) % Final outer product of all remaining objects - ensure enough zeros are present in the sequence
if numel(sequence) < numel(legLinks)-1
sequence = zeros(1,numel(legLinks)-1);
warning('ncon:zisShortSequence','Zeros-in-sequence notation used, and insufficient zeros provided to describe final tensor contraction. Finishing contraction anyway.');
end
end
% Determine number of outer products pending
numOPs = 1;
while sequence(numOPs)==0 && numOPs < numel(sequence)
numOPs = numOPs + 1;
end
if sequence(numOPs)~=0
numOPs = numOPs - 1;
end
% Determine list of tensors on which OP is to be performed
if numOPs == numel(legLinks)-1
% OP of all remaining tensors
OPlist = 1:numel(legLinks);
else
% For OP of n tensors (n=numOPs+1) when more than n tensors remain, proceed past the zeros in the sequence and read nonzero indices until
% n+1 tensors accounted for. Failure to find n+1 tensors implies an invalid sequence.
flags = false(1,numel(legLinks));
ptr = numOPs+1;
while sum(flags) < numOPs+2
% Flag tensors on which leg given by sequence(ptr) appears
if ptr > numel(sequence)
t = 'Contraction sequence includes zeros and is inconsistent with rules of zeros-in-sequence notation. After a ';
if numOPs==1
t = [t 'zero']; %#ok<AGROW>
else
t = [t 'string of ' num2str(numOPs) ' zeros']; %#ok<AGROW>
end
error([t ', while reading further indices to identify the ' num2str(numOPs+1) ' tensors involved in the outer product, ncon encountered end of index list before identifying all tensors.']);
end
if sequence(ptr)==0
t = 'Contraction sequence includes zeros and is inconsistent with rules of zeros-in-sequence notation. After a ';
if numOPs==1
t = [t 'zero']; %#ok<AGROW>
else
t = [t 'string of ' num2str(numOPs) ' zeros']; %#ok<AGROW>
end
error([t ', while reading further indices to identify the ' num2str(numOPs+1) ' tensors involved in the outer product, ncon encountered another zero before identifying all tensors.']);
end
count = 0;
for a=1:numel(legLinks)
if any(legLinks{a}==sequence(ptr))
flags(a) = true;
count = count + 1;
end
end
if count~=2
t = 'Contraction sequence includes zeros and is inconsistent with rules of zeros-in-sequence notation. After a ';
if numOPs==1
t = [t 'zero']; %#ok<AGROW>
else
t = [t 'string of ' num2str(numOPs) ' zeros']; %#ok<AGROW>
end
error([t ', while reading further indices to identify the ' num2str(numOPs+1) ' tensors involved in the outer product, ncon encountered an index ' num2str(sequence(ptr)) ' which appears on ' num2str(count) ' tensor(s). Index should appear on exactly 2 tensors at this time.']);
end
ptr = ptr + 1;
end
% Identify which of these tensors is _not_ participating in the OP (but is instead contracted with the result of the OP), and unflag it.
% - Identify the two tensors on which the first nonzero index appears
% - Examine consecutive nonzero indices until one matches only one of the two tensors. This is the tensor to unflag.
firsttensors = [0 0];
ptr = numOPs+1;
for a=1:numel(legLinks)
if any(legLinks{a}==sequence(ptr))
if firsttensors(1)==0
firsttensors(1) = a;
else
firsttensors(2) = a;
break;
end
end
end
done = false;
while ~done
nexttensors = [0 0];
ptr = ptr + 1;
for a=1:numel(legLinks)
if any(legLinks{a}==sequence(ptr))
if nexttensors(1)==0
nexttensors(1) = a;
else
nexttensors(2) = a;
break;
end
end
end
if ~isequal(firsttensors,nexttensors)
done = true;
end
end
if any(firsttensors == nexttensors(1))
postOPtensor = nexttensors(1);
else
postOPtensor = nexttensors(2);
end
flags(postOPtensor) = false;
OPlist = find(flags);
% - Check contraction with postOPtensor is over all non-trivial indices of OP tensors
OPindices = cell2mat(legLinks(OPlist));
for a=1:numel(OPindices)
if ~any(legLinks{postOPtensor}==OPindices(a))
isnontriv = true;
for b=1:numel(OPlist)
if any(legLinks{b}==OPindices(a))
isnontriv = size(tensorList{b},legLinks{b}(find(legLinks{b}==OPindices(a),1)))~=1;
break;
end
end
if isnontriv
error(['Contraction sequence includes zeros and is inconsistent with rules of zeros-in-sequence notation. After using zeros to contract a group of tensors, all non-trivial indices on those tensors must be contracted with the next object. Contraction did not include index ' num2str(OPindices(a)) '.']);
end
end
end
end
% Find sizes of all tensors involved in OP.
OPsizes = zeros(1,numel(OPlist));
for a=1:numel(OPlist)
OPsizes(a) = numel(tensorList{OPlist(a)});
end
% Perform OPs
while numel(OPsizes)>1
% Find smallest two tensors
[~, ix] = sort(OPsizes,'ascend');
% If they have common nontrivial indices, warn about suboptimal sequence
commonIndices = legLinks{OPlist(ix(1))};
for a=numel(commonIndices):-1:1
if ~any(legLinks{OPlist(ix(2))}==commonIndices(a))
commonIndices(a) = [];
else
if size(tensorList{OPlist(ix(1))},find(legLinks{OPlist(ix(1))}==commonIndices(a),1))==1
commonIndices(a) = [];
end
end
end
if ~isempty(commonIndices)
% Suboptimal contraction sequence - generate warning
tdims = [size(tensorList{OPlist(ix(1))}) ones(1,numel(legLinks{OPlist(ix(1))})-ndims(tensorList{OPlist(ix(1))}))];
tdims = tdims(1:numel(legLinks{OPlist(ix(1))}));
tdims = [tdims size(tensorList{OPlist(ix(2))}) ones(1,numel(legLinks{OPlist(ix(2))})-ndims(tensorList{OPlist(ix(2))}))]; %#ok<AGROW>
warnedLegs = warn_suboptimal([],commonIndices,1,warnedLegs,[legLinks{OPlist(ix(1))} legLinks{OPlist(ix(2))}],tdims);
end
% Contract them
[tensorList{OPlist(ix(1))} legLinks{OPlist(ix(1))}] = tcontract(tensorList{OPlist(ix(1))},tensorList{OPlist(ix(2))},legLinks{OPlist(ix(1))},legLinks{OPlist(ix(2))},[]);
tensorList(OPlist(ix(2))) = [];
legLinks(OPlist(ix(2))) = [];
OPsizes(ix(1)) = OPsizes(ix(1)) * OPsizes(ix(2));
OPsizes(ix(2)) = [];
OPlist(OPlist>OPlist(ix(2))) = OPlist(OPlist>OPlist(ix(2))) - 1;
OPlist(ix(2)) = [];
end
% Update sequence
sequence = sequence(numOPs+1:end);
end
|
github
|
SFlannigan/Tensor_Network_Methods-master
|
expv.m
|
.m
|
Tensor_Network_Methods-master/Kernel/expv.m
| 4,863 |
utf_8
|
c8732ae90e0aa822b4d89d0835ebf115
|
% [w, err, hump] = expv( t, A, v, tol, m )
% EXPV computes an approximation of w = exp(t*A)*v for a
% general matrix A using Krylov subspace projection techniques.
% It does not compute the matrix exponential in isolation but instead,
% it computes directly the action of the exponential operator on the
% operand vector. This way of doing so allows for addressing large
% sparse problems. The matrix under consideration interacts only
% via matrix-vector products (matrix-free method).
%
% w = expv( t, A, v )
% computes w = exp(t*A)*v using a default tol = 1.0e-7 and m = 30.
%
% [w, err] = expv( t, A, v )
% renders an estimate of the error on the approximation.
%
% [w, err] = expv( t, A, v, tol )
% overrides default tolerance.
%
% [w, err, hump] = expv( t, A, v, tol, m )
% overrides default tolerance and dimension of the Krylov subspace,
% and renders an approximation of the `hump'.
%
% The hump is defined as:
% hump = max||exp(sA)||, s in [0,t] (or s in [t,0] if t < 0).
% It is used as a measure of the conditioning of the matrix exponential
% problem. The matrix exponential is well-conditioned if hump = 1,
% whereas it is poorly-conditioned if hump >> 1. However the solution
% can still be relatively fairly accurate even when the hump is large
% (the hump is an upper bound), especially when the hump and
% ||w(t)||/||v|| are of the same order of magnitude (further details in
% reference below).
%
% Example 1:
% ----------
% n = 100;
% A = rand(n);
% v = eye(n,1);
% w = expv(1,A,v);
%
% Example 2:
% ----------
% % generate a random sparse matrix
% n = 100;
% A = rand(n);
% for j = 1:n
% for i = 1:n
% if rand < 0.5, A(i,j) = 0; end;
% end;
% end;
% v = eye(n,1);
% A = sparse(A); % invaluable for a large and sparse matrix.
%
% tic
% [w,err] = expv(1,A,v);
% toc
%
% disp('w(1:10) ='); disp(w(1:10));
% disp('err ='); disp(err);
%
% tic
% w_matlab = expm(full(A))*v;
% toc
%
% disp('w_matlab(1:10) ='); disp(w_matlab(1:10));
% gap = norm(w-w_matlab)/norm(w_matlab);
% disp('||w-w_matlab|| / ||w_matlab|| ='); disp(gap);
%
% In the above example, n could have been set to a larger value,
% but the computation of w_matlab will be too long (feel free to
% discard this computation).
%
% See also MEXPV, EXPOKIT.
% Roger B. Sidje ([email protected])
% EXPOKIT: Software Package for Computing Matrix Exponentials.
% ACM - Transactions On Mathematical Software, 24(1):130-156, 1998
function [w, err, hump] = expv( t, A, v, tol, m )
[n,n] = size(A);
if nargin == 3,
tol = 1.0e-7;
m = min(n,30);
end;
if nargin == 4,
m = min(n,30);
end;
anorm = norm(A,'inf');
mxrej = 10; btol = 1.0e-7;
gamma = 0.9; delta = 1.2;
mb = m; t_out = abs(t);
nstep = 0; t_new = 0;
t_now = 0; s_error = 0;
rndoff= anorm*eps;
k1 = 2; xm = 1/m; normv = norm(v); beta = normv;
fact = (((m+1)/exp(1))^(m+1))*sqrt(2*pi*(m+1));
t_new = (1/anorm)*((fact*tol)/(4*beta*anorm))^xm;
s = 10^(floor(log10(t_new))-1); t_new = ceil(t_new/s)*s;
sgn = sign(t); nstep = 0;
w = v;
hump = normv;
while t_now < t_out
nstep = nstep + 1;
t_step = min( t_out-t_now,t_new );
V = zeros(n,m+1);
H = zeros(m+2,m+2);
V(:,1) = (1/beta)*w;
for j = 1:m
p = A*V(:,j);
for i = 1:j
H(i,j) = V(:,i)'*p;
p = p-H(i,j)*V(:,i);
end;
s = norm(p);
if s < btol,
k1 = 0;
mb = j;
t_step = t_out-t_now;
break;
end;
H(j+1,j) = s;
V(:,j+1) = (1/s)*p;
end;
if k1 ~= 0,
H(m+2,m+1) = 1;
avnorm = norm(A*V(:,m+1));
end;
ireject = 0;
while ireject <= mxrej,
mx = mb + k1;
F = expm(sgn*t_step*H(1:mx,1:mx));
if k1 == 0,
err_loc = btol;
break;
else
phi1 = abs( beta*F(m+1,1) );
phi2 = abs( beta*F(m+2,1) * avnorm );
if phi1 > 10*phi2,
err_loc = phi2;
xm = 1/m;
elseif phi1 > phi2,
err_loc = (phi1*phi2)/(phi1-phi2);
xm = 1/m;
else
err_loc = phi1;
xm = 1/(m-1);
end;
end;
if err_loc <= delta * t_step*tol,
break;
else
t_step = gamma * t_step * (t_step*tol/err_loc)^xm;
s = 10^(floor(log10(t_step))-1);
t_step = ceil(t_step/s) * s;
if ireject == mxrej,
error('The requested tolerance is too high.');
end;
ireject = ireject + 1;
end;
end;
mx = mb + max( 0,k1-1 );
w = V(:,1:mx)*(beta*F(1:mx,1));
beta = norm( w );
hump = max(hump,beta);
t_now = t_now + t_step;
t_new = gamma * t_step * (t_step*tol/err_loc)^xm;
s = 10^(floor(log10(t_new))-1);
t_new = ceil(t_new/s) * s;
err_loc = max(err_loc,rndoff);
s_error = s_error + err_loc;
end;
err = s_error;
hump = hump / normv;
|
github
|
JunhuanLi/mowerautosaved-master
|
hampelf.m
|
.m
|
mowerautosaved-master/Automower/Code/Navigation/姿态解算_m/hampelf.m
| 526 |
utf_8
|
71b97d57044765b5ee65fbce7e8c4864
|
% function [xfilt, xi, xmedian, xsigma] = hampel_my(x)
function xfilt = hampelf(x)
%#codegen
k = 3;
nsigma = 3;
x = x(:);
%filter size will be 2*k+1
[xmad,xmedian] = movmadf(x,k);
% % scale the MAD by ~1.4826 as an estimate of its standard deviation
scale = 1.482602218505602;
xsigma = scale*xmad;
% identify points that are either NaN or beyond the desired threshold
xi = ~(abs(x-xmedian) <= nsigma*xsigma);
% replace identified points with the corresponding median value
xf = x;
xf(xi) = xmedian(xi);
xfilt = xf;
end
|
github
|
JunhuanLi/mowerautosaved-master
|
mag_fitting_ellipse.m
|
.m
|
mowerautosaved-master/Automower/Code/Navigation/姿态解算_m/mag_fitting_ellipse.m
| 628 |
utf_8
|
2c56f832d5f052b629d2378ba3d17488
|
% %ellipse fitting
function mag_body = mag_fitting_ellipse(ellipse_t,imu_mx,imu_my,imu_mz)
%mapping to circle
phi = ellipse_t.phi;
B = [ellipse_t.X0;ellipse_t.Y0];
Xf = max(1,ellipse_t.b/ellipse_t.a);
Yf = max(1,ellipse_t.a/ellipse_t.b);
T = diag([Xf,Yf]);
% T = diag([1,ellipse_t.a/ellipse_t.b]);
A = [cos(phi) -sin(phi);sin(phi) cos(phi)];
for k = 1:length(imu_mx)
mag_body(1:2,k) = T*((A * [imu_mx(k);imu_my(k)]) - B);%/max(ellipse_t.a,ellipse_t.b);
mag_body(3,k) = imu_mz(k);
end
% figure;plot(mag_body(1,:));hold on;plot(mag_body(2,:));grid on;legend('mx','my');
% figure;plot(mag_body(1,:),mag_body(2,:))
end
|
github
|
JunhuanLi/mowerautosaved-master
|
mag_calibration_ellipse.m
|
.m
|
mowerautosaved-master/Automower/Code/Navigation/mag_analysis/mag_calibration_ellipse.m
| 650 |
utf_8
|
226fa941d77be995f2666a1bf662f2bf
|
% %ellipse fitting
% ellipse_t = fit_ellipse(imu_mx,imu_my); %parameters
function mag_body = mag_calibration_ellipse(ellipse_t,imu_mx,imu_my,imu_mz)
%mapping to circle
phi = ellipse_t.phi;
B = [ellipse_t.X0;ellipse_t.Y0];
Xf = max(1,ellipse_t.b/ellipse_t.a);
Yf = max(1,ellipse_t.a/ellipse_t.b);
T = diag([Xf,Yf]);
% T = diag([1,ellipse_t.a/ellipse_t.b]);
A = [cos(phi) -sin(phi);sin(phi) cos(phi)];
% mag_body = zeros(3,length(imu_mx));
for k = 1:length(imu_mx)
mag_body(1:2,k) = T*(A * [imu_mx(k);imu_my(k)])-T*B;
mag_body(3,k) = imu_mz(k);
end
% hold on
% plot(imu_mx,imu_my);
% hold on;plot(ellipse_t.X0*1.27,ellipse_t.Y0,'*')
end
|
github
|
JunhuanLi/mowerautosaved-master
|
spherHarmonicEval.m
|
.m
|
mowerautosaved-master/Automower/Code/Navigation/磁偏角计算/spherHarmonicEval.m
| 4,225 |
utf_8
|
da368cd1395fe2df1b4b0bdb9d1e0e6f
|
function [V,gradV]=spherHarmonicEval(C,S,point,a,c)
%#codegen
scalFactor=10^(-280);
fullyNormalized=true;
M = 12;
%If the coefficients are Schmidt-quasi-normalized, then convert them to
%fully normalized coefficients.
if(fullyNormalized==false)
%Duplicate the input coefficients so that when they are modified, the
%original values are not changed.
for n=0:M
%Deal with all of the other m values.
k=1/sqrt(1+2*n);
for m=0:n
C(n+1,m+1)=k*C(n+1,m+1);
S(n+1,m+1)=k*S(n+1,m+1);
end
end
end
%This stores all of the powers of a/r needed for the sum, regardless of
%which algorithm is used.
V=zeros(1,1);
gradV=zeros(3,1);
% for curPoint=1:numPoints
r=point(1);
lambda=point(2);
thetaCur=point(3);
nCoeff=zeros(M+1,1);
nCoeff(1)=1;
for n=1:M
nCoeff(n+1)=nCoeff(n)*(a/r);
end
if(abs(thetaCur)<88*pi/180||nargout<2)
%At latitudes that are not near the poles, the algorithm of Holmes and
%Featherstone is used. It can not be used for the gradient near the
%poles, because of the singularity of the spherical coordinate system.
%Compute the sine and cosine terms.
[SinVec,CosVec]=calcSinCosTerms(lambda,M);
theta=pi/2-thetaCur;
u=sin(theta);
[PBarUVals,dPBarUValsdTheta]=NALegendreCosRat(theta,M,scalFactor);
%Evaluate Equation 7 from the Holmes and Featherstone paper.
XC=zeros(M+1,1);
XS=zeros(M+1,1);
for m=0:M
for n=m:M
XC(m+1)=XC(m+1)+nCoeff(n+1)*C(n+1,m+1)*PBarUVals(n+1,m+1);
XS(m+1)=XS(m+1)+nCoeff(n+1)*S(n+1,m+1)*PBarUVals(n+1,m+1);
end
end
%Use Horner's method to compute V.
V=0;
for m=M:-1:0
OmegaRat=XC(m+1)*CosVec(m+1)+XS(m+1)*SinVec(m+1);
V=V*u+OmegaRat;
end
%Multiply by the constant in front of the sum and get rid of the scale
%factor.
V=(c/r)*V/scalFactor;
%If the gradient is desired.
dVdr=0;
dVdLambda=0;
dVdTheta=0;
XCdr=zeros(M+1,1);
XSdr=zeros(M+1,1);
XCdTheta=zeros(M+1,1);
XSdTheta=zeros(M+1,1);
%Evaluate Equation 7 from the Holmes and Featherstone paper.
for m=0:M
for n=m:M
CScal=nCoeff(n+1)*C(n+1,m+1);
SScal=nCoeff(n+1)*S(n+1,m+1);
XCdr(m+1)=XCdr(m+1)+(n+1)*CScal*PBarUVals(n+1,m+1);
XSdr(m+1)=XSdr(m+1)+(n+1)*SScal*PBarUVals(n+1,m+1);
XCdTheta(m+1)=XCdTheta(m+1)+CScal*dPBarUValsdTheta(n+1,m+1);
XSdTheta(m+1)=XSdTheta(m+1)+SScal*dPBarUValsdTheta(n+1,m+1);
end
end
for m=M:-1:0
OmegaRat=XCdr(m+1)*CosVec(m+1)+XSdr(m+1)*SinVec(m+1);
dVdr=dVdr*u+OmegaRat;
OmegaRat=m*(-XC(m+1)*SinVec(m+1)+XS(m+1)*CosVec(m+1));
dVdLambda=dVdLambda*u+OmegaRat;
OmegaRat=XCdTheta(m+1)*CosVec(m+1)+XSdTheta(m+1)*SinVec(m+1);
dVdTheta=dVdTheta*u+OmegaRat;
end
dVdr=-(c/r^2)*dVdr/scalFactor;
dVdLambda=(c/r)*dVdLambda/scalFactor;
%The minus sign is because the input coordinate was with respect to
%latitude, not the co-latitude that the NALegendreCosRat function uses.
dVdTheta=-(c/r)*dVdTheta/scalFactor;
gradV(:) = calcSpherJacob(point)'*[dVdr;dVdLambda;dVdTheta];
end
end
function [SinVec,CosVec]=calcSinCosTerms(lambda,M)
%Compute sin(m*lambda) and cos(m*lambda) for m=0 to m=M.
SinVec=zeros(M+1,1);
CosVec=zeros(M+1,1);
%Explicitely set the first two terms.
SinVec(0+1)=0;
CosVec(0+1)=1;
SinVec(1+1)=sin(lambda);
CosVec(1+1)=cos(lambda);
%Use a double angle identity to get the second order term.
SinVec(2+1)=2*SinVec(1+1)*CosVec(1+1);
CosVec(2+1)=1-2*SinVec(1+1)^2;
%Use a two-part recursion for the rest of the terms.
for m=3:M
SinVec(m+1)=2*CosVec(1+1)*SinVec(m-1+1)-SinVec(m-2+1);
CosVec(m+1)=2*CosVec(1+1)*CosVec(m-1+1)-CosVec(m-2+1);
end
end
|
github
|
luk036/ellcpp-master
|
ldlt.m
|
.m
|
ellcpp-master/ldlt.m
| 921 |
utf_8
|
1d3bdb083b615f5e3b10a8e2538df357
|
%
% [L,D]=ldlt(A)
%
% This function computes the square root free Cholesky factorization
%
% A=L*D*L'
%
% where L is a lower triangular matrix with ones on the diagonal, and D
% is a diagonal matrix.
%
% It is assumed that A is symmetric and postive definite.
%
% Reference: Golub and Van Loan, "Matrix Computations", second edition,
% p 137.
% Author: Brian Borchers ([email protected])
%
function [L,D]=ldlt(A)
%
% Figure out the size of A.
%
n=size(A,1);
%
% The main loop. See Golub and Van Loan for details.
%
L=zeros(n,n);
for j=1:n,
if (j > 1),
v(1:j-1)=L(j,1:j-1).*d(1:j-1);
v(j)=A(j,j)-L(j,1:j-1)*v(1:j-1)';
d(j)=v(j);
if (j < n),
L(j+1:n,j)=(A(j+1:n,j)-L(j+1:n,1:j-1)*v(1:j-1)')/v(j);
end;
else
v(1)=A(1,1);
d(1)=v(1);
L(2:n,1)=A(2:n,1)/v(1);
end;
end;
%
% Put d into a matrix.
%
D=diag(d);
%
% Put ones on the diagonal of L.
%
L=L+eye(n);
|
github
|
adelbibi/Tensor_CSC-master
|
sparse_code_update_ADMM_2D.m
|
.m
|
Tensor_CSC-master/Training/sparse_code_update_ADMM_2D.m
| 3,409 |
utf_8
|
a5382aa76b33c22a49fa1a677ec840af
|
function [X,error_XZnorm,error_reg] = sparse_code_update_ADMM_2D(Dhat,Xhat,Yhat,n3,n4,K,N,lambda)
Xhat_per = permute(Xhat,[3,4, 1, 2]);
X_per = real(ifft2(Xhat_per))*sqrt(n3*n4);
X = permute(X_per,[3,4, 1, 2]);
Z = X;
U = Z;
%% Conj function parameters
pcg_tol = 1e-7;
%% ADMM updates parameters init
rho = 1;
gamma = 1e-2;
rho_max = 600;
error_XZnorm_thresh = 1e-7;
error_reg_change_thresh = 1e-7;
error_XZnorm = inf;
max_iter = 150;
counter = 0;
temp2=[];
error_reg = [];
Xhat_Cat=[];
counter_error = 1;
%% ADMM
while(true)
counter = counter + 1;
if(counter > max_iter)
break;
end
%Prepare data for foureir domain solution of X
Z_per = permute(Z,[3, 4, 1, 2]); Zhat_per = fft2(Z_per)/sqrt(n3*n4); Zhat = permute(Zhat_per,[3, 4, 1, 2]);
U_per = permute(U,[3, 4, 1, 2]); Uhat_per = fft2(U_per)/sqrt(n3*n4); Uhat = permute(Uhat_per,[3, 4, 1, 2]);
%% Update Xhat in the Foureir Domain
for image_train=1:N
parfor comb_ind=1:(n3*n4)
rhs = (Dhat(:,:,comb_ind)'*Yhat(:,image_train,comb_ind) + rho*Zhat(:,image_train,comb_ind) - Uhat(:,image_train,comb_ind));
[Xhat_Cat(:,image_train,comb_ind),cg_flag,~,pcg_iter] = pcg(@afun_Xhat,rhs,pcg_tol,[],[],[],Xhat(:,image_train,comb_ind),Dhat(:,:,comb_ind),rho);
end
end
Xhat = reshape(Xhat_Cat,K,N,n3,n4);
X_hat_per = permute(Xhat,[3,4,1,2]);
%going back to time domain
X = permute(real(ifft2(X_hat_per)),[3,4,1,2])*sqrt(n3*n4);
%% Update Zhat
temp = X + (1/rho)*U;
Z = prox_111_norm(temp,lambda,rho);
%% Update Uhat
U = U + rho * (X - Z);
%% Compute cost and errors
if(mod(counter,10) == 0)
X_Z_errors = reshape(X - Z,[],1);
error_XZnorm(counter_error) = sqrt(X_Z_errors'*X_Z_errors);
for image_train=1:N
parfor comb_ind_kw=1:(n3*n4)
temp2(:,image_train,comb_ind_kw) = (Yhat(:,image_train,comb_ind_kw) - Dhat(:,:,comb_ind_kw)*Xhat(:,image_train,comb_ind_kw));
end
end
for image_train=1:N
du22mmy = temp2(:,image_train,:);
dummy_sum(image_train) = sqrt(du22mmy(:)'*du22mmy(:));
end
error_reg(counter_error) = sum(dummy_sum);
if (counter_error == 1)
error_reg_change = 0 ;
error_XZnorm_change = 0;
else
error_reg_change = norm(error_reg(end) - error_reg(end-1))/norm(error_reg(end-1));
error_XZnorm_change = norm(error_XZnorm(end) - error_XZnorm(end-1))/norm(error_XZnorm(end-1));
end
counter_error = counter_error + 1;
%% Print
if mod(counter,1)== 0
fprintf('+ Iter: %f RegError: %1.3f ConsError: %1.3f Rho: %f \n',counter,error_reg(end),error_XZnorm(end),rho);
end
%% Checks for breaks
if(counter_error > 2)
if(error_XZnorm_change < error_XZnorm_thresh || error_reg_change < error_reg_change_thresh)
break;
end
end
end
%% Parameter update
rho = rho*(1+gamma);
rho = min(rho_max, rho);
end
Xhat_per = permute(Xhat,[3,4, 1, 2]);
X_per = real(ifft2(Xhat_per));
X = permute(X_per,[3,4, 1, 2]);
fprintf('+ Updateing X (Sparse Code): took %d iterations. \n',counter);
return;
%% functions for variable update
function [res] = afun_Xhat(Xhat,Dhat,rho)
dummy_1 = Dhat* Xhat;
dummy_2 = Dhat'*dummy_1;
res = dummy_2 + rho*Xhat;
return;
|
github
|
adelbibi/Tensor_CSC-master
|
rconv2.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/rconv2.m
| 1,789 |
utf_8
|
5e2a3b15d1c1fadc409d5cb3b6a5b4b7
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% Convolution of two matrices, with boundaries handled via reflection
% about the edge pixels. Result will be of size of LARGER matrix.
%
% Further adapted for speed by Matthew Zeiler.
%
% @file
% @author Matthew Zeiler
% @author Eero Simonscelli
% @date Feb 13, 2010
%
% @ipp_file @copybrief make_noz.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief make_noz.m
% @param large the image you want to convolve over.
% @param small the filter you want to convolve with.
%
% @retval c the convolved image.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function c = rconv2(large,small)
ctr = 0;
% if (( size(a,1) >= size(b,1) ) & ( size(a,2) >= size(b,2) ))
% large = a; small = b;
% elseif (( size(a,1) <= size(b,1) ) & ( size(a,2) <= size(b,2) ))
% large = b; small = a;
% else
% error('one arg must be larger than the other in both dimensions!');
% end
ly = size(large,1);
lx = size(large,2);
sy = size(small,1);
sx = size(small,2);
%% These values are one less than the index of the small mtx that falls on
%% the border pixel of the large matrix when computing the first
%% convolution response sample:
sy2 = floor((sy+ctr-1)/2);
sx2 = floor((sx+ctr-1)/2);
% pad with reflected copies
clarge = [
large(sy-sy2:-1:2,sx-sx2:-1:2), large(sy-sy2:-1:2,:), ...
large(sy-sy2:-1:2,lx-1:-1:lx-sx2); ...
large(:,sx-sx2:-1:2), large, large(:,lx-1:-1:lx-sx2); ...
large(ly-1:-1:ly-sy2,sx-sx2:-1:2), ...
large(ly-1:-1:ly-sy2,:), ...
large(ly-1:-1:ly-sy2,lx-1:-1:lx-sx2) ];
% keyboard
c = conv2(clarge,small,'valid');
|
github
|
adelbibi/Tensor_CSC-master
|
CreateImagesList.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/CreateImagesList.m
| 25,616 |
utf_8
|
1c9fb0d1123e9dc41f5b3d446351b08e
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% This takes all images from the input folder, converts them to the desired
% colorspace, removes mean/divides by standard deviations (if desired), and
% constrast normalizes the image (if desired). If the images are of different
% sizes, then it will padd them with zeros (after contrast normalizing) to make
% them square (assumes that they all images have the same maximum dimension).
% Note that some of the whitening/contrast normalization features are not
% fully tested for datasets where the images are of variable size so please
% use with caution in that case. For best result, resize all the images to the
% same dimensions beforehand.
%
% @file
% @author Matthew Zeiler
% @date Mar 11, 2010
%
% @image_file @copybrief CreateImages.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief CreateImages.m
%
% @param imgs_path either 1) a path to a folder contain only image files (or other folders
% which will be ignored), 2) a variable with the images as xdim x ydim x
% num_colors x num_images size , 3) a path to a file that contains a variable
% called I that has images as xdim x ydim x num_colors x num_images, or 4)
% a path to a folder containing a single .mat file containing a variable called
% I that has images as xdim x ydim x num_colors x num_images.
% @param CONTRAST_NORMALIZE [optional] binary value indicating whether to contrast
% normalize or whiten the images. Defaults to local contrast normalization ('local_cn').
% Available types are: 'none','local_cn','laplacian_cn','box_cn','PCA_whitening',
% 'ZCA_image_whitening','ZCA_patch_whitening',and 'inv_f_whitening'
% @param ZERO_MEAN [optional] binary value indicating whether to subtract the mean and divides by standard deviation (current
% commented out in the code). Defuaults to 1.
% @param COLOR_TYPE [optional] a string of: 'gray','rgb','ycbcr','hsv'. Defaults to 'gray'.
% @param SQUARE_IMAGES [optional] binary value indicating whether or not to square the
% images. This must be used if using different sized images. Even then the max
% dimensions of each image must be the same. Defaults to 0.
% @param image_selection the subset of images you want to select. This is a cell
% array with 3 dimensions, {A,B,C} -> A:B:C where A and B are numbers and C can
% be a number or 'end' string.
%
% @retval I the images as: xdim x ydim x color_channels x num_images
% @retval mn the mean if ZERO_MEAN was set.
% @retval sd the standard deviation if ZERO_MEAN was set.
% @retval xdim the size of the images in x direction.
% @retval ydim the size of the images in y direction.
% @retval resI the (image-contrast normalized image) if CONTRAST_NORMALIZE is
% set.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I] = CreateImagesList(imgs_path,CONTRAST_NORMALIZE,ZERO_MEAN,COLOR_TYPE,SQUARE_IMAGES,image_frames)
% Defaults
if(nargin<6)
image_frames = {1,1,'end'};
end
if(nargin<5)
SQUARE_IMAGES = 0;
end
if(nargin<4)
COLOR_TYPE = 'gray'
end
if(nargin<3)
ZERO_MEAN = 1
end
if(nargin<2)
CONTRAST_NORMALIZE = 'local_cn'
end
if(isnumeric(CONTRAST_NORMALIZE))
if(CONTRAST_NORMALIZE==1)
CONTRAST_NORMALIZE = 'local_cn';
else
CONTRAST_NORMALIZE = 'none';
end
end
% For backwards compatibility, revert to grayscale.
if(isnumeric(COLOR_TYPE))
if(COLOR_TYPE == 1)
COLOR_TYPE = 'rgb';
else
COLOR_TYPE = 'gray';
end
end
% For backwards compatibility, revert to grayscale.
if(isnumeric(COLOR_TYPE))
if(COLOR_TYPE == 1)
COLOR_TYPE = 'local_cn';
else
COLOR_TYPE = 'none';
end
end
% Select only the frames (images) you want.
if(ischar(image_frames{3}))
last_ind = sprintf('%d:%d:%s',image_frames{1},image_frames{2},image_frames{3});
else
last_ind = sprintf('%d:%d:%d',image_frames{1},image_frames{2},image_frames{3});
end
fprintf('Going to select frames: %s',last_ind);
% Cell array listing all files and paths.
subdir = dir(imgs_path);
[~,files] = split_folders_files(subdir);
if(check_imgs_path(imgs_path)==0)
error('Path to images is not a valid .mat file or a directory of images.');
end
% Make sure it is a directory and doesn't just have one file that is not an image.
if(ischar(imgs_path) && exist(imgs_path,'dir')>0 && (length(files)>1 ...
|| (length(files)==1 && strcmp(files(1).name(end-3:end),'.mat')==0)))
% Make sure the directory ends in '/'
if(strcmp(imgs_path(end),'/')==0)
imgs_path = [imgs_path '/'];
end
% Counter for the image
image = 1;
if(length(files) == 0)
error('No Images in this directory');
end
% I = cell(1,length(files));
actual_files = 0;
fprintf('The length of the I file cell array found in this directory is: %d\n',length(files));
% Make sure the selection is not over the number of files.
if(ischar(image_frames{3}))
image_frames{3} = length(files);
else
if(image_frames{3}>length(files))
image_frames{3}=length(files);
end
end
% Loop through the number of files ignoring . and ..
for file=image_frames{1}:image_frames{2}:image_frames{3}
% Makes sure not to count subdirectories
if (files(file).isdir == 0)
% Get the path to the given file.
img_name = strcat(imgs_path,files(file).name);
try
% Load the image file
IMG = single(imread(img_name));
% Count number of images loaded.
actual_files = actual_files+1;
fprintf('Loading: %s \n Image: %10d/%10d. Selecting every %5d. Selected: %10d so far.\r',img_name,file,length(files),image_frames{2},actual_files);
if(actual_files==1)
I = cell(1,length(files));
end
I{actual_files} = IMG;
% Increment the number of images found so far.
image=image+1;
catch
fprintf('Counld not load %s as an image.\n',img_name);
end
end
end
I = I(1:actual_files);
% Automatically find the .mat file in the directory that contains all images (no other files or folders can be in teh directory though).
elseif(ischar(imgs_path) && (length(files)==1 && strcmp(files(1).name(end-3:end),'.mat'))) % Only 1 file in folder and it's a .mat
load([imgs_path files(1).name]);
if(exist('original_images','var'))
I = original_images;
clear original_images;
end
clear imgs_path
% Make sure the images are single.
I = single(I);
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
origI = I;
I = cell(1,size(origI,4));
for i=1:size(origI,4)
fprintf('Loaded image: %10d from file.\r',i);
I{i} = origI(:,:,:,i);
end
actual_files = size(origI,4);
clear origI
elseif(ischar(imgs_path) && exist(imgs_path,'file')~=0) % Path is to a file with all images in it.
fprintf('\nLoading %s\n',imgs_path);
% May be a .mat file.
if(strcmp(imgs_path(end-3:end),'.mat'))
fprintf('Loading single .mat file');
load(imgs_path);
else % May be a single image.
fprintf('Reading single image.\n');
I = single(imread(imgs_path));
end
if(exist('original_images','var'))
I = original_images;
clear original_images;
end
clear imgs_path
I = single(I);
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
fprintf('Converting from matrix to cell array selected %d images.\n',size(I,4));
I = mat2cell(I,size(I,1),size(I,2),size(I,3),ones(size(I,4),1));
I = reshape(I,[size(I,4) 1]);
actual_files = size(I,2);
else % The imgs_path is a variable of images ( can just use it instead of loading).
I = imgs_path;
clear imgs_path
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
origI = I;
I = cell(1,size(origI,4));
for i=1:size(origI,4)
fprintf('Loaded image: %10d from file.\r',i);
I{i} = origI(:,:,:,i);
end
actual_files = size(origI,4);
clear origI
end
clear files subdir
fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Convert the colors here.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% old_I = I;
for i=1:length(I)
switch(COLOR_TYPE)
case 'rgb'
fprintf('Making RGB Image %10d\r',i);
% IMG = rgb_im;
% Normalize the RGB values to [0,1] (do not do this on YCbCr!!!!!).
I{i} = double(I{i})/255.0;
case 'ycbcr'
fprintf('Making YUV Image %10d\r',i);
I{i} = double(rgb2ycbcr(double(I{i})/255.0));
case 'hsv'
fprintf('Making HSV Image %10d\r',i);
I{i} = double(rgb2hsv(double(I{i})/255.0));
case 'gray'
fprintf('Making Gray Image %10d\r',i);
% Convert to grayscale
if(size(I{i},3)==3)
I{i} = single(rgb2gray(double(I{i})/255.0));
else
if(max(I{i}(:))>1)
I{i} = double(I{i})/255.0;
else
I{i} = double(I{i});
end
end
end
% I{i} = IMG;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Contrast normalize the image?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CN_I = cell(size(I));
% res_I = cell(size(I));
switch(CONTRAST_NORMALIZE)
case 'none'
fprintf('Not doing any constrast normalization or whitening to the images.\n');
% Make the CN_I result the original images.
% CN_I = I;
% res_I = I;
case 'local_cn'
%%%%%
%% Local Constrast Normalization.
%%%%%
num_colors = size(I{1},3);
% k = fspecial('gaussian',[13 13],1.591*3);
% k = fspecial('gaussian',[5 5],1.591);
k = fspecial('gaussian',[13 13],3*1.591);
k2 = fspecial('gaussian',[13 13],3*1.591);
% k = fspecial('gaussian',[7 7],1.5*1.591);
% k2 = fspecial('gaussian',[7 7],1.5*1.591);
if(all(k(:)==k2(:)))
SAME_KERNELS=1;
else
SAME_KERNELS=0;
end
for image=1:length(I)
fprintf('Contrast Normalizing Image with Local CN: %10d\r',image);
temp = I{image};
for j=1:num_colors
% if(image==151)
% keyboard
% end
dim = double(temp(:,:,j));
% lmn = conv2(dim,k,'valid');
% lmnsq = conv2(dim.^2,k,'valid');
lmn = rconv2(dim,k);
lmnsq = rconv2(dim.^2,k2);
if(SAME_KERNELS)
lmn2 = lmn;
else
lmn2 = rconv2(dim,k2);
end
lvar = lmnsq - lmn2.^2;
lvar(lvar<0) = 0; % avoid numerical problems
lstd = sqrt(lvar);
q=sort(lstd(:));
lq = round(length(q)/2);
th = q(lq);
if(th==0)
q = nonzeros(q);
if(~isempty(q))
lq = round(length(q)/2);
th = q(lq);
else
th = 0;
end
end
lstd(lstd<=th) = th;
%lstd(lstd<(8/255)) = 8/255;
% lstd = conv2(lstd,k2,'same');
lstd(lstd(:)==0) = eps;
% shifti = floor(size(k,1)/2)+1;
% shiftj = floor(size(k,2)/2)+1;
% since we do valid convolutions
% dim = dim(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1);
dim = dim - lmn;
dim = dim ./ lstd;
temp(:,:,j) = dim;
% res_I{image}(:,:,j) = single(double(I{image}(:,:,j))-dim);
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
% IMG = conI;
end
I{image} = single(temp);
end
case 'laplacian_cn'
%%%%%
%% CN with a laplacian filter (CVPR 2010 method).
%%%%%
% Run a laplacian over images to get edge features.
h = fspecial('laplacian',0.2);
shifti = floor(size(h,1)/2)+1;
shiftj = floor(size(h,2)/2)+1;
% Loop through the number of images
for image=1:length(I)
fprintf('Contrast Normalizing Image with Laplacian: %10d\r',image);
for j=1:size(I{1},3) % Each color plane needs to be passed with laplacin
I{image}(:,:,j) = conv2(single(I{image}(:,:,j)),single(h),'same');
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(CN_I{image},1)-1,shiftj:shiftj+size(CN_I{image},2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
end
end
case 'box_cn'
%%%%%%
%% CN with a box filter (has bad boundary effects though)
%%%%%%
boxf = ones(5,5)/25;
for image=1:size(I,4)
fprintf('Contrast Normalizing Image with Box Filtering: %10d\r',image);
for j=1:size(I,3)
I(:,:,j,image) = I(:,:,j,image) - imfilter(I(:,:,j,image),boxf,'replicate');
end
CN_I{image} = I(:,:,:,image);
end
case 'PCA_whitening'
%%%%%
%% PCA based whitening
%%%%%
for color=1:size(I,3)
fprintf('\nPCA whitening all images...\n\n');
data = double(reshape(I(:,:,color,:),size(I,1)*size(I,2),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data);
[V D] = eig(cc);
ii = cumsum(fliplr(diag(D)'))/sum(D(:));
nrc = length(find(ii<0.99)); % retain 99% of the variance
V = V(:,end-nrc+1:end);
D = D(end-nrc+1:end,end-nrc+1:end);
PCAtransf = diag(diag(D).^-0.5) * V';
invPCAtransf = V * diag(diag(D).^0.5);
data = single(data * PCAtransf');
% whitendata = single(data * PCAtransf');
I(:,:,color,1:size(PCAtransf,1)) = reshape(data,size(I(:,:,color,1:size(PCAtransf,1))));
end
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_image_whitening'
%%%%%
%% ZCA image based whitening (uses entire images).
%% this is much slower than the below for large images.
%%%%%
fprintf('\nZCA whitening all images...this can take a while...\n\n');
data = double(reshape(I,size(I,1)*size(I,2)*size(I,3),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% whitening happens here.
data = data*ZCAtransform;
% data = data*invZCAtransform*sd+repmat(mn,1,size(data,2));
I = reshape(data,size(I));
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_patch_whitening'
%%%%%
%% ZCA patch based whitening (uses randomly selected patches)
%% this is much faster than the above.
%%%%%
%%%%%%%%%%%%%%%%%%%
% Define the patch size (largest one possible)
%%%%%%%%%%%%%%%%%%%
for patch_size=size(I,1):-1:1
% Has to evenly divide into image.
if(mod(size(I,1),patch_size)==0)
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
% Need more patches from the dataset than size of
% patches (which are times # of colors).
if(size(temp,2)*size(I,4)>size(temp,1)*size(I,3))
break
end
end
end
fprintf('Size of the whitening filter is %d.\n',patch_size);
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Derive whitening transform from random patches of the images.
%%%%%%%%%%%%%%%%%%%
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
data = zeros(patch_size^2,size(temp,2),size(I,3),size(I,4));
clear temp
% Create image patches of 11x11 size.
indices = randperm(size(I,4));
for i=1:size(I,4)
% Use random selection of the images.
ind = indices(i);
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,ind),[patch_size patch_size],'distinct');
end
% Keep only 100,000 patches around for computing the whitening transforms.
if(size(data,2)*i>100000)
break
end
end
fprintf('\nZCA whitening all images based on patches...\n\n');
data = data(:,:,:,1:i);
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data)
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
patch_mn = mean(data,2);
data = data - repmat(patch_mn,[1 size(data,2)]);
patch_sd = std(data(:));
data = data/patch_sd;
size(data)
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% Get middle index (where the filters are in ZCAtransform.
middle = sub2ind([patch_size patch_size],ceil(patch_size/2),ceil(patch_size/2));
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters(:,:,:,color) = reshape(ZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(100+color)
% imshow(filters(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters2(:,:,:,color) = reshape(invZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(200+color)
% imshow(filters2(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Applying ZCA transform to each distinct patch and then forming images
% again.
clear data
for i=1:size(I,4)
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,i),[patch_size patch_size],'distinct');
end
end
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data);
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
data= ZCAtransform*data;
data = reshape(data,patch,colors,num_patches,num_images);
data=permute(data,[1 3 2 4]);
for i=1:size(I,4)
for color=1:size(I,3)
I(:,:,color,i) = col2im(data(:,:,color,i),[patch_size patch_size],[size(I,1) size(I,2)],'distinct');
end
end
%%%%%%%%%%%%%%%%%%%%
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'inv_f_whitening'
%%%%%
%% 1/f whitening of the images
%%%%%
% Number of images.
M=length(I);
REGULARIZATION=0.3;
WHITEN_POWER = 4;
WHITEN_SCALE = 0.4;
EPSILON = 1e-3;
BORDER=0;
for i=1:M
fprintf('Whitening image: %10d\r',i);
temp_im = I{i};
[imx,imy,imc] = size(temp_im);
if(exist('I','var')==0)
I = zeros(imx,imy,imc,M);
end
% Make 1/f filter
[fx fy]=meshgrid(-imy/2:imy/2-1,-imx/2:imx/2-1);
rho=sqrt(fx.*fx+fy.*fy)+REGULARIZATION;
f_0=WHITEN_SCALE*mean([imx,imy]);
filt=rho.*exp(-(rho/f_0).^WHITEN_POWER) + EPSILON;
for c=1:imc
If=fft2(temp_im(:,:,c));
imagew=real(ifft2(If.*fftshift(filt)));
BORDER_VALUE = mean(imagew(:));
if(BORDER~=0)
imagew(1:BORDER,:,:,:)=BORDER_VALUE;
imagew(:,1:BORDER,:,:)=BORDER_VALUE;
imagew(end-BORDER+1:end,:,:,:)=BORDER_VALUE;
imagew(:,end-BORDER+1:end,:,:)=BORDER_VALUE;
end
temp_im(:,:,c) = imagew;
end
CN_I{i} = temp_im;
res_I{i} = I{i}-CN_I{i};
% I(:,:,:,i) = temp_im;
end
case 'sep_mean' % Make each image separately have zero mean (useful for text.
for i=1:length(I)
fprintf('Zero Meaning Image %10d',i);
I{i} = I{i}-mean(I{i}(:));
% res_I{i} = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
if ZERO_MEAN
for i=1:length(I)
fprintf('Making Image %10d Zero Mean.\r',i);
I{i} = I{i} - mean(I{i}(:));
end
end
fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Square the images to the max dimension.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear PADIMG; % Size of I may have changed by this point due to CN.
if(SQUARE_IMAGES)
% Now pad them again to ensure they are square.
% This has to be done after contrast normalizing to avoid strong edges on padded
% regions.
% max_size = max(size(I{1},1),size(I{1},2));
% I = zeros(max_size,max_size,size(I{1},3),length(I),'single');
% resI = zeros(max_size,max_size,size(I{1},3),length(I),'single');
for image=1:length(I)
[xdim ydim planes] = size(I{image});
if(xdim~=ydim) % If not already square.
maxdim = max(xdim,ydim);
PADIMG = zeros(maxdim,maxdim,planes,'single');
% RESIMG = zeros(maxdim,maxdim,planes,'single');
for plane=1:planes
tempimg = padarray(I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
PADIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
% tempimg = padarray(res_I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
% RESIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
end
% Store the padded images into a matrix (as they are all the same
% dimension).
fprintf('Squaring Image: %10d\r',image);
I{image} = single(PADIMG);
% resI(:,:,:,image) = RESIMG;
else
fprintf('Image %10d Already Square\r',image);
I{image} = single(I{image});
% resI(:,:,:,image) = res_I{image};
end
% Save memory.
% I{image} = [];
% res_I{image} = [];
end
end
fprintf('\nAll Images have been loaded and preprocessed.\n\n');
|
github
|
adelbibi/Tensor_CSC-master
|
split_folders_files.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/split_folders_files.m
| 1,172 |
utf_8
|
e1d2fca2cb656660543772eb4e5468b0
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% Return two struct arrays of just the folers and just the files of the input
% struct array.
%
% @file
% @author Matthew Zeiler
% @date Mar 11, 2010
%
% @fileman_file @copybrief split_folders_files.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief split_folders_files.m
%
% @param input a struct array of both files and folders combined.
% @retval folders a struct array of the folders
% @retval files a struct array of the files
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [folders,files] = split_folders_files(input)
%
% folders = input(find(~cellfun(@iszero,{input(:).isdir})));
%
% files = input(find(cellfun(@iszero,{input(:).isdir})));
%
%
% function [result] = iszero(input)
%
% if(input==0)
% result = 1;
% else
% result = 0;
% end
% end
B = struct2cell(input);
dirs = cell2mat(B(4,:));
folders = input(logical(dirs));
files = input(~logical(dirs));
end
|
github
|
adelbibi/Tensor_CSC-master
|
check_imgs_path.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/check_imgs_path.m
| 1,977 |
utf_8
|
6efa00d529b073702ab46ee25cb25b2e
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% This is a helper function to check that there are valid image files or
% a .mat in the input path that can be used by CreateImages.m
%
% @file
% @author Matthew Zeiler
% @date Jun 28, 2011
%
% @image_file @copybrief check_imgs_path.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief check_imgs_path.m
%
% @param path the path to check
%
% @retval valid 1 if the path is valid and 0 if it is no good.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [valid] = check_imgs_path(path)
if(strcmp(path(end),'/')==0)
path = [path '/'];
end
valid = 1;
% Make sure the path is a string to continue the checks, otherwise it's fine as a variable.
if(ischar(path))
% As a string it has to be a file or a directory
if(~exist(path,'file') || ~exist(path,'dir'))
fprintf('Image Path is not a directory or a file\n');
valid = 0;
return;
end
% Cell array listing all files and paths.
subdir = dir(path);
[blah,files] = split_folders_files(subdir);
% Empty directory
if(exist(path,'dir') && length(files)==0)
fprintf('No files in Image directory\n');
valid = 0;
return;
end
if(length(files)==1)% Can be a single image in the directory or a .mat file.
if(strcmp(files(1).name(end-3:end),'.mat'))
valid = 1; % okay
return;
else % make sure it is an image
try
imread([path files(1).name]);
catch
fprintf('There is no single .mat file in the directory or the single file is not images.\n');
valid = 0; % Not an image
return;
end
end
end
else
valid = 1;
end
|
github
|
adelbibi/Tensor_CSC-master
|
CreateImage.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/CreateImage.m
| 24,712 |
utf_8
|
4332dbe1daa9b2d1803b445a61363183
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% This takes all images from the input folder, converts them to the desired
% colorspace, removes mean/divides by standard deviations (if desired), and
% constrast normalizes the image (if desired). If the images are of different
% sizes, then it will padd them with zeros (after contrast normalizing) to make
% them square (assumes that they all images have the same maximum dimension).
% Note that some of the whitening/contrast normalization features are not
% fully tested for datasets where the images are of variable size so please
% use with caution in that case. For best result, resize all the images to the
% same dimensions beforehand.
%
% @file
% @author Matthew Zeiler
% @date Mar 11, 2010
%
% @image_file @copybrief CreateImages.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief CreateImages.m
%
% @param imgs_path either 1) a path to a folder contain only image files (or other folders
% which will be ignored), 2) a variable with the images as xdim x ydim x
% num_colors x num_images size , 3) a path to a file that contains a variable
% called I that has images as xdim x ydim x num_colors x num_images, or 4)
% a path to a folder containing a single .mat file containing a variable called
% I that has images as xdim x ydim x num_colors x num_images.
% @param CONTRAST_NORMALIZE [optional] binary value indicating whether to contrast
% normalize or whiten the images. Defaults to local contrast normalization ('local_cn').
% Available types are: 'none','local_cn','laplacian_cn','box_cn','PCA_whitening',
% 'ZCA_image_whitening','ZCA_patch_whitening',and 'inv_f_whitening'
% @param ZERO_MEAN [optional] binary value indicating whether to subtract the mean and divides by standard deviation (current
% commented out in the code). Defuaults to 1.
% @param COLOR_TYPE [optional] a string of: 'gray','rgb','ycbcr','hsv'. Defaults to 'gray'.
% @param SQUARE_IMAGES [optional] binary value indicating whether or not to square the
% images. This must be used if using different sized images. Even then the max
% dimensions of each image must be the same. Defaults to 0.
% @param image_selection the subset of images you want to select. This is a cell
% array with 3 dimensions, {A,B,C} -> A:B:C where A and B are numbers and C can
% be a number or 'end' string.
%
% @retval I the images as: xdim x ydim x color_channels x num_images
% @retval mn the mean if ZERO_MEAN was set.
% @retval sd the standard deviation if ZERO_MEAN was set.
% @retval xdim the size of the images in x direction.
% @retval ydim the size of the images in y direction.
% @retval resI the (image-contrast normalized image) if CONTRAST_NORMALIZE is
% set.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I] = CreateImages(imgs_path,CONTRAST_NORMALIZE,ZERO_MEAN,COLOR_TYPE,SQUARE_IMAGES,image_frames)
global pars
% Defaults
if(nargin<6)
image_frames = {1,1,'end'};
end
if(nargin<5)
SQUARE_IMAGES = 0;
end
if(nargin<4)
COLOR_TYPE = 'gray'
end
if(nargin<3)
ZERO_MEAN = 1
end
if(nargin<2)
CONTRAST_NORMALIZE = 'local_cn'
end
if(isnumeric(CONTRAST_NORMALIZE))
if(CONTRAST_NORMALIZE==1)
CONTRAST_NORMALIZE = 'local_cn';
else
CONTRAST_NORMALIZE = 'none';
end
end
% For backwards compatibility, revert to grayscale.
if(isnumeric(COLOR_TYPE))
if(COLOR_TYPE == 1)
COLOR_TYPE = 'rgb';
else
COLOR_TYPE = 'gray';
end
end
% For backwards compatibility, revert to grayscale.
if(isnumeric(COLOR_TYPE))
if(COLOR_TYPE == 1)
COLOR_TYPE = 'local_cn';
else
COLOR_TYPE = 'none';
end
end
% % Select only the frames (images) you want.
% if(ischar(image_frames{3}))
% last_ind = sprintf('%d:%d:%s',image_frames{1},image_frames{2},image_frames{3});
% else
% last_ind = sprintf('%d:%d:%d',image_frames{1},image_frames{2},image_frames{3});
% end
%
% if strcmp(pars.verbose,'all')
% fprintf('Going to select frames: %s',last_ind);
% end
% Cell array listing all files and paths.
% subdir = dir(imgs_path);
% [~,files] = split_folders_files(subdir);
%
% if(check_imgs_path(imgs_path)==0)
% error('Path to images is not a valid .mat file or a directory of images.');
% end
% Make sure it is a directory and doesn't just have one file that is not an image.
% if(ischar(imgs_path) && exist(imgs_path,'dir')>0 && (length(files)>1 ...
% || (length(files)==1 && strcmp(files(1).name(end-3:end),'.mat')==0)))
%
% % Make sure the directory ends in '/'
% if(strcmp(imgs_path(end),'/')==0)
% imgs_path = [imgs_path '/'];
% end
% Counter for the image
image = 1;
if(~exist(imgs_path))
error('No Images in this directory');
end
% I = cell(1,length(files));
% actual_files = 0;
% if strcmp(pars.verbose,'all')
% fprintf('The length of the I file cell array found in this directory is: %d\n',length(files));
% end
% Make sure the selection is not over the number of files.
% if(ischar(image_frames{3}))
% image_frames{3} = length(files);
% else
% if(image_frames{3}>length(files))
% image_frames{3}=length(files);
% end
% end
% Loop through the number of files ignoring . and ..
% for file=image_frames{1}:image_frames{2}:image_frames{3}
% % Makes sure not to count subdirectories
% if (files(file).isdir == 0)
%
%
% % Get the path to the given file.
% img_name = strcat(imgs_path,files(file).name);
%
% try
% Load the image file
IMG = single(imread(imgs_path));
% Count number of images loaded.
% actual_files = actual_files+1;
% if strcmp(pars.verbose,'all')
% fprintf('Loading: %s \n Image: %10d/%10d. Selecting every %5d. Selected: %10d so far.\r',img_name,file,length(files),image_frames{2},actual_files);
% end
% if(actual_files==1)
I = cell(1,1);
% end
I{1} = IMG;
% Increment the number of images found so far.
% image=image+1;
% catch
% if strcmp(pars.verbose,'all')
% fprintf('Counld not load %s as an image.\n',img_name);
% end
% end
% end
% end
% I = I(1:actual_files);
% Automatically find the .mat file in the directory that contains all images (no other files or folders can be in teh directory though).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Convert the colors here.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% old_I = I;
for i=1:length(I)
switch(COLOR_TYPE)
case 'rgb'
fprintf('Making RGB Image %10d\r',i);
% IMG = rgb_im;
% Normalize the RGB values to [0,1] (do not do this on YCbCr!!!!!).
I{i} = double(I{i})/255.0;
case 'ycbcr'
fprintf('Making YUV Image %10d\r',i);
I{i} = double(rgb2ycbcr(double(I{i})/255.0));
case 'hsv'
fprintf('Making HSV Image %10d\r',i);
I{i} = double(rgb2hsv(double(I{i})/255.0));
case 'gray'
if strcmp(pars.verbose,'all')
fprintf('Making Gray Image %10d\r',i);
end
% Convert to grayscale
if(size(I{i},3)==3)
I{i} = single(rgb2gray(double(I{i})/255.0));
else
if(max(I{i}(:))>1)
I{i} = double(I{i})/255.0;
else
I{i} = double(I{i});
end
end
end
% I{i} = IMG;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Contrast normalize the image?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CN_I = cell(size(I));
% res_I = cell(size(I));
switch(CONTRAST_NORMALIZE)
case 'none'
fprintf('Not doing any constrast normalization or whitening to the images.\n');
% Make the CN_I result the original images.
% CN_I = I;
% res_I = I;
case 'local_cn'
%%%%%
%% Local Constrast Normalization.
%%%%%
num_colors = size(I{1},3);
% k = fspecial('gaussian',[13 13],1.591*3);
% k = fspecial('gaussian',[5 5],1.591);
k = fspecial('gaussian',[13 13],3*1.591);
k2 = fspecial('gaussian',[13 13],3*1.591);
% k = fspecial('gaussian',[7 7],1.5*1.591);
% k2 = fspecial('gaussian',[7 7],1.5*1.591);
if(all(k(:)==k2(:)))
SAME_KERNELS=1;
else
SAME_KERNELS=0;
end
for image=1:length(I)
if strcmp(pars.verbose,'all')
fprintf('Contrast Normalizing Image with Local CN: %10d\r',image);
end
temp = I{image};
for j=1:num_colors
% if(image==151)
% keyboard
% end
dim = double(temp(:,:,j));
% lmn = conv2(dim,k,'valid');
% lmnsq = conv2(dim.^2,k,'valid');
lmn = rconv2(dim,k);
lmnsq = rconv2(dim.^2,k2);
if(SAME_KERNELS)
lmn2 = lmn;
else
lmn2 = rconv2(dim,k2);
end
lvar = lmnsq - lmn2.^2;
lvar(lvar<0) = 0; % avoid numerical problems
lstd = sqrt(lvar);
q=sort(lstd(:));
lq = round(length(q)/2);
th = q(lq);
if(th==0)
q = nonzeros(q);
if(~isempty(q))
lq = round(length(q)/2);
th = q(lq);
else
th = 0;
end
end
lstd(lstd<=th) = th;
%lstd(lstd<(8/255)) = 8/255;
% lstd = conv2(lstd,k2,'same');
lstd(lstd(:)==0) = eps;
% shifti = floor(size(k,1)/2)+1;
% shiftj = floor(size(k,2)/2)+1;
% since we do valid convolutions
% dim = dim(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1);
dim = dim - lmn;
dim = dim ./ lstd;
temp(:,:,j) = dim;
% res_I{image}(:,:,j) = single(double(I{image}(:,:,j))-dim);
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
% IMG = conI;
end
I{image} = single(temp);
end
case 'laplacian_cn'
%%%%%
%% CN with a laplacian filter (CVPR 2010 method).
%%%%%
% Run a laplacian over images to get edge features.
h = fspecial('laplacian',0.2);
shifti = floor(size(h,1)/2)+1;
shiftj = floor(size(h,2)/2)+1;
% Loop through the number of images
for image=1:length(I)
fprintf('Contrast Normalizing Image with Laplacian: %10d\r',image);
for j=1:size(I{1},3) % Each color plane needs to be passed with laplacin
I{image}(:,:,j) = conv2(single(I{image}(:,:,j)),single(h),'same');
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(CN_I{image},1)-1,shiftj:shiftj+size(CN_I{image},2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
end
end
case 'box_cn'
%%%%%%
%% CN with a box filter (has bad boundary effects though)
%%%%%%
boxf = ones(5,5)/25;
for image=1:size(I,4)
fprintf('Contrast Normalizing Image with Box Filtering: %10d\r',image);
for j=1:size(I,3)
I(:,:,j,image) = I(:,:,j,image) - imfilter(I(:,:,j,image),boxf,'replicate');
end
CN_I{image} = I(:,:,:,image);
end
case 'PCA_whitening'
%%%%%
%% PCA based whitening
%%%%%
for color=1:size(I,3)
fprintf('\nPCA whitening all images...\n\n');
data = double(reshape(I(:,:,color,:),size(I,1)*size(I,2),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data);
[V D] = eig(cc);
ii = cumsum(fliplr(diag(D)'))/sum(D(:));
nrc = length(find(ii<0.99)); % retain 99% of the variance
V = V(:,end-nrc+1:end);
D = D(end-nrc+1:end,end-nrc+1:end);
PCAtransf = diag(diag(D).^-0.5) * V';
invPCAtransf = V * diag(diag(D).^0.5);
data = single(data * PCAtransf');
% whitendata = single(data * PCAtransf');
I(:,:,color,1:size(PCAtransf,1)) = reshape(data,size(I(:,:,color,1:size(PCAtransf,1))));
end
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_image_whitening'
%%%%%
%% ZCA image based whitening (uses entire images).
%% this is much slower than the below for large images.
%%%%%
fprintf('\nZCA whitening all images...this can take a while...\n\n');
data = double(reshape(I,size(I,1)*size(I,2)*size(I,3),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% whitening happens here.
data = data*ZCAtransform;
% data = data*invZCAtransform*sd+repmat(mn,1,size(data,2));
I = reshape(data,size(I));
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_patch_whitening'
%%%%%
%% ZCA patch based whitening (uses randomly selected patches)
%% this is much faster than the above.
%%%%%
%%%%%%%%%%%%%%%%%%%
% Define the patch size (largest one possible)
%%%%%%%%%%%%%%%%%%%
for patch_size=size(I,1):-1:1
% Has to evenly divide into image.
if(mod(size(I,1),patch_size)==0)
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
% Need more patches from the dataset than size of
% patches (which are times # of colors).
if(size(temp,2)*size(I,4)>size(temp,1)*size(I,3))
break
end
end
end
fprintf('Size of the whitening filter is %d.\n',patch_size);
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Derive whitening transform from random patches of the images.
%%%%%%%%%%%%%%%%%%%
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
data = zeros(patch_size^2,size(temp,2),size(I,3),size(I,4));
clear temp
% Create image patches of 11x11 size.
indices = randperm(size(I,4));
for i=1:size(I,4)
% Use random selection of the images.
ind = indices(i);
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,ind),[patch_size patch_size],'distinct');
end
% Keep only 100,000 patches around for computing the whitening transforms.
if(size(data,2)*i>100000)
break
end
end
fprintf('\nZCA whitening all images based on patches...\n\n');
data = data(:,:,:,1:i);
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data)
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
patch_mn = mean(data,2);
data = data - repmat(patch_mn,[1 size(data,2)]);
patch_sd = std(data(:));
data = data/patch_sd;
size(data)
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% Get middle index (where the filters are in ZCAtransform.
middle = sub2ind([patch_size patch_size],ceil(patch_size/2),ceil(patch_size/2));
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters(:,:,:,color) = reshape(ZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(100+color)
% imshow(filters(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters2(:,:,:,color) = reshape(invZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(200+color)
% imshow(filters2(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Applying ZCA transform to each distinct patch and then forming images
% again.
clear data
for i=1:size(I,4)
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,i),[patch_size patch_size],'distinct');
end
end
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data);
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
data= ZCAtransform*data;
data = reshape(data,patch,colors,num_patches,num_images);
data=permute(data,[1 3 2 4]);
for i=1:size(I,4)
for color=1:size(I,3)
I(:,:,color,i) = col2im(data(:,:,color,i),[patch_size patch_size],[size(I,1) size(I,2)],'distinct');
end
end
%%%%%%%%%%%%%%%%%%%%
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'inv_f_whitening'
%%%%%
%% 1/f whitening of the images
%%%%%
% Number of images.
M=length(I);
REGULARIZATION=0.3;
WHITEN_POWER = 4;
WHITEN_SCALE = 0.4;
EPSILON = 1e-3;
BORDER=0;
for i=1:M
fprintf('Whitening image: %10d\r',i);
temp_im = I{i};
[imx,imy,imc] = size(temp_im);
if(exist('I','var')==0)
I = zeros(imx,imy,imc,M);
end
% Make 1/f filter
[fx fy]=meshgrid(-imy/2:imy/2-1,-imx/2:imx/2-1);
rho=sqrt(fx.*fx+fy.*fy)+REGULARIZATION;
f_0=WHITEN_SCALE*mean([imx,imy]);
filt=rho.*exp(-(rho/f_0).^WHITEN_POWER) + EPSILON;
for c=1:imc
If=fft2(temp_im(:,:,c));
imagew=real(ifft2(If.*fftshift(filt)));
BORDER_VALUE = mean(imagew(:));
if(BORDER~=0)
imagew(1:BORDER,:,:,:)=BORDER_VALUE;
imagew(:,1:BORDER,:,:)=BORDER_VALUE;
imagew(end-BORDER+1:end,:,:,:)=BORDER_VALUE;
imagew(:,end-BORDER+1:end,:,:)=BORDER_VALUE;
end
temp_im(:,:,c) = imagew;
end
CN_I{i} = temp_im;
res_I{i} = I{i}-CN_I{i};
% I(:,:,:,i) = temp_im;
end
case 'sep_mean' % Make each image separately have zero mean (useful for text.
for i=1:length(I)
fprintf('Zero Meaning Image %10d',i);
I{i} = I{i}-mean(I{i}(:));
% res_I{i} = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fprintf('\n');
if ZERO_MEAN
for i=1:length(I)
if strcmp(pars.verbose,'all')
fprintf('Making Image %10d Zero Mean.\r',i);
end
I{i} = I{i} - mean(I{i}(:));
end
end
fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Square the images to the max dimension.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear PADIMG; % Size of I may have changed by this point due to CN.
if(SQUARE_IMAGES)
% Now pad them again to ensure they are square.
% This has to be done after contrast normalizing to avoid strong edges on padded
% regions.
% max_size = max(size(I{1},1),size(I{1},2));
% I = zeros(max_size,max_size,size(I{1},3),length(I),'single');
% resI = zeros(max_size,max_size,size(I{1},3),length(I),'single');
for image=1:length(I)
[xdim ydim planes] = size(I{image});
if(xdim~=ydim) % If not already square.
maxdim = max(xdim,ydim);
PADIMG = zeros(maxdim,maxdim,planes,'single');
% RESIMG = zeros(maxdim,maxdim,planes,'single');
for plane=1:planes
tempimg = padarray(I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
PADIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
% tempimg = padarray(res_I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
% RESIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
end
% Store the padded images into a matrix (as they are all the same
% dimension).
fprintf('Squaring Image: %10d\r',image);
I{image} = single(PADIMG);
% resI(:,:,:,image) = RESIMG;
else
fprintf('Image %10d Already Square\r',image);
I{image} = single(I{image});
% resI(:,:,:,image) = res_I{image};
end
% Save memory.
% I{image} = [];
% res_I{image} = [];
end
end
% Now all of I is assumed to be the same size.
[xdim ydim colors] = size(I{1});
numims = length(I);
% Make sure it is a row vector.
I = reshape(I,[1 numims]);
I = single(cell2mat(I));
I = reshape(I,[xdim ydim numims colors]);
I = permute(I,[1 2 4 3]);
I = double(I);
% I = reshape(I,[xdim ydim colors numims]);
if strcmp(pars.verbose,'all')
fprintf('Not Squaring, just converting all images from cell to matrix...\n')
end
% for image=1:length(I)
% I(:,:,:,image) = single(I{image});
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(pars.verbose,'all')
fprintf('\nAll Images have been loaded and preprocessed.\n\n');
end
|
github
|
adelbibi/Tensor_CSC-master
|
CreateImages.m
|
.m
|
Tensor_CSC-master/Training/image_helpers/CreateImages.m
| 26,810 |
utf_8
|
a1ac1d9be68a54c241bf728f9ecc3c99
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% This takes all images from the input folder, converts them to the desired
% colorspace, removes mean/divides by standard deviations (if desired), and
% constrast normalizes the image (if desired). If the images are of different
% sizes, then it will padd them with zeros (after contrast normalizing) to make
% them square (assumes that they all images have the same maximum dimension).
% Note that some of the whitening/contrast normalization features are not
% fully tested for datasets where the images are of variable size so please
% use with caution in that case. For best result, resize all the images to the
% same dimensions beforehand.
%
% @file
% @author Matthew Zeiler
% @date Mar 11, 2010
%
% @image_file @copybrief CreateImages.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%>
% @copybrief CreateImages.m
%
% @param imgs_path either 1) a path to a folder contain only image files (or other folders
% which will be ignored), 2) a variable with the images as xdim x ydim x
% num_colors x num_images size , 3) a path to a file that contains a variable
% called I that has images as xdim x ydim x num_colors x num_images, or 4)
% a path to a folder containing a single .mat file containing a variable called
% I that has images as xdim x ydim x num_colors x num_images.
% @param CONTRAST_NORMALIZE [optional] binary value indicating whether to contrast
% normalize or whiten the images. Defaults to local contrast normalization ('local_cn').
% Available types are: 'none','local_cn','laplacian_cn','box_cn','PCA_whitening',
% 'ZCA_image_whitening','ZCA_patch_whitening',and 'inv_f_whitening'
% @param ZERO_MEAN [optional] binary value indicating whether to subtract the mean and divides by standard deviation (current
% commented out in the code). Defuaults to 1.
% @param COLOR_TYPE [optional] a string of: 'gray','rgb','ycbcr','hsv'. Defaults to 'gray'.
% @param SQUARE_IMAGES [optional] binary value indicating whether or not to square the
% images. This must be used if using different sized images. Even then the max
% dimensions of each image must be the same. Defaults to 0.
% @param image_selection the subset of images you want to select. This is a cell
% array with 3 dimensions, {A,B,C} -> A:B:C where A and B are numbers and C can
% be a number or 'end' string.
%
% @retval I the images as: xdim x ydim x color_channels x num_images
% @retval mn the mean if ZERO_MEAN was set.
% @retval sd the standard deviation if ZERO_MEAN was set.
% @retval xdim the size of the images in x direction.
% @retval ydim the size of the images in y direction.
% @retval resI the (image-contrast normalized image) if CONTRAST_NORMALIZE is
% set.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I,files,mn_,lmn_,lstd_] = CreateImages(imgs_path,CONTRAST_NORMALIZE,ZERO_MEAN,COLOR_TYPE,SQUARE_IMAGES,image_frames)
global pars
% Defaults
if(nargin<6)
image_frames = {1,1,'end'};
end
if(nargin<5)
SQUARE_IMAGES = 0;
end
if(nargin<4)
COLOR_TYPE = 'gray'
end
if(nargin<3)
ZERO_MEAN = 1
end
if(nargin<2)
CONTRAST_NORMALIZE = 'local_cn'
end
if(isnumeric(CONTRAST_NORMALIZE))
if(CONTRAST_NORMALIZE==1)
CONTRAST_NORMALIZE = 'local_cn';
else
CONTRAST_NORMALIZE = 'none';
end
end
% For backwards compatibility, revert to grayscale.
if(isnumeric(COLOR_TYPE))
if(COLOR_TYPE == 1)
COLOR_TYPE = 'rgb';
else
COLOR_TYPE = 'gray';
end
end
% Select only the frames (images) you want.
if(ischar(image_frames{3}))
last_ind = sprintf('%d:%d:%s',image_frames{1},image_frames{2},image_frames{3});
else
last_ind = sprintf('%d:%d:%d',image_frames{1},image_frames{2},image_frames{3});
end
if strcmp(pars.verbose,'all')
fprintf('Going to select frames: %s',last_ind);
end
% Cell array listing all files and paths.
subdir = dir(imgs_path);
[~,files] = split_folders_files(subdir);
if(check_imgs_path(imgs_path)==0)
error('Path to images is not a valid .mat file or a directory of images.');
end
% Make sure it is a directory and doesn't just have one file that is not an image.
if(ischar(imgs_path) && exist(imgs_path,'dir')>0 && (length(files)>1 ...
|| (length(files)==1 && strcmp(files(1).name(end-3:end),'.mat')==0)))
% Make sure the directory ends in '/'
if(strcmp(imgs_path(end),'/')==0)
imgs_path = [imgs_path '/'];
end
% Counter for the image
image = 1;
if(length(files) == 0)
error('No Images in this directory');
end
% I = cell(1,length(files));
actual_files = 0;
if strcmp(pars.verbose,'all')
fprintf('The length of the I file cell array found in this directory is: %d\n',length(files));
end
% Make sure the selection is not over the number of files.
if(ischar(image_frames{3}))
image_frames{3} = length(files);
else
if(image_frames{3}>length(files))
image_frames{3}=length(files);
end
end
% Loop through the number of files ignoring . and ..
for file=image_frames{1}:image_frames{2}:image_frames{3}
% Makes sure not to count subdirectories
if (files(file).isdir == 0)
% Get the path to the given file.
img_name = strcat(imgs_path,files(file).name);
try
% Load the image file
IMG = single(imread(img_name));
% Count number of images loaded.
actual_files = actual_files+1;
if strcmp(pars.verbose,'all')
fprintf('Loading: %s \n Image: %10d/%10d. Selecting every %5d. Selected: %10d so far.\r',img_name,file,length(files),image_frames{2},actual_files);
end
if(actual_files==1)
I = cell(1,length(files));
end
I{actual_files} = IMG;
% Increment the number of images found so far.
image=image+1;
catch
if strcmp(pars.verbose,'all')
fprintf('Counld not load %s as an image.\n',img_name);
end
end
end
end
I = I(1:actual_files);
% Automatically find the .mat file in the directory that contains all images (no other files or folders can be in teh directory though).
elseif(ischar(imgs_path) && (length(files)==1 && strcmp(files(1).name(end-3:end),'.mat'))) % Only 1 file in folder and it's a .mat
load([imgs_path files(1).name]);
if(exist('original_images','var'))
I = original_images;
clear original_images;
end
clear imgs_path
% Make sure the images are single.
I = single(I);
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
origI = I;
I = cell(1,size(origI,4));
for i=1:size(origI,4)
if strcmp(pars.verbose,'all')
fprintf('Loaded image: %10d from file.\r',i);
end
I{i} = origI(:,:,:,i);
end
actual_files = size(origI,4);
clear origI
elseif(ischar(imgs_path) && exist(imgs_path,'file')~=0) % Path is to a file with all images in it.
if strcmp(pars.verbose,'all')
fprintf('\nLoading %s\n',imgs_path);
end
% May be a .mat file.
if(strcmp(imgs_path(end-3:end),'.mat'))
if strcmp(pars.verbose,'all')
fprintf('Loading single .mat file');
end
load(imgs_path);
else % May be a single image.
fprintf('Reading single image.\n');
I = single(imread(imgs_path));
end
if(exist('original_images','var'))
I = original_images;
clear original_images;
end
clear imgs_path
I = single(I);
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
if strcmp(pars.verbose,'all')
fprintf('Converting from matrix to cell array selected %d images.\n',size(I,4));
end
I = mat2cell(I,size(I,1),size(I,2),size(I,3),ones(size(I,4),1));
I = reshape(I,[size(I,4) 1]);
actual_files = size(I,2);
else % The imgs_path is a variable of images ( can just use it instead of loading).
I = imgs_path;
clear imgs_path
% Select the ones you want.
eval(strcat('I = I(:,:,:,',last_ind,');'));
origI = I;
I = cell(1,size(origI,4));
for i=1:size(origI,4)
fprintf('Loaded image: %10d from file.\r',i);
I{i} = origI(:,:,:,i);
end
actual_files = size(origI,4);
clear origI
end
clear subdir
% fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Convert the colors here.
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% old_I = I;
for i=1:length(I)
switch(COLOR_TYPE)
case 'rgb'
fprintf('Making RGB Image %10d\r',i);
% IMG = rgb_im;
% Normalize the RGB values to [0,1] (do not do this on YCbCr!!!!!).
I{i} = double(I{i})/255.0;
case 'ycbcr'
fprintf('Making YUV Image %10d\r',i);
I{i} = double(rgb2ycbcr(double(I{i})/255.0));
case 'hsv'
fprintf('Making HSV Image %10d\r',i);
I{i} = double(rgb2hsv(double(I{i})/255.0));
case 'gray'
if strcmp(pars.verbose,'all')
fprintf('Making Gray Image %10d\r',i);
end
% Convert to grayscale
if(size(I{i},3)==3)
I{i} = single(rgb2gray(double(I{i})/255.0));
else
if(max(I{i}(:))>1)
I{i} = double(I{i})/255.0;
else
I{i} = double(I{i});
end
end
end
% I{i} = IMG;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Contrast normalize the image?
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CN_I = cell(size(I));
% res_I = cell(size(I));
switch(CONTRAST_NORMALIZE)
case 'none'
fprintf('Not doing any constrast normalization or whitening to the images.\n');
% Make the CN_I result the original images.
% CN_I = I;
% res_I = I;
case 'local_cn'
%%%%%
%% Local Constrast Normalization.
%%%%%
num_colors = size(I{1},3);
% k = fspecial('gaussian',[13 13],1.591*3);
% k = fspecial('gaussian',[5 5],1.591);
k = fspecial('gaussian',[13 13],3*1.591);
k2 = fspecial('gaussian',[13 13],3*1.591);
% k = fspecial('gaussian',[7 7],1.5*1.591);
% k2 = fspecial('gaussian',[7 7],1.5*1.591);
if(all(k(:)==k2(:)))
SAME_KERNELS=1;
else
SAME_KERNELS=0;
end
for image=1:length(I)
if strcmp(pars.verbose,'all')
fprintf('Contrast Normalizing Image with Local CN: %10d\r',image);
end
temp = I{image};
for j=1:num_colors
% if(image==151)
% keyboard
% end
dim = double(temp(:,:,j));
% lmn = conv2(dim,k,'valid');
% lmnsq = conv2(dim.^2,k,'valid');
lmn = rconv2(dim,k);
lmnsq = rconv2(dim.^2,k2);
if(SAME_KERNELS)
lmn2 = lmn;
else
lmn2 = rconv2(dim,k2);
end
lvar = lmnsq - lmn2.^2;
lvar(lvar<0) = 0; % avoid numerical problems
lstd = sqrt(lvar);
q=sort(lstd(:));
lq = round(length(q)/2);
th = q(lq);
if(th==0)
q = nonzeros(q);
if(~isempty(q))
lq = round(length(q)/2);
th = q(lq);
else
th = 0;
end
end
lstd(lstd<=th) = th;
%lstd(lstd<(8/255)) = 8/255;
% lstd = conv2(lstd,k2,'same');
lstd(lstd(:)==0) = eps;
% shifti = floor(size(k,1)/2)+1;
% shiftj = floor(size(k,2)/2)+1;
% since we do valid convolutions
% dim = dim(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1);
dim = dim - lmn;
dim = dim ./ lstd;
temp(:,:,j) = dim;
% res_I{image}(:,:,j) = single(double(I{image}(:,:,j))-dim);
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(lstd,1)-1,shiftj:shiftj+size(lstd,2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
% IMG = conI;
lmndim(:,:,j)=lmn;
lstddim(:,:,j)=lstd;
end
I{image} = single(temp);
lmn_{image}=lmndim;
lstd_{image}=lstddim;
end
case 'laplacian_cn'
%%%%%
%% CN with a laplacian filter (CVPR 2010 method).
%%%%%
% Run a laplacian over images to get edge features.
h = fspecial('laplacian',0.2);
shifti = floor(size(h,1)/2)+1;
shiftj = floor(size(h,2)/2)+1;
% Loop through the number of images
for image=1:length(I)
fprintf('Contrast Normalizing Image with Laplacian: %10d\r',image);
for j=1:size(I{1},3) % Each color plane needs to be passed with laplacin
I{image}(:,:,j) = conv2(single(I{image}(:,:,j)),single(h),'same');
% res_I{image}(:,:,j) = double(I{image}(shifti:shifti+size(CN_I{image},1)-1,shiftj:shiftj+size(CN_I{image},2)-1,j))-double(CN_I{image}(:,:,j)); % Compute the residual image.
end
end
case 'box_cn'
%%%%%%
%% CN with a box filter (has bad boundary effects though)
%%%%%%
boxf = ones(5,5)/25;
for image=1:size(I,4)
fprintf('Contrast Normalizing Image with Box Filtering: %10d\r',image);
for j=1:size(I,3)
I(:,:,j,image) = I(:,:,j,image) - imfilter(I(:,:,j,image),boxf,'replicate');
end
CN_I{image} = I(:,:,:,image);
end
case 'PCA_whitening'
%%%%%
%% PCA based whitening
%%%%%
for color=1:size(I,3)
fprintf('\nPCA whitening all images...\n\n');
data = double(reshape(I(:,:,color,:),size(I,1)*size(I,2),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data);
[V D] = eig(cc);
ii = cumsum(fliplr(diag(D)'))/sum(D(:));
nrc = length(find(ii<0.99)); % retain 99% of the variance
V = V(:,end-nrc+1:end);
D = D(end-nrc+1:end,end-nrc+1:end);
PCAtransf = diag(diag(D).^-0.5) * V';
invPCAtransf = V * diag(diag(D).^0.5);
data = single(data * PCAtransf');
% whitendata = single(data * PCAtransf');
I(:,:,color,1:size(PCAtransf,1)) = reshape(data,size(I(:,:,color,1:size(PCAtransf,1))));
end
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_image_whitening'
%%%%%
%% ZCA image based whitening (uses entire images).
%% this is much slower than the below for large images.
%%%%%
fprintf('\nZCA whitening all images...this can take a while...\n\n');
data = double(reshape(I,size(I,1)*size(I,2)*size(I,3),size(I,4)));
% size(data)
% center the data
% Only take mean if more than one image.
if(ZERO_MEAN==0)
fprintf('Taking zero mean of the dataset anyways.\n')
if(size(data,2)>1)
mn = mean(data,2);
else
mn=mean(data(:));
end
data = data - repmat(mn,1,size(data,2));
sd = std(data(:));
data = data/sd;
end
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% whitening happens here.
data = data*ZCAtransform;
% data = data*invZCAtransform*sd+repmat(mn,1,size(data,2));
I = reshape(data,size(I));
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'ZCA_patch_whitening'
%%%%%
%% ZCA patch based whitening (uses randomly selected patches)
%% this is much faster than the above.
%%%%%
%%%%%%%%%%%%%%%%%%%
% Define the patch size (largest one possible)
%%%%%%%%%%%%%%%%%%%
for patch_size=size(I,1):-1:1
% Has to evenly divide into image.
if(mod(size(I,1),patch_size)==0)
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
% Need more patches from the dataset than size of
% patches (which are times # of colors).
if(size(temp,2)*size(I,4)>size(temp,1)*size(I,3))
break
end
end
end
fprintf('Size of the whitening filter is %d.\n',patch_size);
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Derive whitening transform from random patches of the images.
%%%%%%%%%%%%%%%%%%%
temp = im2col(I(:,:,1,1),[patch_size patch_size],'distinct');
data = zeros(patch_size^2,size(temp,2),size(I,3),size(I,4));
clear temp
% Create image patches of 11x11 size.
indices = randperm(size(I,4));
for i=1:size(I,4)
% Use random selection of the images.
ind = indices(i);
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,ind),[patch_size patch_size],'distinct');
end
% Keep only 100,000 patches around for computing the whitening transforms.
if(size(data,2)*i>100000)
break
end
end
fprintf('\nZCA whitening all images based on patches...\n\n');
data = data(:,:,:,1:i);
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data)
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
patch_mn = mean(data,2);
data = data - repmat(patch_mn,[1 size(data,2)]);
patch_sd = std(data(:));
data = data/patch_sd;
size(data)
cc = cov(data');
[V D] = eig(cc);
indx = find(diag(D) > 0);
ZCAtransform = V(:,indx) * inv(sqrt(D(indx,indx))) * V(:,indx)';
invZCAtransform = V(:,indx) * sqrt(D(indx,indx)) * V(:,indx)';
% Get middle index (where the filters are in ZCAtransform.
middle = sub2ind([patch_size patch_size],ceil(patch_size/2),ceil(patch_size/2));
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters(:,:,:,color) = reshape(ZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(100+color)
% imshow(filters(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Show whitening filters
%%%%%%%%%%%%%%%%%%%
%for color=1:size(I,3)
% filters2(:,:,:,color) = reshape(invZCAtransform((color-1)*patch_size^2+middle,:)',patch_size,patch_size,colors);
% figure(200+color)
% imshow(filters2(:,:,:,color))
%end
%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%
% Applying ZCA transform to each distinct patch and then forming images
% again.
clear data
for i=1:size(I,4)
for color=1:size(I,3)
data(:,:,color,i) = im2col(I(:,:,color,i),[patch_size patch_size],'distinct');
end
end
data=permute(data,[1 3 2 4]);
[patch colors num_patches num_images] = size(data);
data = reshape(data,size(data,1)*size(data,2),size(data,3)*size(data,4));
data= ZCAtransform*data;
data = reshape(data,patch,colors,num_patches,num_images);
data=permute(data,[1 3 2 4]);
for i=1:size(I,4)
for color=1:size(I,3)
I(:,:,color,i) = col2im(data(:,:,color,i),[patch_size patch_size],[size(I,1) size(I,2)],'distinct');
end
end
%%%%%%%%%%%%%%%%%%%%
for image=1:size(I,4)
CN_I{image} = I(:,:,:,image);
end
case 'inv_f_whitening'
%%%%%
%% 1/f whitening of the images
%%%%%
% Number of images.
M=length(I);
REGULARIZATION=0.3;
WHITEN_POWER = 4;
WHITEN_SCALE = 0.4;
EPSILON = 1e-3;
BORDER=0;
for i=1:M
fprintf('Whitening image: %10d\r',i);
temp_im = I{i};
[imx,imy,imc] = size(temp_im);
if(exist('I','var')==0)
I = zeros(imx,imy,imc,M);
end
% Make 1/f filter
[fx fy]=meshgrid(-imy/2:imy/2-1,-imx/2:imx/2-1);
rho=sqrt(fx.*fx+fy.*fy)+REGULARIZATION;
f_0=WHITEN_SCALE*mean([imx,imy]);
filt=rho.*exp(-(rho/f_0).^WHITEN_POWER) + EPSILON;
for c=1:imc
If=fft2(temp_im(:,:,c));
imagew=real(ifft2(If.*fftshift(filt)));
BORDER_VALUE = mean(imagew(:));
if(BORDER~=0)
imagew(1:BORDER,:,:,:)=BORDER_VALUE;
imagew(:,1:BORDER,:,:)=BORDER_VALUE;
imagew(end-BORDER+1:end,:,:,:)=BORDER_VALUE;
imagew(:,end-BORDER+1:end,:,:)=BORDER_VALUE;
end
temp_im(:,:,c) = imagew;
end
CN_I{i} = temp_im;
res_I{i} = I{i}-CN_I{i};
% I(:,:,:,i) = temp_im;
end
case 'sep_mean' % Make each image separately have zero mean (useful for text.
for i=1:length(I)
fprintf('Zero Meaning Image %10d',i);
I{i} = I{i}-mean(I{i}(:));
% res_I{i} = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fprintf('\n');
if ZERO_MEAN
for i=1:length(I)
if strcmp(pars.verbose,'all')
fprintf('Making Image %10d Zero Mean.\r',i);
end
I{i} = I{i} - mean(I{i}(:));
mn_{i}=mean(I{i}(:));
end
end
% fprintf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Square the images to the max dimension.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear PADIMG; % Size of I may have changed by this point due to CN.
if(SQUARE_IMAGES)
% Now pad them again to ensure they are square.
% This has to be done after contrast normalizing to avoid strong edges on padded
% regions.
% max_size = max(size(I{1},1),size(I{1},2));
% I = zeros(max_size,max_size,size(I{1},3),length(I),'single');
% resI = zeros(max_size,max_size,size(I{1},3),length(I),'single');
for image=1:length(I)
[xdim ydim planes] = size(I{image});
if(xdim~=ydim) % If not already square.
maxdim = max(xdim,ydim);
PADIMG = zeros(maxdim,maxdim,planes,'single');
% RESIMG = zeros(maxdim,maxdim,planes,'single');
for plane=1:planes
tempimg = padarray(I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
PADIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
% tempimg = padarray(res_I{image}(:,:,plane),[floor((maxdim-xdim)/2) floor((maxdim-ydim)/2)],'pre');
% RESIMG(:,:,plane) = padarray(tempimg,[ceil((maxdim-xdim)/2) ceil((maxdim-ydim)/2)],'post');
end
% Store the padded images into a matrix (as they are all the same
% dimension).
fprintf('Squaring Image: %10d\r',image);
I{image} = single(PADIMG);
% resI(:,:,:,image) = RESIMG;
else
fprintf('Image %10d Already Square\r',image);
I{image} = single(I{image});
% resI(:,:,:,image) = res_I{image};
end
% Save memory.
% I{image} = [];
% res_I{image} = [];
end
end
% Now all of I is assumed to be the same size.
[xdim ydim colors] = size(I{1});
numims = length(I);
% Make sure it is a row vector.
I = reshape(I,[1 numims]);
I = single(cell2mat(I));
I = reshape(I,[xdim ydim numims colors]);
I = permute(I,[1 2 4 3]);
I = double(I);
% I = reshape(I,[xdim ydim colors numims]);
if strcmp(pars.verbose,'all')
fprintf('Not Squaring, just converting all images from cell to matrix...\n')
end
% for image=1:length(I)
% I(:,:,:,image) = single(I{image});
% end
% end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(pars.verbose,'all')
fprintf('\nAll Images have been loaded and preprocessed.\n\n');
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.