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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex6/ex6/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submit.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex7/ex7/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submit.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submit.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submit.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex8/ex8/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submit.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
submitWithConfiguration.m
|
.m
|
machine-learning-coursera-master/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
jagmoreira/machine-learning-coursera-master
|
savejson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
loadubjson.m
|
.m
|
machine-learning-coursera-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
|
jagmoreira/machine-learning-coursera-master
|
saveubjson.m
|
.m
|
machine-learning-coursera-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
|
NitinJSanket/CMSC828THW1-master
|
gtsamExamples.m
|
.m
|
CMSC828THW1-master/gtsam_toolbox/gtsam_examples/gtsamExamples.m
| 5,664 |
utf_8
|
f2621b78fabdb370c4f63d5e0309b7e9
|
function varargout = gtsamExamples(varargin)
% GTSAMEXAMPLES MATLAB code for gtsamExamples.fig
% GTSAMEXAMPLES, by itself, creates a new GTSAMEXAMPLES or raises the existing
% singleton*.
%
% H = GTSAMEXAMPLES returns the handle to a new GTSAMEXAMPLES or the handle to
% the existing singleton*.
%
% GTSAMEXAMPLES('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GTSAMEXAMPLES.M with the given input arguments.
%
% GTSAMEXAMPLES('Property','Value',...) creates a new GTSAMEXAMPLES or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before gtsamExamples_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to gtsamExamples_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 gtsamExamples
% Last Modified by GUIDE v2.5 03-Sep-2012 13:34:13
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @gtsamExamples_OpeningFcn, ...
'gui_OutputFcn', @gtsamExamples_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 gtsamExamples is made visible.
function gtsamExamples_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 gtsamExamples (see VARARGIN)
% Choose default command line output for gtsamExamples
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
OdometryExample;
% --- Outputs from this function are returned to the command line.
function varargout = gtsamExamples_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;
% --------------------------------------------------------------------
function CloseMenuItem_Callback(hObject, eventdata, handles)
% hObject handle to CloseMenuItem (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],...
['Close ' get(handles.figure1,'Name') '...'],...
'Yes','No','Yes');
if strcmp(selection,'No')
return;
end
delete(handles.figure1)
% --- Executes on button press in Odometry.
function Odometry_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
OdometryExample;
echo off
% --- Executes on button press in Localization.
function Localization_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
LocalizationExample;
echo off
% --- Executes on button press in Pose2SLAM.
function Pose2SLAM_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
Pose2SLAMExample
echo off
% --- Executes on button press in Pose2SLAMCircle.
function Pose2SLAMCircle_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
Pose2SLAMExample_circle
echo off
% --- Executes on button press in Pose2SLAMManhattan.
function Pose2SLAMManhattan_Callback(hObject, eventdata, handles)
axes(handles.axes3);
Pose2SLAMExample_graph
% --- Executes on button press in Pose3SLAM.
function Pose3SLAM_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
Pose3SLAMExample
echo off
% --- Executes on button press in Pose3SLAMSphere.
function Pose3SLAMSphere_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
Pose3SLAMExample_graph
echo off
% --- Executes on button press in PlanarSLAM.
function PlanarSLAM_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
PlanarSLAMExample
echo off
% --- Executes on button press in PlanarSLAMSampling.
function PlanarSLAMSampling_Callback(hObject, eventdata, handles)
axes(handles.axes3);
PlanarSLAMExample_sampling
% --- Executes on button press in PlanarSLAMGraph.
function PlanarSLAMGraph_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
PlanarSLAMExample_graph
echo off
% --- Executes on button press in SFM.
function SFM_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
SFMExample
echo off
% --- Executes on button press in VisualISAM.
function VisualISAM_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
VisualISAMExample
echo off
% --- Executes on button press in StereoVO.
function StereoVO_Callback(hObject, eventdata, handles)
axes(handles.axes3);
echo on
StereoVOExample
echo off
% --- Executes on button press in StereoVOLarge.
function StereoVOLarge_Callback(hObject, eventdata, handles)
axes(handles.axes3);
StereoVOExample_large
|
github
|
NitinJSanket/CMSC828THW1-master
|
VisualISAM_gui.m
|
.m
|
CMSC828THW1-master/gtsam_toolbox/gtsam_examples/VisualISAM_gui.m
| 10,009 |
utf_8
|
ed501f5a7d855d179385d3bb29e65500
|
function varargout = VisualISAM_gui(varargin)
% VisualISAM_gui: runs VisualSLAM iSAM demo in GUI
% Interface is defined by VisualISAM_gui.fig
% You can run this file directly, but won't have access to globals
% By running ViusalISAMDemo, you see all variables in command prompt
% Authors: Duy Nguyen Ta
% Last Modified by GUIDE v2.5 13-Jun-2012 23:15:43
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @VisualISAM_gui_OpeningFcn, ...
'gui_OutputFcn', @VisualISAM_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 VisualISAM_gui is made visible.
function VisualISAM_gui_OpeningFcn(hObject, ~, handles, varargin)
% This function has no output args, see OutputFcn.
% varargin command line arguments to VisualISAM_gui (see VARARGIN)
% Choose default command line output for VisualISAM_gui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = VisualISAM_gui_OutputFcn(hObject, ~, handles)
% varargout cell array for returning output args (see VARARGOUT);
% Get default command line output from handles structure
varargout{1} = handles.output;
%----------------------------------------------------------
% Convenient functions
%----------------------------------------------------------
function showFramei(hObject, handles)
global frame_i
set(handles.frameStatus, 'String', sprintf('Frame: %d',frame_i));
drawnow
guidata(hObject, handles);
function showWaiting(handles, status)
set(handles.waitingStatus,'String', status);
drawnow
guidata(handles.waitingStatus, handles);
function triangle = chooseDataset(handles)
str = cellstr(get(handles.dataset,'String'));
sel = get(handles.dataset,'Value');
switch str{sel}
case 'triangle'
triangle = true;
case 'cube'
triangle = false;
end
function initOptions(handles)
global options
% Data options
options.triangle = chooseDataset(handles);
options.nrCameras = str2num(get(handles.numCamEdit,'String'));
options.showImages = get(handles.showImagesCB,'Value');
% iSAM Options
options.hardConstraint = get(handles.hardConstraintCB,'Value');
options.pointPriors = get(handles.pointPriorsCB,'Value');
options.batchInitialization = get(handles.batchInitCB,'Value');
%options.reorderInterval = str2num(get(handles.reorderIntervalEdit,'String'));
options.alwaysRelinearize = get(handles.alwaysRelinearizeCB,'Value');
% Display Options
options.saveDotFile = get(handles.saveGraphCB,'Value');
options.printStats = get(handles.printStatsCB,'Value');
options.drawInterval = str2num(get(handles.drawInterval,'String'));
options.cameraInterval = str2num(get(handles.cameraIntervalEdit,'String'));
options.drawTruePoses = get(handles.drawTruePosesCB,'Value');
options.saveFigures = get(handles.saveFiguresCB,'Value');
options.saveDotFiles = get(handles.saveGraphsCB,'Value');
%----------------------------------------------------------
% Callback functions for GUI elements
%----------------------------------------------------------
% --- Executes during object creation, after setting all properties.
function dataset_CreateFcn(hObject, ~, handles)
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in dataset.
function dataset_Callback(hObject, ~, handles)
% Hints: contents = cellstr(get(hObject,'String')) returns dataset contents as cell array
% contents{get(hObject,'Value')} returns selected item from dataset
% --- Executes during object creation, after setting all properties.
function numCamEdit_CreateFcn(hObject, ~, handles)
% Hint: edit controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function numCamEdit_Callback(hObject, ~, handles)
% Hints: get(hObject,'String') returns contents of numCamEdit as text
% str2double(get(hObject,'String')) returns contents of numCamEdit as a double
% --- Executes on button press in showImagesCB.
function showImagesCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of showImagesCB
% --- Executes on button press in hardConstraintCB.
function hardConstraintCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of hardConstraintCB
% --- Executes on button press in pointPriorsCB.
function pointPriorsCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of pointPriorsCB
% --- Executes during object creation, after setting all properties.
function batchInitCB_CreateFcn(hObject, eventdata, handles)
set(hObject,'Value',1);
% --- Executes on button press in batchInitCB.
function batchInitCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of batchInitCB
% --- Executes on button press in alwaysRelinearizeCB.
function alwaysRelinearizeCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of alwaysRelinearizeCB
% --- Executes during object creation, after setting all properties.
function reorderIntervalText_CreateFcn(hObject, ~, handles)
% Hint: edit controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function reorderIntervalEdit_CreateFcn(hObject, ~, handles)
% Hint: edit controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes during object creation, after setting all properties.
function drawInterval_CreateFcn(hObject, ~, handles)
% Hint: edit controls usually have a white background on Windows.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function drawInterval_Callback(hObject, ~, handles)
% Hints: get(hObject,'String') returns contents of drawInterval as text
% str2double(get(hObject,'String')) returns contents of drawInterval as a double
function cameraIntervalEdit_Callback(hObject, ~, handles)
% Hints: get(hObject,'String') returns contents of cameraIntervalEdit as text
% str2double(get(hObject,'String')) returns contents of cameraIntervalEdit as a double
% --- Executes during object creation, after setting all properties.
function cameraIntervalEdit_CreateFcn(hObject, ~, handles)
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in saveGraphCB.
function saveGraphCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of saveGraphCB
% --- Executes on button press in printStatsCB.
function printStatsCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of printStatsCB
% --- Executes on button press in drawTruePosesCB.
function drawTruePosesCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of drawTruePosesCB
% --- Executes on button press in saveFiguresCB.
function saveFiguresCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of saveFiguresCB
% --- Executes on button press in saveGraphsCB.
function saveGraphsCB_Callback(hObject, ~, handles)
% Hint: get(hObject,'Value') returns toggle state of saveGraphsCB
% --- Executes on button press in intializeButton.
function intializeButton_Callback(hObject, ~, handles)
global frame_i truth data noiseModels isam result nextPoseIndex options
% initialize global options
initOptions(handles)
% Generate Data
[data,truth] = gtsam.VisualISAMGenerateData(options);
% Initialize and plot
[noiseModels,isam,result,nextPoseIndex] = gtsam.VisualISAMInitialize(data,truth,options);
cla
gtsam.VisualISAMPlot(truth, data, isam, result, options)
frame_i = 2;
showFramei(hObject, handles)
% --- Executes on button press in runButton.
function runButton_Callback(hObject, ~, handles)
global frame_i truth data noiseModels isam result nextPoseIndex options
while (frame_i<size(truth.cameras,2))
frame_i = frame_i+1;
showFramei(hObject, handles)
[isam,result,nextPoseIndex] = gtsam.VisualISAMStep(data,noiseModels,isam,result,truth,nextPoseIndex);
if mod(frame_i,options.drawInterval)==0
showWaiting(handles, 'Computing marginals...');
gtsam.VisualISAMPlot(truth, data, isam, result, options)
showWaiting(handles, '');
end
end
% --- Executes on button press in stepButton.
function stepButton_Callback(hObject, ~, handles)
global frame_i truth data noiseModels isam result nextPoseIndex options
if (frame_i<size(truth.cameras,2))
frame_i = frame_i+1;
showFramei(hObject, handles)
[isam,result,nextPoseIndex] = gtsam.VisualISAMStep(data,noiseModels,isam,result,truth,nextPoseIndex);
showWaiting(handles, 'Computing marginals...');
gtsam.VisualISAMPlot(truth, data, isam, result, options)
showWaiting(handles, '');
end
|
github
|
wanwanbeen/toy_code-master
|
GMM_MCMC.m
|
.m
|
toy_code-master/GMM_MCMC.m
| 4,935 |
utf_8
|
0eba8c5c4c31e3ab80702f37c99e6982
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Gibbs Sampling for Gaussian Mixture Model
% Jie Yang 2015
%
% Note: All parameters named by My_** are
% parameters to be iterated/optimized
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GMM_MCMC()
load('data.mat')
n_obs=size(X,2);
n_dim=size(X,1);
n_iter=500;
X_mean=mean(X,2);
X_cov=cov(X');
c0=0.1;
a=n_dim;
A=X_cov;
B=c0*n_dim*A;
alpha=1;
My_phi=zeros(n_obs,n_obs+1,n_iter+1);
My_lambda=zeros(n_dim,n_dim,n_obs+1,n_iter+1);
My_mu=zeros(n_dim,n_obs+1,n_iter+1);
My_inds=zeros(n_obs,n_iter+1);
My_nK=zeros(n_iter+1,1);
ind_cnt=zeros(6,n_iter+1);
%--------------------------------------
% initialize My_parameters in some way
%--------------------------------------
n_rng=0;
rng(n_rng);
My_lambda(:,:,1,1)=wishrnd(inv(B),a);
My_mu(:,1,1)=mvnrnd(X_mean',inv(c0*My_lambda(:,:,1,1)));
My_inds(:,1)=1; % index of cluster per observation
My_nK(1)=1; % number of cluster
for i_iter=2:n_iter+1
My_mu(:,:,i_iter)=My_mu(:,:,i_iter-1);
My_lambda(:,:,:,i_iter)=My_lambda(:,:,:,i_iter-1);
My_inds(:,i_iter)=My_inds(:,i_iter-1);
for i_obs=1:n_obs
My_nK_temp=max(My_inds(:,i_iter));
for i_K=1:My_nK_temp
if sum(My_inds(setdiff(1:n_obs,i_obs),i_iter)==i_K)
My_phi(i_obs,i_K,i_iter)=mvnpdf(X(:,i_obs)',...
My_mu(:,i_K,i_iter)',...
inv(My_lambda(:,:,i_K,i_iter)))*sum(My_inds(setdiff(1:n_obs,i_obs),i_iter)==i_K)/(alpha+n_obs-1);
end;
end;
i_K=My_nK_temp+1;
%--------------------------------------
% iteration of My_parameters
%--------------------------------------
My_phi(i_obs,i_K,i_iter)=alpha/(alpha+n_obs-1)*(c0/(pi*(1+c0)))^(n_dim/2)/(det(B))^(-a/2)*...
det(B+c0/(1+c0)*(X(:,i_obs)-X_mean)*(X(:,i_obs)-X_mean)')^(-(a+1)/2)*...
exp(sum(gammaln((a+1)/2+(1-(1:n_dim))/2)-gammaln(a/2+(1-(1:n_dim))/2)));
My_phi(i_obs,:,i_iter)=My_phi(i_obs,:,i_iter)/sum(My_phi(i_obs,:,i_iter),2);
My_inds(i_obs,i_iter)=sum(rand(1)>cumsum(My_phi(i_obs,:,i_iter)))+1;
if (My_inds(i_obs,i_iter)==i_K)
s=1;c1=c0+s;a1=a+s;
m1=c0/(c0+s)*X_mean+1/(s+c0)*X(:,i_obs);
B1=B+s/(a*s+1)*(X(:,i_obs)-X_mean)*(X(:,i_obs)-X_mean)';
My_lambda(:,:,i_K,i_iter)=wishrnd(inv(B1),a1);
My_mu(:,i_K,i_iter)=mvnrnd(m1,inv(c1*My_lambda(:,:,i_K,i_iter)));
end;
end;
My_nK(i_iter)=max(My_inds(:,i_iter));
ind_delete=[];
for i_K=1:My_nK(i_iter)
s=sum(My_inds(:,i_iter)==i_K);
if ~s
ind_delete=[ind_delete i_K];
else
c1=c0+s;a1=a+s;
m1=c0/(c0+s)*X_mean+1/(s+c0)*sum(X(:,My_inds(:,i_iter)==i_K),2);
Xmean=mean(X(:,My_inds(:,i_iter)==i_K),2);
B1=B+s/(a*s+1)*(Xmean-X_mean)*(Xmean-X_mean)'+(X(:,My_inds(:,i_iter)==i_K)...
-Xmean*ones(1,s))*(X(:,My_inds(:,i_iter)==i_K)-Xmean*ones(1,s))';
My_lambda(:,:,i_K,i_iter)=wishrnd(inv(B1),a1);
My_mu(:,i_K,i_iter)=mvnrnd(m1,inv(c1*My_lambda(:,:,i_K,i_iter)));
end;
end;
% new cluster inds
if ~isempty(ind_delete)
ind_save=setdiff(1:My_nK(i_iter),ind_delete);
mu_temp=My_mu(:,ind_save,i_iter);
lambda_temp=My_lambda(:,:,ind_save,i_iter);
My_nK(i_iter)=My_nK(i_iter) - length(ind_delete);
My_mu(:,1:My_nK(i_iter),i_iter)=mu_temp;
My_lambda(:,:,1:My_nK(i_iter),i_iter)=lambda_temp;
My_inds_temp=My_inds(:,i_iter);
for k=1:length(ind_save)
My_inds_temp(My_inds_temp == ind_save(k))=k;
end;
My_inds(:,i_iter)=My_inds_temp;
end;
ind_cnt_temp=histc(My_inds(:,i_iter),unique(My_inds(:,i_iter)));
if length(ind_cnt_temp)>6
ind_cnt_temp=ind_cnt_temp(1:6);
end;
ind_cnt(1:length(ind_cnt_temp),i_iter)=ind_cnt_temp;
disp(['iteration time = ' num2str(i_iter)])
end;
ind_cnt=sort(ind_cnt)';
ind_cnt=flip(ind_cnt,2);
%--------------------------------------
% Plot
%--------------------------------------
figure;
subplot(1,3,1);
plot(1:n_iter,ind_cnt(2:end,:))
legend('cluster 1','cluster 2','cluster 3','cluster 4','cluster 5','cluster 6')
xlabel('iteration');
ylabel('number of observations per cluster')
set(gca,'FontSize',12,'FontWeight','b');
subplot(1,3,2);
plot(1:n_iter,My_nK(2:end))
xlim([1 n_iter])
ylim([1 max(My_nK)])
xlabel('iteration');
ylabel('number of clusters')
set(gca,'FontSize',12,'FontWeight','b');
subplot(1,3,3);
lgd=cell(My_nK(n_iter+1),1);
for ii_K = 1:My_nK(n_iter+1)
hold on;
dnX=find(My_inds(:,n_iter+1)==ii_K);
scatter(X(1,dnX),X(2,dnX),'*')
lgd{ii_K}=['Cluster ' num2str(ii_K)];
end;
xlabel('Dimension 1')
ylabel('Dimension 2')
legend(lgd);
set(gca,'FontSize',12,'FontWeight','b');
axis square
|
github
|
wanwanbeen/toy_code-master
|
GMM_EM.m
|
.m
|
toy_code-master/GMM_EM.m
| 3,362 |
utf_8
|
ed8c29426673f51b7824924dc2c86a51
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Expectation Maximization for Gaussian Mixture Model
% Jie Yang 2015
%
% Note: All parameters named by My_** are
% parameters to be iterated/optimized
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GMM_EM()
load('data.mat')
n_obs=size(X,2);
n_dim=size(X,1);
n_iter=100;
K=[2 4 8 10];
X_mean=mean(X,2);
X_cov=cov(X');
n_rng=0;
figure;
for i_K=1:length(K)
My_pi=zeros(K(i_K),n_iter+1);
My_mu=zeros(n_dim,K(i_K),n_iter+1);
My_cov=zeros(n_dim,n_dim,K(i_K),n_iter+1);
My_phi=zeros(n_obs,K(i_K),n_iter+1);
My_n=zeros(K(i_K),n_iter+1);
My_obj_ft=zeros(n_iter+1,1);
%--------------------------------------
% initialize My_parameters in some way
%--------------------------------------
rng(n_rng);
My_pi(:,1)=1/K(i_K)*ones(1,K(i_K));
rand_mean=round(abs(max(max(X)))/2);
My_mu(:,:,1)=X_mean*ones(1,K(i_K))+rand_mean*(rand(n_dim,K(i_K))-0.5);
for ii_K=1:K(i_K)
My_cov(:,:,ii_K,1)=X_cov;
end;
My_obj_ft_temp=zeros(n_obs,1);
for ii_K=1:K(i_K)
My_obj_ft_temp=My_obj_ft_temp + My_pi(ii_K,1)*mvnpdf(X',My_mu(:,ii_K,1)',My_cov(:,:,ii_K,1));
end;
My_obj_ft(1)=sum(log(My_obj_ft_temp));
for i_iter=2:n_iter+1
%--------------------------------------
% E-step
%--------------------------------------
for ii_K=1:K(i_K)
My_phi(:,ii_K,i_iter)=My_pi(ii_K,i_iter-1)*mvnpdf(X',My_mu(:,ii_K,i_iter-1)',My_cov(:,:,ii_K,i_iter-1));
end;
My_phi(:,:,i_iter)=My_phi(:,:,i_iter)./(sum(My_phi(:,:,i_iter),2)*ones(1,K(i_K)));
%--------------------------------------
% M-step
%--------------------------------------
My_n(:,i_iter)=squeeze(sum(My_phi(:,:,i_iter)));
My_pi(:,i_iter) =My_n(:,i_iter)/n_obs;
for ii_K=1:K(i_K)
My_mu(:,ii_K,i_iter)=sum(ones(n_dim,1)*My_phi(:,ii_K,i_iter)'.*X,2)/My_n(ii_K,i_iter);
My_cov(:,:,ii_K,i_iter)=((X-My_mu(:,ii_K,i_iter)*ones(1,n_obs)).*(ones(2,1)...
*sqrt(My_phi(:,ii_K,i_iter))'))*((X'-ones(n_obs,1)*My_mu(:,ii_K,i_iter)')...
.*(sqrt(My_phi(:,ii_K,i_iter))*ones(1,2)))/My_n(ii_K,i_iter);
end;
My_obj_ft_temp=zeros(n_obs,1);
for ii_K=1:K(i_K)
My_obj_ft_temp=My_obj_ft_temp + My_pi(ii_K,i_iter)*mvnpdf(X',My_mu(:,ii_K,i_iter)',My_cov(:,:,ii_K,i_iter));
end;
My_obj_ft(i_iter)=sum(log(My_obj_ft_temp));
end;
%--------------------------------------
% Plot
%--------------------------------------
subplot(2,4,i_K)
plot(1:n_iter,My_obj_ft(2:end))
xlim([1 n_iter]);
ylim([-1500 -1000]);
xlabel('iteration')
ylabel('log likelihood')
title(['K=',num2str(K(i_K))]);
set(gca,'FontSize',12,'FontWeight','b');
subplot(2,4,i_K+4)
[~,My_phi_M] = max(My_phi(:,:,n_iter),[],2);
lgd=cell(K(i_K),1);
for ii_K = 1:K(i_K)
hold on;
scatter(X(1,find(My_phi_M==ii_K)),X(2,find(My_phi_M==ii_K)),'*')
lgd{ii_K}=['Cluster ' num2str(ii_K)];
end;
xlabel('Dimension 1')
ylabel('Dimension 2')
title(['K=',num2str(K(i_K))]);
legend(lgd)
set(gca,'FontSize',12,'FontWeight','b');
axis square
end
|
github
|
wanwanbeen/toy_code-master
|
GMM_VI.m
|
.m
|
toy_code-master/GMM_VI.m
| 8,108 |
utf_8
|
cc496089b2b0c182f36db24702794124
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Variational Inference for Gaussian Mixture Model
% Jie Yang 2015
%
% Note: All parameters named by My_** are
% parameters to be iterated/optimized
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function GMM_VI()
load('data.mat')
n_obs=size(X,2);
n_dim=size(X,1);
n_iter=100;
K=[2 4 10 25];
c=10;
a0=n_dim;
X_mean=mean(X,2);
X_cov=cov(X');
n_rng=2;
figure;
for i_K=1:length(K)
My_phi = zeros(n_obs,K(i_K),n_iter+1);
My_n = zeros(K(i_K),n_iter+1);
My_mu = zeros(n_dim,K(i_K),n_iter+1);
My_covA = zeros(n_dim,n_dim,K(i_K),n_iter+1);
My_alpha = zeros(K(i_K),n_iter+1);
My_a = zeros(K(i_K),n_iter+1);
My_B = zeros(n_dim,n_dim,K(i_K),n_iter+1);
My_t1 = zeros(K(i_K),n_iter+1);
My_t2 = zeros(n_obs,K(i_K),n_iter+1);
My_t3 = zeros(K(i_K),n_iter+1);
My_t4 = zeros(K(i_K),n_iter+1);
P_x=zeros(n_iter+1,1);
P_c=zeros(n_iter+1,1);
P_pi=zeros(n_iter+1,1);
P_lambda=zeros(n_iter+1,1);
P_mu=zeros(n_iter+1,1);
P_pos=zeros(n_iter+1,1);
Q=zeros(n_iter+1,1);
PQ=zeros(n_iter+1,1);
%-------------------------------------
% initialize My_parameters in some way
%-------------------------------------
rng(n_rng);
rand_mean=round(abs(max(max(X)))/2);
My_mu(:,:,1)=X_mean*ones(1,K(i_K))+rand_mean*(rand(n_dim,K(i_K))-0.5);
for ii_K=1:K(i_K)
My_covA(:,:,ii_K,1)=X_cov;
end;
My_alpha(:,1)=ones(K(i_K),1);
My_a(:,1)=a0*ones(K(i_K),1);
for ii_K=1:K(i_K)
My_B(:,:,ii_K,1)=n_dim/10*X_cov;
end;
for i_iter=2:n_iter+1
%-------------------------------------
% iteration of My_parameters
%-------------------------------------
% My_phi
for ii_K=1:K(i_K)
My_t1(ii_K,i_iter)=sum(psi((1-(1:n_dim)+My_a(ii_K,i_iter-1))/2))...
-2*sum(log(diag(chol(My_B(:,:,ii_K,i_iter-1)))));
My_t2(:,ii_K,i_iter)=diag((X-My_mu(:,ii_K,i_iter-1)*ones(1,n_obs))'...
*(My_a(ii_K,i_iter-1)*inv(My_B(:,:,ii_K,i_iter-1)))*(X-My_mu(:,ii_K,i_iter-1)*ones(1,n_obs)));
My_t3(ii_K,i_iter)=trace(My_a(ii_K,i_iter-1)*inv(My_B(:,:,ii_K,i_iter-1))...
*My_covA(:,:,ii_K,i_iter-1));
My_t4(ii_K,i_iter)=psi(My_alpha(ii_K,i_iter-1))-psi(sum(My_alpha(:,i_iter-1)));
My_phi(:,ii_K,i_iter)=exp(0.5*My_t1(ii_K,i_iter)...
-0.5*My_t2(:,ii_K,i_iter)-0.5*My_t3(ii_K,i_iter)+My_t4(ii_K,i_iter));
end;
My_phi(:,:,i_iter)=My_phi(:,:,i_iter)./(sum(My_phi(:,:,i_iter),2)*ones(1,K(i_K)));
% My_n
My_n(:,i_iter)=squeeze(sum(My_phi(:,:,i_iter)));
% My_covA
for ii_K=1:K(i_K)
My_covA(:,:,ii_K,i_iter)=inv(1/c*eye(n_dim)+My_n(ii_K,i_iter)*...
My_a(ii_K,i_iter-1)*inv(My_B(:,:,ii_K,i_iter-1)));
end;
% My_mu
for ii_K=1:K(i_K)
My_mu(:,ii_K,i_iter)=My_covA(:,:,ii_K,i_iter)*(My_a(ii_K,i_iter-1)*...
inv(My_B(:,:,ii_K,i_iter-1))*sum(ones(n_dim,1)*My_phi(:,ii_K,i_iter)'.*X,2));
end;
% My_alpha
My_alpha(:,i_iter)=My_alpha(:,1)+My_n(:,i_iter);
% My_a
My_a(:,i_iter)=My_a(:,1)+My_n(:,i_iter);
% My_B
for ii_K=1:K(i_K)
My_B(:,:,ii_K,i_iter)=((X-My_mu(:,ii_K,i_iter)*ones(1,n_obs)).*(ones(n_dim,1)*...
sqrt(My_phi(:,ii_K,i_iter))'))*((X'-ones(n_obs,1)*My_mu(:,ii_K,i_iter)').*...
(sqrt(My_phi(:,ii_K,i_iter))*ones(1,n_dim)))...
+sum(My_phi(:,ii_K,i_iter))*My_covA(:,:,ii_K,i_iter)+My_B(:,:,ii_K,1);
end;
%-------------------------------------
% objective function (log)
%-------------------------------------
% log P(x|c,mu,lambda)
P_x_temp1=zeros(n_obs,1);
P_x_temp2=zeros(K(i_K),1);
Det_B=zeros(K(i_K),1);
for ii_K=1:K(i_K)
Det_B(ii_K)=2*sum(log(diag(chol(My_B(:,:,ii_K,i_iter)))));
P_x_temp1=P_x_temp1-...
0.5*My_phi(:,ii_K,i_iter).*...
(diag((X'-ones(n_obs,1)*My_mu(:,ii_K,i_iter)')*(My_a(ii_K,i_iter)*...
inv(My_B(:,:,ii_K,i_iter)))*(X-My_mu(:,ii_K,i_iter)*ones(1,n_obs)))+...
trace((My_a(ii_K,i_iter)*inv(My_B(:,:,ii_K,i_iter)))*My_covA(:,:,ii_K,i_iter)));
P_x_temp2 (ii_K)=0.5*sum(My_n(ii_K,i_iter)*(n_dim*(n_dim-1)/4*log(pi)+n_dim*log(2)...
+sum(psi(My_a(ii_K,i_iter)/2+(1-(1:n_dim))/2))-Det_B(ii_K)));
end;
P_x(i_iter)=-n_dim/2*n_obs*log(2*pi)+sum(P_x_temp1)+sum(P_x_temp2);
% log P(c|pi)
P_c_temp=zeros(n_obs,1);
for ii_K=1:K(i_K)
P_c_temp=P_c_temp+My_phi(:,ii_K,i_iter)*...
(psi(My_alpha(ii_K,i_iter))-psi(sum(My_alpha(:,i_iter))));
end;
P_c(i_iter)=sum(P_c_temp);
% log P(pi)
P_pi(i_iter)=gammaln(sum(My_alpha(:,i_iter)))-sum(gammaln(My_alpha(:,i_iter)))+...
sum((My_alpha(:,i_iter)-1).*(psi(My_alpha(:,i_iter))-psi(sum(My_alpha(:,i_iter)))));
% log P(mu)
P_mu_temp=zeros(K(i_K),1);
for ii_K=1:K(i_K)
P_mu_temp(ii_K)=sum(diag(My_covA(:,:,ii_K,i_iter)...
+My_mu(:,ii_K,i_iter)*My_mu(:,ii_K,i_iter)'));
end;
P_mu(i_iter)=-K(i_K)*(log(2*pi)+0.5*log(c))-1/2/c*sum(P_mu_temp);
% log P(lambda)
psi_d=zeros(K(i_K),1);
tr_B=zeros(K(i_K),1);
for ii_K=1:K(i_K)
psi_d(ii_K)=n_dim*(n_dim-1)/4*log(pi)+sum(psi(My_a(ii_K,i_iter)/2+(1-(1:n_dim))/2));
tr_B(ii_K)=sum(trace(n_dim/10*X_cov*My_a(ii_K,i_iter)*inv(My_B(:,:,ii_K,i_iter))));
end;
gamma_d0=n_dim*(n_dim-1)/4*log(pi)+sum(gammaln(a0/2+(1-(1:n_dim))/2));
P_lambda(i_iter)=(a0-n_dim-1)/2*sum(psi_d+n_dim*log(2)-Det_B)-0.5*sum(tr_B)-...
a0/2*(n_dim*log(2)+2*sum(log(diag(chol(n_dim/10*X_cov)))))*K(i_K)-gamma_d0*K(i_K);
% log P_pos
P_pos(i_iter)=P_x(i_iter)+P_c(i_iter)+P_pi(i_iter)+P_mu(i_iter)+P_lambda(i_iter);
% log q
Gamma_d=zeros(K(i_K),1);
for ii_K=1:K(i_K)
Gamma_d(ii_K)=n_dim*(n_dim-1)/4*log(pi)+...
sum(gammaln(My_a(ii_K,i_iter)/2+(1-(1:n_dim))/2));
Q(i_iter)=Q(i_iter)-(n_dim+1)/2*Det_B(ii_K)+n_dim*(n_dim+1)/2*log(2)...
+Gamma_d(ii_K)-(My_a(ii_K,i_iter)-n_dim-1)/2*psi_d(ii_K)+My_a(ii_K,i_iter)*n_dim/2;
end;
Det_A=zeros(K(i_K),1);
for ii_K=1:K(i_K)
Det_A(ii_K)=2*sum(log(diag(chol(My_covA(:,:,ii_K,i_iter)))));
Q(i_iter)=Q(i_iter)+n_dim/2*(1+log(2*pi))+0.5*Det_A(ii_K);
end;
Q(i_iter)=Q(i_iter)+sum(-sum(My_phi(:,:,i_iter).*log(My_phi(:,:,i_iter)),2));
Q(i_iter)=Q(i_iter)-gammaln(sum(My_alpha(:,i_iter)))+sum(gammaln(My_alpha(:,i_iter)))+...
(sum(My_alpha(:,i_iter))-K(i_K))*psi(sum(My_alpha(:,i_iter)))...
-sum((My_alpha(:,i_iter)-1).*psi(My_alpha(:,i_iter)));
% pq
PQ(i_iter)=P_pos(i_iter)+Q(i_iter);
end;
%-------------------------------------
% Plot
%-------------------------------------
subplot(2,4,i_K)
plot(1:n_iter,PQ(2:end))
xlim([1 n_iter]);
ylim([-1500 -1000]);
xlabel('iteration')
ylabel('objective function')
title(['K=',num2str(K(i_K))]);
set(gca,'FontSize',12,'FontWeight','b');
subplot(2,4,i_K+4)
[~,My_phi_M] = max(My_phi(:,:,n_iter),[],2);
lk=1;
for ii_K = 1:K(i_K)
hold on;
if ~isempty(find(My_phi_M==ii_K))
scatter(X(1,find(My_phi_M==ii_K)),X(2,find(My_phi_M==ii_K)),'*')
lgd{lk}=['Cluster ' num2str(lk)];
lk=lk+1;
end
end;
xlabel('Dimension 1')
ylabel('Dimension 2')
title(['K=',num2str(K(i_K))]);
legend(lgd')
set(gca,'FontSize',12,'FontWeight','b');
axis square
end
|
github
|
akhilesh-k/Robotics-Specialization-master
|
QuadPlot.m
|
.m
|
Robotics-Specialization-master/AerialRobotics/GainTuningExercise/QuadPlot.m
| 5,212 |
utf_8
|
9b869b07631faa5214a3a9c6cfae2cac
|
classdef QuadPlot < handle
%QUADPLOT Visualization class for quad
properties (SetAccess = public)
k = 0;
qn; % quad number
time = 0; % time
state; % state
rot; % rotation matrix body to world
color; % color of quad
wingspan; % wingspan
height; % height of quad
motor; % motor position
state_hist; % position history
time_hist; % time history
max_iter; % max iteration
end
properties (SetAccess = private)
h_3d
h_m13; % motor 1 and 3 handle
h_m24; % motor 2 and 4 handle
h_qz; % z axis of quad handle
h_qn; % quad number handle
h_pos_hist; % position history handle
text_dist; % distance of quad number to quad
end
methods
% Constructor
function Q = QuadPlot(qn, state, wingspan, height, color, max_iter, h_3d)
Q.qn = qn;
Q.state = state;
Q.wingspan = wingspan;
Q.color = color;
Q.height = height;
Q.rot = QuatToRot(Q.state(7:10));
Q.motor = quad_pos(Q.state(1:3), Q.rot, Q.wingspan, Q.height);
Q.text_dist = Q.wingspan / 3;
Q.max_iter = max_iter;
Q.state_hist = zeros(6, max_iter);
Q.time_hist = zeros(1, max_iter);
% Initialize plot handle
if nargin < 7, h_3d = gca; end
Q.h_3d = h_3d;
hold(Q.h_3d, 'on')
Q.h_pos_hist = plot3(Q.h_3d, Q.state(1), Q.state(2), Q.state(3), 'r.');
Q.h_m13 = plot3(Q.h_3d, ...
Q.motor(1,[1 3]), ...
Q.motor(2,[1 3]), ...
Q.motor(3,[1 3]), ...
'-ko', 'MarkerFaceColor', Q.color, 'MarkerSize', 5);
Q.h_m24 = plot3(Q.h_3d, ...
Q.motor(1,[2 4]), ...
Q.motor(2,[2 4]), ...
Q.motor(3,[2 4]), ...
'-ko', 'MarkerFaceColor', Q.color, 'MarkerSize', 5);
Q.h_qz = plot3(Q.h_3d, ...
Q.motor(1,[5 6]), ...
Q.motor(2,[5 6]), ...
Q.motor(3,[5 6]), ...
'Color', Q.color, 'LineWidth', 2);
Q.h_qn = text(...
Q.motor(1,5) + Q.text_dist, ...
Q.motor(2,5) + Q.text_dist, ...
Q.motor(3,5) + Q.text_dist, num2str(qn));
hold(Q.h_3d, 'off')
end
% Update quad state
function UpdateQuadState(Q, state, time)
Q.state = state;
Q.time = time;
Q.rot = QuatToRot(state(7:10))'; % Q.rot needs to be body-to-world
end
% Update quad history
function UpdateQuadHist(Q)
Q.k = Q.k + 1;
Q.time_hist(Q.k) = Q.time;
Q.state_hist(:,Q.k) = Q.state(1:6);
end
% Update motor position
function UpdateMotorPos(Q)
Q.motor = quad_pos(Q.state(1:3), Q.rot, Q.wingspan, Q.height);
end
% Truncate history
function TruncateHist(Q)
Q.time_hist = Q.time_hist(1:Q.k);
Q.state_hist = Q.state_hist(:, 1:Q.k);
end
% Update quad plot
function UpdateQuadPlot(Q, state, time)
Q.UpdateQuadState(state, time);
Q.UpdateQuadHist();
Q.UpdateMotorPos();
set(Q.h_m13, ...
'XData', Q.motor(1,[1 3]), ...
'YData', Q.motor(2,[1 3]), ...
'ZData', Q.motor(3,[1 3]));
set(Q.h_m24, ...
'XData', Q.motor(1,[2 4]), ...
'YData', Q.motor(2,[2 4]), ...
'ZData', Q.motor(3,[2 4]));
set(Q.h_qz, ...
'XData', Q.motor(1,[5 6]), ...
'YData', Q.motor(2,[5 6]), ...
'ZData', Q.motor(3,[5 6]))
set(Q.h_qn, 'Position', ...
[Q.motor(1,5) + Q.text_dist, ...
Q.motor(2,5) + Q.text_dist, ...
Q.motor(3,5) + Q.text_dist]);
set(Q.h_pos_hist, ...
'XData', Q.state_hist(1,1:Q.k), ...
'YData', Q.state_hist(2,1:Q.k), ...
'ZData', Q.state_hist(3,1:Q.k));
drawnow;
end
end
end
function [ quad ] = quad_pos( pos, rot, L, H )
%QUAD_POS Calculates coordinates of quadrotor's position in world frame
% pos 3x1 position vector [x; y; z];
% rot 3x3 body-to-world rotation matrix
% L 1x1 length of the quad
if nargin < 4; H = 0.05; end
wHb = [rot pos(:); 0 0 0 1]; % homogeneous transformation from body to world
quadBodyFrame = [L 0 0 1; 0 L 0 1; -L 0 0 1; 0 -L 0 1; 0 0 0 1; 0 0 H 1]';
quadWorldFrame = wHb * quadBodyFrame;
quad = quadWorldFrame(1:3, :);
end
function R = QuatToRot(q)
%QuatToRot Converts a Quaternion to Rotation matrix
% written by Daniel Mellinger
% normalize q
q = q./sqrt(sum(q.^2));
qahat(1,2) = -q(4);
qahat(1,3) = q(3);
qahat(2,3) = -q(2);
qahat(2,1) = q(4);
qahat(3,1) = -q(3);
qahat(3,2) = q(2);
R = eye(3) + 2*qahat*qahat + 2*q(1)*qahat;
end
|
github
|
akhilesh-k/Robotics-Specialization-master
|
QuadPlot.m
|
.m
|
Robotics-Specialization-master/AerialRobotics/GainTuningQuiz/QuadPlot.m
| 5,220 |
utf_8
|
1f4b7d11af220cf6f1d5e395f4a180f9
|
classdef QuadPlot < handle
%QUADPLOT Visualization class for quad
properties (SetAccess = public)
k = 0;
qn; % quad number
time = 0; % time
state; % state
rot; % rotation matrix body to world
color; % color of quad
wingspan; % wingspan
height; % height of quad
motor; % motor position
state_hist; % position history
time_hist; % time history
max_iter; % max iteration
end
properties (SetAccess = private)
h_3d
h_m13; % motor 1 and 3 handle
h_m24; % motor 2 and 4 handle
h_qz; % z axis of quad handle
h_qn; % quad number handle
h_pos_hist; % position history handle
text_dist; % distance of quad number to quad
end
methods
% Constructor
function Q = QuadPlot(qn, state, wingspan, height, color, max_iter, h_3d)
Q.qn = qn;
Q.state = state;
Q.wingspan = wingspan;
Q.color = color;
Q.height = height;
Q.rot = QuatToRot(Q.state(7:10));
Q.motor = quad_pos(Q.state(1:3), Q.rot, Q.wingspan, Q.height);
Q.text_dist = Q.wingspan / 3;
Q.max_iter = max_iter;
Q.state_hist = zeros(6, max_iter);
Q.time_hist = zeros(1, max_iter);
% Initialize plot handle
if nargin < 7, h_3d = gca; end
Q.h_3d = h_3d;
hold(Q.h_3d, 'on')
Q.h_pos_hist = plot3(Q.h_3d, Q.state(1), Q.state(2), Q.state(3), 'r.');
Q.h_m13 = plot3(Q.h_3d, ...
Q.motor(1,[1 3]), ...
Q.motor(2,[1 3]), ...
Q.motor(3,[1 3]), ...
'-ko', 'MarkerFaceColor', Q.color, 'MarkerSize', 5);
Q.h_m24 = plot3(Q.h_3d, ...
Q.motor(1,[2 4]), ...
Q.motor(2,[2 4]), ...
Q.motor(3,[2 4]), ...
'-ko', 'MarkerFaceColor', Q.color, 'MarkerSize', 5);
Q.h_qz = plot3(Q.h_3d, ...
Q.motor(1,[5 6]), ...
Q.motor(2,[5 6]), ...
Q.motor(3,[5 6]), ...
'Color', Q.color, 'LineWidth', 2);
% Q.h_qn = text(...
% Q.motor(1,5) + Q.text_dist, ...
% Q.motor(2,5) + Q.text_dist, ...
% Q.motor(3,5) + Q.text_dist, num2str(qn));
hold(Q.h_3d, 'off')
end
% Update quad state
function UpdateQuadState(Q, state, time)
Q.state = state;
Q.time = time;
Q.rot = QuatToRot(state(7:10))'; % Q.rot needs to be body-to-world
end
% Update quad history
function UpdateQuadHist(Q)
Q.k = Q.k + 1;
Q.time_hist(Q.k) = Q.time;
Q.state_hist(:,Q.k) = Q.state(1:6);
end
% Update motor position
function UpdateMotorPos(Q)
Q.motor = quad_pos(Q.state(1:3), Q.rot, Q.wingspan, Q.height);
end
% Truncate history
function TruncateHist(Q)
Q.time_hist = Q.time_hist(1:Q.k);
Q.state_hist = Q.state_hist(:, 1:Q.k);
end
% Update quad plot
function UpdateQuadPlot(Q, state, time)
Q.UpdateQuadState(state, time);
Q.UpdateQuadHist();
Q.UpdateMotorPos();
set(Q.h_m13, ...
'XData', Q.motor(1,[1 3]), ...
'YData', Q.motor(2,[1 3]), ...
'ZData', Q.motor(3,[1 3]));
set(Q.h_m24, ...
'XData', Q.motor(1,[2 4]), ...
'YData', Q.motor(2,[2 4]), ...
'ZData', Q.motor(3,[2 4]));
set(Q.h_qz, ...
'XData', Q.motor(1,[5 6]), ...
'YData', Q.motor(2,[5 6]), ...
'ZData', Q.motor(3,[5 6]))
set(Q.h_qn, 'Position', ...
[Q.motor(1,5) + Q.text_dist, ...
Q.motor(2,5) + Q.text_dist, ...
Q.motor(3,5) + Q.text_dist]);
set(Q.h_pos_hist, ...
'XData', Q.state_hist(1,1:Q.k), ...
'YData', Q.state_hist(2,1:Q.k), ...
'ZData', Q.state_hist(3,1:Q.k));
drawnow;
end
end
end
function [ quad ] = quad_pos( pos, rot, L, H )
%QUAD_POS Calculates coordinates of quadrotor's position in world frame
% pos 3x1 position vector [x; y; z];
% rot 3x3 body-to-world rotation matrix
% L 1x1 length of the quad
if nargin < 4; H = 0.05; end
wHb = [rot pos(:); 0 0 0 1]; % homogeneous transformation from body to world
quadBodyFrame = [L 0 0 1; 0 L 0 1; -L 0 0 1; 0 -L 0 1; 0 0 0 1; 0 0 H 1]';
quadWorldFrame = wHb * quadBodyFrame;
quad = quadWorldFrame(1:3, :);
end
function R = QuatToRot(q)
%QuatToRot Converts a Quaternion to Rotation matrix
% written by Daniel Mellinger
% normalize q
q = q./sqrt(sum(q.^2));
qahat(1,2) = -q(4);
qahat(1,3) = q(3);
qahat(2,3) = -q(2);
qahat(2,1) = q(4);
qahat(3,1) = -q(3);
qahat(3,2) = q(2);
R = eye(3) + 2*qahat*qahat + 2*q(1)*qahat;
end
|
github
|
xkunwu/Conformal-master
|
subaxis.m
|
.m
|
Conformal-master/+Utility/subaxis.m
| 7,846 |
utf_8
|
7bede64f6313fa3bb699728d149cda90
|
function h=subaxis(varargin)
%SUBAXIS Create axes in tiled positions. (just like subplot)
% Usage:
% h=subaxis(rows,cols,cellno[,settings])
% h=subaxis(rows,cols,cellx,celly[,settings])
% h=subaxis(rows,cols,cellx,celly,spanx,spany[,settings])
%
% SETTINGS: Spacing,SpacingHoriz,SpacingVert
% Padding,PaddingRight,PaddingLeft,PaddingTop,PaddingBottom
% Margin,MarginRight,MarginLeft,MarginTop,MarginBottom
% Holdaxis
%
% all units are relative (e.g from 0 to 1)
%
% Abbreviations of parameters can be used.. (Eg MR instead of MarginRight)
% (holdaxis means that it wont delete any axes below.)
%
%
% Example:
%
% >> subaxis(2,1,1,'SpacingVert',0,'MR',0);
% >> imagesc(magic(3))
% >> subaxis(2,'p',.02);
% >> imagesc(magic(4))
%
% 2001 / Aslak Grinsted (Feel free to modify this code.)
f=gcf;
Args=[];
UserDataArgsOK=0;
Args=get(f,'UserData');
if isstruct(Args)
UserDataArgsOK=isfield(Args,'SpacingHorizontal')&isfield(Args,'Holdaxis')&isfield(Args,'rows')&isfield(Args,'cols');
end
OKToStoreArgs=isempty(Args)|UserDataArgsOK;
if isempty(Args)&(~UserDataArgsOK)
Args=struct('Holdaxis',0, ...
'SpacingVertical',0.05,'SpacingHorizontal',0.05, ...
'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ...
'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ...
'rows',[],'cols',[]);
end
Args=parseArgs(varargin,Args,{'Holdaxis'},{'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}});
if (length(Args.NumericArguments)>1)
Args.rows=Args.NumericArguments{1};
Args.cols=Args.NumericArguments{2};
%remove these 2 numerical arguments
Args.NumericArguments={Args.NumericArguments{3:end}};
end
if OKToStoreArgs
set(f,'UserData',Args);
end
switch length(Args.NumericArguments)
case 0
return % no arguments but rows/cols....
case 1
x1=mod((Args.NumericArguments{1}-1),Args.cols)+1; x2=x1;
y1=floor((Args.NumericArguments{1}-1)/Args.cols)+1; y2=y1;
case 2
x1=Args.NumericArguments{1};x2=x1;
y1=Args.NumericArguments{2};y2=y1;
case 4
x1=Args.NumericArguments{1};x2=x1+Args.NumericArguments{3}-1;
y1=Args.NumericArguments{2};y2=y1+Args.NumericArguments{4}-1;
otherwise
error('subaxis argument error')
end
cellwidth=((1-Args.MarginLeft-Args.MarginRight)-(Args.cols-1)*Args.SpacingHorizontal)/Args.cols;
cellheight=((1-Args.MarginTop-Args.MarginBottom)-(Args.rows-1)*Args.SpacingVertical)/Args.rows;
xpos1=Args.MarginLeft+Args.PaddingLeft+cellwidth*(x1-1)+Args.SpacingHorizontal*(x1-1);
xpos2=Args.MarginLeft-Args.PaddingRight+cellwidth*x2+Args.SpacingHorizontal*(x2-1);
ypos1=Args.MarginTop+Args.PaddingTop+cellheight*(y1-1)+Args.SpacingVertical*(y1-1);
ypos2=Args.MarginTop-Args.PaddingBottom+cellheight*y2+Args.SpacingVertical*(y2-1);
if Args.Holdaxis
h=axes('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]);
else
h=subplot('position',[xpos1 1-ypos2 xpos2-xpos1 ypos2-ypos1]);
end
set(h,'box','on');
%h=axes('position',[x1 1-y2 x2-x1 y2-y1]);
set(h,'units',get(gcf,'defaultaxesunits'));
set(h,'tag','subaxis');
if (nargout==0) clear h; end;
end
function ArgStruct=parseArgs(args,ArgStruct,varargin)
% Helper function for parsing varargin.
%
%
% ArgStruct=parseArgs(varargin,ArgStruct[,FlagtypeParams[,Aliases]])
%
% * ArgStruct is the structure full of named arguments with default values.
% * Flagtype params is params that don't require a value. (the value will be set to 1 if it is present)
% * Aliases can be used to map one argument-name to several argstruct fields
%
%
% example usage:
% --------------
% function parseargtest(varargin)
%
% %define the acceptable named arguments and assign default values
% Args=struct('Holdaxis',0, ...
% 'SpacingVertical',0.05,'SpacingHorizontal',0.05, ...
% 'PaddingLeft',0,'PaddingRight',0,'PaddingTop',0,'PaddingBottom',0, ...
% 'MarginLeft',.1,'MarginRight',.1,'MarginTop',.1,'MarginBottom',.1, ...
% 'rows',[],'cols',[]);
%
% %The capital letters define abrreviations.
% % Eg. parseargtest('spacingvertical',0) is equivalent to parseargtest('sv',0)
%
% Args=parseArgs(varargin,Args, ... % fill the arg-struct with values entered by the user
% {'Holdaxis'}, ... %this argument has no value (flag-type)
% {'Spacing' {'sh','sv'}; 'Padding' {'pl','pr','pt','pb'}; 'Margin' {'ml','mr','mt','mb'}});
%
% disp(Args)
%
%
%
%
% % Aslak Grinsted 2003
Aliases={};
FlagTypeParams='';
if (length(varargin)>0)
FlagTypeParams=strvcat(varargin{1});
if length(varargin)>1
Aliases=varargin{2};
end
end
%---------------Get "numeric" arguments
NumArgCount=1;
while (NumArgCount<=size(args,2))&(~ischar(args{NumArgCount}))
NumArgCount=NumArgCount+1;
end
NumArgCount=NumArgCount-1;
if (NumArgCount>0)
ArgStruct.NumericArguments={args{1:NumArgCount}};
else
ArgStruct.NumericArguments={};
end
%--------------Make an accepted fieldname matrix (case insensitive)
Fnames=fieldnames(ArgStruct);
for i=1:length(Fnames)
name=lower(Fnames{i,1});
Fnames{i,2}=name; %col2=lower
AbbrevIdx=find(Fnames{i,1}~=name);
Fnames{i,3}=[name(AbbrevIdx) ' ']; %col3=abreviation letters (those that are uppercase in the ArgStruct) e.g. SpacingHoriz->sh
%the space prevents strvcat from removing empty lines
Fnames{i,4}=isempty(strmatch(Fnames{i,2},FlagTypeParams)); %Does this parameter have a value? (e.g. not flagtype)
end
FnamesFull=strvcat(Fnames{:,2});
FnamesAbbr=strvcat(Fnames{:,3});
if length(Aliases)>0
for i=1:length(Aliases)
name=lower(Aliases{i,1});
FieldIdx=strmatch(name,FnamesAbbr,'exact'); %try abbreviations (must be exact)
if isempty(FieldIdx)
FieldIdx=strmatch(name,FnamesFull); %&??????? exact or not?
end
Aliases{i,2}=FieldIdx;
AbbrevIdx=find(Aliases{i,1}~=name);
Aliases{i,3}=[name(AbbrevIdx) ' ']; %the space prevents strvcat from removing empty lines
Aliases{i,1}=name; %dont need the name in uppercase anymore for aliases
end
%Append aliases to the end of FnamesFull and FnamesAbbr
FnamesFull=strvcat(FnamesFull,strvcat(Aliases{:,1}));
FnamesAbbr=strvcat(FnamesAbbr,strvcat(Aliases{:,3}));
end
%--------------get parameters--------------------
l=NumArgCount+1;
while (l<=length(args))
a=args{l};
if ischar(a)
paramHasValue=1; % assume that the parameter has is of type 'param',value
a=lower(a);
FieldIdx=strmatch(a,FnamesAbbr,'exact'); %try abbreviations (must be exact)
if isempty(FieldIdx)
FieldIdx=strmatch(a,FnamesFull);
end
if (length(FieldIdx)>1) %shortest fieldname should win
[mx,mxi]=max(sum(FnamesFull(FieldIdx,:)==' ',2));
FieldIdx=FieldIdx(mxi);
end
if FieldIdx>length(Fnames) %then it's an alias type.
FieldIdx=Aliases{FieldIdx-length(Fnames),2};
end
if isempty(FieldIdx)
error(['Unknown named parameter: ' a])
end
for curField=FieldIdx' %if it is an alias it could be more than one.
if (Fnames{curField,4})
val=args{l+1};
else
val=1; %parameter is of flag type and is set (1=true)....
end
ArgStruct.(Fnames{curField,1})=val;
end
l=l+1+Fnames{FieldIdx(1),4}; %if a wildcard matches more than one
else
error(['Expected a named parameter: ' num2str(a)])
end
end
end
|
github
|
xkunwu/Conformal-master
|
layout_vertices_from_la.m
|
.m
|
Conformal-master/+ConvexAngleSum/layout_vertices_from_la.m
| 4,508 |
utf_8
|
04dbb7176ee11ef2b6919f55bbc5c409
|
function [positions, seedi] = layout_vertices_from_la(obj)
num_vert = obj.vertData.num_entry;
i_v_star = obj.meshTri.i_v_star;
ledge = obj.edgeData.length;
alpha = obj.halfData.alpha;
positions = zeros(3, num_vert);
markv = false(1, num_vert);
seedi = seed_vertex(obj);
s0vec = zeros(3, 1);
markv(seedi) = true;
layout_queue();
function layout_queue()
cpos = 1;
epos = 1;
lqueue = zeros(1, num_vert);
lqueue(cpos) = seedi;
while cpos <= num_vert
nvert = layout_span(lqueue(cpos));
ndiff = setdiff(nvert, lqueue(1 : cpos));
lqueue(epos+1 : epos+numel(ndiff)) = ndiff;
cpos = cpos + 1;
epos = epos + numel(ndiff);
end
debug_draw(lqueue);
end
function vert = layout_span(cen)
vert = i_v_star(cen).vert;
% boundary vertex must have been reached
if obj.meshTri.is_boundary_vert(cen), return; end
nn = numel(vert);
n0 = 0; n1 = 0;
for v = 1 : nn % find the 1st vertex already been layout
if markv(vert(v))
if n0 == 0
n0 = v;
else
n1 = v;
break;
end
end
end
if n0 == 0 % no vertices are layout
layout_seed(cen);
return;
end
if n1 == 0
error('isolated vertex');
end
nl = ledge(i_v_star(cen).edge);
na = alpha(i_v_star(cen).alpha);
% if numel(na) < numel(nl) % add a complementary to make it circular traversable
% na = horzcat(na, 2 * pi - sum(na));
% end
n0vec = positions(:, vert(n0)) - positions(:, cen);
n1vec = positions(:, vert(n1)) - positions(:, cen);
cvec = positions(:, cen) - positions(:, seedi);
dir = sign(dot(s0vec, n0vec) * dot(n0vec, n1vec));
acs = acos(dot(s0vec, n0vec) / norm(s0vec) / norm(n0vec));
acs = acs + dir * na(n0);
nc = mod(n0, nn) + 1;
while nc ~= n0
vid = vert(nc);
pos = zeros(3, 1);
pos(1) = nl(nc) * cos(acs) + cvec(1);
pos(2) = nl(nc) * sin(acs) + cvec(2);
if ~markv(vid)
positions(:, vid) = pos;
markv(vid) = true;
else
if 1e-2 < norm(positions(:, vid) - pos)
disp(horzcat(positions(:, vid), pos));
end
end
acs = acs + dir * na(nc);
nc = mod(nc, nn) + 1;
end
end
function vert = layout_seed(cen)
vert = i_v_star(cen).vert;
nn = numel(vert);
nl = ledge(i_v_star(cen).edge);
na = alpha(i_v_star(cen).alpha);
acs = 0;
for v = 1 : nn
vid = vert(v);
positions(1, vid) = nl(v) * cos(acs);
positions(2, vid) = nl(v) * sin(acs);
markv(vid) = true;
acs = acs + na(v);
end
s0vec = positions(:, vert(1)) - positions(:, cen);
end
function debug_draw(lqueue)
scrsz = get(0, 'ScreenSize');
scrsz = [50 50 scrsz(3)-100 scrsz(4)-150];
plot_row = floor(scrsz(4) / 300);
plot_col = floor(scrsz(3) / 300);
plot_num = min(plot_row * plot_col, num_vert);
figure('Position',scrsz);
set(gcf, 'Color', 'w');
for spi = 1 : plot_num
draw_star(lqueue(spi), spi);
end
function draw_star(cen, spi)
if spi > 16, return; end;
vert = i_v_star(cen).vert;
nn = numel(vert);
clrn = cool(nn);
Utility.subaxis(plot_row, plot_col, spi, 'Spacing',0, 'Margin',0.05);
plot(positions(1, :), positions(2, :), 'k*');
for v = 1 : nn
line(positions(1, [cen, vert(v)]), positions(2, [cen, vert(v)]), 'color',clrn(v, :));
end
hold on;
inner_index = find(~obj.meshTri.boundary_verts());
plot(positions(1, inner_index), positions(2, inner_index), 'ro');
lm = max(max(abs(positions))) * 1.1;
xlim([-lm lm]);
ylim([-lm lm]);
end
end
end
function sid = seed_vertex(obj)
asum = obj.vertData.angle_sum;
[~, sid] = min(abs(asum - 2 * pi));
end
|
github
|
xkunwu/Conformal-master
|
layout_voronoi.m
|
.m
|
Conformal-master/+ConvexAngleSum/layout_voronoi.m
| 2,938 |
utf_8
|
7b1727a2c8b8baeb4e935dbefa37a835
|
function [positions] = layout_voronoi(obj)
i_v_star = obj.meshTri.i_v_star;
i_e2h = obj.meshTri.i_e2h;
ledge = obj.edgeData.length;
alpha = obj.halfData.alpha;
faces = obj.meshTri.faces;
num_vert = obj.vertData.num_entry;
face_vert = obj.meshTri.face_vert;
face_link = obj.meshTri.face_link;
num_face = size(face_link, 1);
positions = zeros(3, num_vert);
markv = false(1, num_vert);
markf = false(1, num_face);
% seed a starting point, and fix its first neighbor
[seedv0] = seed_vertex(obj);
seedv1 = i_v_star(seedv0).vert(1);
positions(2, seedv1) = ledge(i_v_star(seedv0).edge(1));
markv(seedv0) = true;
markv(seedv1) = true;
% seed a starting face
[seedf1] = seed_face(face_vert, seedv0, seedv1);
layout_queue();
function layout_queue()
cpos = 1;
epos = 1;
fqueue = zeros(1, num_face);
fqueue(cpos) = seedf1;
vqueue = zeros(1, num_face);
vqueue(cpos) = 0;
while cpos <= num_face
nface = layout_face(fqueue(cpos), vqueue(cpos));
nface = nface(nface ~= 0);
ndiff = setdiff(nface, fqueue(1 : epos));
fqueue(epos+1 : epos+numel(ndiff)) = ndiff;
markf(fqueue(cpos)) = true;
cpos = cpos + 1;
epos = epos + numel(ndiff);
end
end
function nface = layout_face(fid, vid)
nface = face_link(fid, :);
if markf(fid), return; end;
fv = face_vert(fid, :);
mfv = markv(fv);
% all covered already, or one left
if sum(mfv) ~= 2, return; end
v3 = fv(~mfv);
halfs = faces(fid).halfs;
a1 = 0; a2 = 0;
v1 = 0; v2 = 0;
for h = 1 : 3
if halfs(h).source.index ~= v3, continue; end
a1 = halfs(h).index;
a2 = halfs(mod(mod(h, 3) + 1, 3) + 1).index;
v1 = halfs(mod(h, 3) + 1).target.index;
v2 = halfs(h).target.index;
break;
end
l13 = ledge(i_e2h(a2));
vec12 = positions(1:2, v2) - positions(1:2, v1);
% determine direction: x12 +/- 213 = x12 -/+ 21o
dir = 1;
if vid ~= 0
vec1o = positions(1:2, vid) - positions(1:2, v1);
dir = - sign(dot(cross([1, 0], vec12), cross(vec12, vec1o)));
end
a1r = acos(vec12(1) / norm(vec12));
if vec12(2) < 0, a1r = 2 * pi - a1r; end
a1r = a1r + dir * alpha(a1);
positions(1, v3) = l13 * cos(a1r) + positions(1, v1);
positions(2, v3) = l13 * sin(a1r) + positions(2, v1);
markv(v3) = true;
end
end
function [sv0] = seed_vertex(obj)
asum = obj.vertData.angle_sum;
[~, sv0] = min(abs(asum - 2 * pi));
end
function [sf0] = seed_face(face_vert, sv0, sv1)
fv = (face_vert == sv0) | (face_vert == sv1);
s = find(sum(fv, 2) == 2);
% must be at least one
sf0 = s(1);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_nnloss_regression.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo5_analysis_MShift_gradient/vl_nnloss_regression.m
| 12,261 |
utf_8
|
06b83e6c343531803ed5696beb89388b
|
function y = vl_nnloss_regression(x,c,dzdy,varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logisticlog`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
%
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
hasIgnoreLabel = any(c(:) == 0);
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
% disp(labelSize);
% disp(inputSize);
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge', 'regressionloss'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights)
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
else
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'regressionloss'
t = (x(:)-c(:));
t = t.^2;
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case 'regressionloss'
%t = x(:)-c(:);
%t = t.^2;
y = dzdy.* (2*(x-c)) ;
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
ci = unique(ci);
y(ci) = y(ci) - 1 ; % CUDA execution problem -- not unique values in large input
% y = gather(y);
% y(ci) = y(ci) - 1;
% y = gpuArray(y);
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
linspecer.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo5_analysis_MShift_gradient/linspecer.m
| 8,087 |
utf_8
|
b7cd4dab49656ba92d0e006cc5a912e9
|
% function lineStyles = linspecer(N)
% This function creates an Nx3 array of N [R B G] colors
% These can be used to plot lots of lines with distinguishable and nice
% looking colors.
%
% lineStyles = linspecer(N); makes N colors for you to use: lineStyles(ii,:)
%
% colormap(linspecer); set your colormap to have easily distinguishable
% colors and a pleasing aesthetic
%
% lineStyles = linspecer(N,'qualitative'); forces the colors to all be distinguishable (up to 12)
% lineStyles = linspecer(N,'sequential'); forces the colors to vary along a spectrum
%
% % Examples demonstrating the colors.
%
% LINE COLORS
% N=6;
% X = linspace(0,pi*3,1000);
% Y = bsxfun(@(x,n)sin(x+2*n*pi/N), X.', 1:N);
% C = linspecer(N);
% axes('NextPlot','replacechildren', 'ColorOrder',C);
% plot(X,Y,'linewidth',5)
% ylim([-1.1 1.1]);
%
% SIMPLER LINE COLOR EXAMPLE
% N = 6; X = linspace(0,pi*3,1000);
% C = linspecer(N)
% hold off;
% for ii=1:N
% Y = sin(X+2*ii*pi/N);
% plot(X,Y,'color',C(ii,:),'linewidth',3);
% hold on;
% end
%
% COLORMAP EXAMPLE
% A = rand(15);
% figure; imagesc(A); % default colormap
% figure; imagesc(A); colormap(linspecer); % linspecer colormap
%
% See also NDHIST, NHIST, PLOT, COLORMAP, 43700-cubehelix-colormaps
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% by Jonathan Lansey, March 2009-2013 Lansey at gmail.com %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%% credits and where the function came from
% The colors are largely taken from:
% http://colorbrewer2.org and Cynthia Brewer, Mark Harrower and The Pennsylvania State University
%
%
% She studied this from a phsychometric perspective and crafted the colors
% beautifully.
%
% I made choices from the many there to decide the nicest once for plotting
% lines in Matlab. I also made a small change to one of the colors I
% thought was a bit too bright. In addition some interpolation is going on
% for the sequential line styles.
%
%
%%
function lineStyles=linspecer(N,varargin)
if nargin==0 % return a colormap
lineStyles = linspecer(128);
return;
end
if ischar(N)
lineStyles = linspecer(128,N);
return;
end
if N<=0 % its empty, nothing else to do here
lineStyles=[];
return;
end
% interperet varagin
qualFlag = 0;
colorblindFlag = 0;
if ~isempty(varargin)>0 % you set a parameter?
switch lower(varargin{1})
case {'qualitative','qua'}
if N>12 % go home, you just can't get this.
warning('qualitiative is not possible for greater than 12 items, please reconsider');
else
if N>9
warning(['Default may be nicer for ' num2str(N) ' for clearer colors use: whitebg(''black''); ']);
end
end
qualFlag = 1;
case {'sequential','seq'}
lineStyles = colorm(N);
return;
case {'white','whitefade'}
lineStyles = whiteFade(N);return;
case 'red'
lineStyles = whiteFade(N,'red');return;
case 'blue'
lineStyles = whiteFade(N,'blue');return;
case 'green'
lineStyles = whiteFade(N,'green');return;
case {'gray','grey'}
lineStyles = whiteFade(N,'gray');return;
case {'colorblind'}
colorblindFlag = 1;
otherwise
warning(['parameter ''' varargin{1} ''' not recognized']);
end
end
% *.95
% predefine some colormaps
set3 = colorBrew2mat({[141, 211, 199];[ 255, 237, 111];[ 190, 186, 218];[ 251, 128, 114];[ 128, 177, 211];[ 253, 180, 98];[ 179, 222, 105];[ 188, 128, 189];[ 217, 217, 217];[ 204, 235, 197];[ 252, 205, 229];[ 255, 255, 179]}');
set1JL = brighten(colorBrew2mat({[228, 26, 28];[ 55, 126, 184]; [ 77, 175, 74];[ 255, 127, 0];[ 255, 237, 111]*.85;[ 166, 86, 40];[ 247, 129, 191];[ 153, 153, 153];[ 152, 78, 163]}'));
set1 = brighten(colorBrew2mat({[ 55, 126, 184]*.85;[228, 26, 28];[ 77, 175, 74];[ 255, 127, 0];[ 152, 78, 163]}),.8);
% colorblindSet = {[215,25,28];[253,174,97];[171,217,233];[44,123,182]};
colorblindSet = {[215,25,28];[253,174,97];[171,217,233]*.8;[44,123,182]*.8};
set3 = dim(set3,.93);
if colorblindFlag
switch N
% sorry about this line folks. kind of legacy here because I used to
% use individual 1x3 cells instead of nx3 arrays
case 4
lineStyles = colorBrew2mat(colorblindSet);
otherwise
colorblindFlag = false;
warning('sorry unsupported colorblind set for this number, using regular types');
end
end
if ~colorblindFlag
switch N
case 1
lineStyles = { [ 55, 126, 184]/255};
case {2, 3, 4, 5 }
lineStyles = set1(1:N);
case {6 , 7, 8, 9}
lineStyles = set1JL(1:N)';
case {10, 11, 12}
if qualFlag % force qualitative graphs
lineStyles = set3(1:N)';
else % 10 is a good number to start with the sequential ones.
lineStyles = cmap2linspecer(colorm(N));
end
otherwise % any old case where I need a quick job done.
lineStyles = cmap2linspecer(colorm(N));
end
end
lineStyles = cell2mat(lineStyles);
end
% extra functions
function varIn = colorBrew2mat(varIn)
for ii=1:length(varIn) % just divide by 255
varIn{ii}=varIn{ii}/255;
end
end
function varIn = brighten(varIn,varargin) % increase the brightness
if isempty(varargin),
frac = .9;
else
frac = varargin{1};
end
for ii=1:length(varIn)
varIn{ii}=varIn{ii}*frac+(1-frac);
end
end
function varIn = dim(varIn,f)
for ii=1:length(varIn)
varIn{ii} = f*varIn{ii};
end
end
function vOut = cmap2linspecer(vIn) % changes the format from a double array to a cell array with the right format
vOut = cell(size(vIn,1),1);
for ii=1:size(vIn,1)
vOut{ii} = vIn(ii,:);
end
end
%%
% colorm returns a colormap which is really good for creating informative
% heatmap style figures.
% No particular color stands out and it doesn't do too badly for colorblind people either.
% It works by interpolating the data from the
% 'spectral' setting on http://colorbrewer2.org/ set to 11 colors
% It is modified a little to make the brightest yellow a little less bright.
function cmap = colorm(varargin)
n = 100;
if ~isempty(varargin)
n = varargin{1};
end
if n==1
cmap = [0.2005 0.5593 0.7380];
return;
end
if n==2
cmap = [0.2005 0.5593 0.7380;
0.9684 0.4799 0.2723];
return;
end
frac=.95; % Slight modification from colorbrewer here to make the yellows in the center just a bit darker
cmapp = [158, 1, 66; 213, 62, 79; 244, 109, 67; 253, 174, 97; 254, 224, 139; 255*frac, 255*frac, 191*frac; 230, 245, 152; 171, 221, 164; 102, 194, 165; 50, 136, 189; 94, 79, 162];
x = linspace(1,n,size(cmapp,1));
xi = 1:n;
cmap = zeros(n,3);
for ii=1:3
cmap(:,ii) = pchip(x,cmapp(:,ii),xi);
end
cmap = flipud(cmap/255);
end
function cmap = whiteFade(varargin)
n = 100;
if nargin>0
n = varargin{1};
end
thisColor = 'blue';
if nargin>1
thisColor = varargin{2};
end
switch thisColor
case {'gray','grey'}
cmapp = [255,255,255;240,240,240;217,217,217;189,189,189;150,150,150;115,115,115;82,82,82;37,37,37;0,0,0];
case 'green'
cmapp = [247,252,245;229,245,224;199,233,192;161,217,155;116,196,118;65,171,93;35,139,69;0,109,44;0,68,27];
case 'blue'
cmapp = [247,251,255;222,235,247;198,219,239;158,202,225;107,174,214;66,146,198;33,113,181;8,81,156;8,48,107];
case 'red'
cmapp = [255,245,240;254,224,210;252,187,161;252,146,114;251,106,74;239,59,44;203,24,29;165,15,21;103,0,13];
otherwise
warning(['sorry your color argument ' thisColor ' was not recognized']);
end
cmap = interpomap(n,cmapp);
end
% Eat a approximate colormap, then interpolate the rest of it up.
function cmap = interpomap(n,cmapp)
x = linspace(1,n,size(cmapp,1));
xi = 1:n;
cmap = zeros(n,3);
for ii=1:3
cmap(:,ii) = pchip(x,cmapp(:,ii),xi);
end
cmap = (cmap/255); % flipud??
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
pdftops.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/pdftops.m
| 3,687 |
utf_8
|
43c139e49fce63cb78060895bd13137a
|
function varargout = pdftops(cmd)
%PDFTOPS Calls a local pdftops executable with the input command
%
% Example:
% [status result] = pdftops(cmd)
%
% Attempts to locate a pdftops executable, finally asking the user to
% specify the directory pdftops was installed into. The resulting path is
% stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have pdftops (from the Xpdf package)
% installed on your system. You can download this from:
% http://www.foolabs.com/xpdf
%
% IN:
% cmd - Command string to be passed into pdftops.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from pdftops.
% Copyright: Oliver Woodford, 2009-2010
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on
% Mac OS.
% Thanks to Christoph Hertel for pointing out a bug in check_xpdf_path
% under linux.
% 23/01/2014 - Add full path to pdftops.txt in warning.
% 27/05/2015 - Fixed alert in case of missing pdftops; fixed code indentation
% Call pdftops
[varargout{1:nargout}] = system(sprintf('"%s" %s', xpdf_path, cmd));
end
function path_ = xpdf_path
% Return a valid path
% Start with the currently set path
path_ = user_string('pdftops');
% Check the path works
if check_xpdf_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = 'pdftops.exe';
else
bin = 'pdftops';
end
if check_store_xpdf_path(bin)
path_ = bin;
return
end
% Search the obvious places
if ispc
path_ = 'C:\Program Files\xpdf\pdftops.exe';
else
path_ = '/usr/local/bin/pdftops';
end
if check_store_xpdf_path(path_)
return
end
% Ask the user to enter the path
while 1
errMsg = 'Pdftops not found. Please locate the program, or install xpdf-tools from ';
url = 'http://foolabs.com/xpdf';
fprintf(2, '%s\n', [errMsg '<a href="matlab:web(''-browser'',''' url ''');">' url '</a>']);
errMsg = [errMsg url]; %#ok<AGROW>
if strncmp(computer,'MAC',3) % Is a Mac
% Give separate warning as the MacOS uigetdir dialogue box doesn't have a title
uiwait(warndlg(errMsg))
end
base = uigetdir('/', errMsg);
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
path_ = [base bin_dir{a} bin];
if exist(path_, 'file') == 2
break;
end
end
if check_store_xpdf_path(path_)
return
end
end
error('pdftops executable not found.');
end
function good = check_store_xpdf_path(path_)
% Check the path is valid
good = check_xpdf_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('pdftops', path_)
warning('Path to pdftops executable could not be saved. Enter it manually in %s.', fullfile(fileparts(which('user_string.m')), '.ignore', 'pdftops.txt'));
return
end
end
function good = check_xpdf_path(path_)
% Check the path is valid
[good, message] = system(sprintf('"%s" -h', path_)); %#ok<ASGLU>
% system returns good = 1 even when the command runs
% Look for something distinct in the help text
good = ~isempty(strfind(message, 'PostScript'));
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
crop_borders.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/crop_borders.m
| 3,791 |
utf_8
|
2c8fc83f142f1d5b28b99080556c791e
|
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
if nargin < 3
padding = 0;
end
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop margin from right
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop margin from top
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
% Crop the background, leaving one boundary pixel to avoid bleeding on resize
%v = [max(t-padding, 1) min(b+padding, h) max(l-padding, 1) min(r+padding, w)];
%A = A(v(1):v(2),v(3):v(4),:,:);
if padding == 0 % no padding
padding = 1;
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,(b-t)+1+padding*2,(r-l)+1+padding*2);
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :) = A(vA(1):vA(2), vA(3):vA(4), :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
isolate_axes.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/isolate_axes.m
| 4,851 |
utf_8
|
611d9727e84ad6ba76dcb3543434d0ce
|
function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
im2gif.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/im2gif.m
| 6,234 |
utf_8
|
8ee74d7d94e524410788276aa41dd5f1
|
%IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
read_write_entire_textfile.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/read_write_entire_textfile.m
| 961 |
utf_8
|
775aa1f538c76516c7fb406a4f129320
|
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
pdf2eps.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/pdf2eps.m
| 1,522 |
utf_8
|
4c8f0603619234278ed413670d24bdb6
|
%PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
print2array.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/print2array.m
| 9,613 |
utf_8
|
e398a6296734121e6e1983a45298549a
|
function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
err = false;
% Set paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset paper size
set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
append_pdfs.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/append_pdfs.m
| 2,759 |
utf_8
|
9b52be41aff48bea6f27992396900640
|
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
using_hg2.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/using_hg2.m
| 1,037 |
utf_8
|
3303caab5694b040103ccb6b689387bf
|
%USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
eps2pdf.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/eps2pdf.m
| 8,543 |
utf_8
|
a63a364925b89dac21030d36b0dd29a3
|
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename(-fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
ghostscript.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/ghostscript.m
| 7,902 |
utf_8
|
ff62a40d651197dbea5d3c39998b3bad
|
function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
fix_lines.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/exportFig/fix_lines.m
| 6,441 |
utf_8
|
ffda929ebad8144b1e72d528fa5d9460
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
AddDilationErosionObjectives.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/layerExt/AddDilationErosionObjectives.m
| 2,955 |
utf_8
|
475beab90ff4584fde1b8972ff685f73
|
function net = AddDilationErosionObjectives(net, upsample_fac, rec_upsample, var_to_upsample, bases_size, num_basis, neigh_size, learningrate, opts)
up_name = [num2str(upsample_fac) 'x'];
net = AddSegObjective(net, var_to_upsample, up_name, upsample_fac, upsample_fac/rec_upsample, rec_upsample, neigh_size, num_basis, bases_size, 'dil', learningrate, opts);
net = AddSegObjective(net, var_to_upsample, up_name, upsample_fac, upsample_fac/rec_upsample, rec_upsample, neigh_size, num_basis, bases_size, 'ero', learningrate, opts);
function net = AddSegObjective(net, var_to_upsample, up_name, upsample_fac, bilinear_upsample, rec_upsample, neigh_size, num_basis, bases_size, sub_name, learningrate, opts)
ind_var = net.getVarIndex(var_to_upsample);
vsizes = net.getVarSizes({'input', [224 224 3 10]});
n_channels = vsizes{ind_var}(3);
conv_name = [sub_name '_seg' up_name '_coef'];
net.addLayer(conv_name, ...
dagnn.Conv('size', [neigh_size neigh_size n_channels opts.num_classes*num_basis], 'pad', floor(neigh_size/2), 'hasBias', true), ...
var_to_upsample, conv_name, {[conv_name 'f'],[conv_name 'b']});
ind = net.getParamIndex([conv_name 'f']);
net.params(ind).value = zeros(neigh_size, neigh_size, n_channels, opts.num_classes*num_basis, 'single');
net.params(ind).learningRate = learningrate;
net.params(ind).weightDecay = 1;
ind = net.getParamIndex([conv_name 'b']);
net.params(ind).value = zeros([1 opts.num_classes*num_basis], 'single');
net.params(ind).learningRate = 2;
net.params(ind).weightDecay = 1;
load(opts.bases_add);
assert(size(f,4) == opts.num_classes * num_basis);
if size(f,1) ~= bases_size
fr = zeros(bases_size, bases_size, size(f,3), size(f,4));
for fi = 1 : size(f, 4)
fr(:,:,:,fi) = imresize(f(:,:,:,fi), bases_size/size(f,1));
end
f = fr;
end
filters = single(f);
postname = '_add';
if upsample_fac == 32
postname = '';
end
deconv_name = [sub_name '_seg_deconv_' up_name postname];
type_name_ = [sub_name '_seg' up_name];
type_name = [type_name_ postname];
net.addLayer(deconv_name, ...
dagnn.ConvTranspose(...
'size', size(filters), ...
'upsample', rec_upsample, ...
'crop', [rec_upsample/2 rec_upsample/2 rec_upsample/2 rec_upsample/2], ...
'opts', {'cudnn','nocudnn'}, ...
'numGroups', opts.num_classes, ...
'hasBias', true), ...
conv_name, type_name, {[deconv_name 'f'], [deconv_name 'b']}) ;
ind = net.getParamIndex([deconv_name 'f']);
net.params(ind).value = filters;
net.params(ind).learningRate = 0;
net.params(ind).weightDecay = 1;
ind = net.getParamIndex([deconv_name 'b']);
net.params(ind).value = -ones([1 opts.num_classes], 'single');
net.params(ind).value(1) = 1;
net.params(ind).learningRate = 2;
net.params(ind).weightDecay = 1;
obj_name = ['obj_' sub_name '_seg' up_name];
net.addLayer(obj_name, ...
SegmentationLossLogistic('loss', 'logistic'), ...
{type_name_, [sub_name '_gt_' num2str(bilinear_upsample)]}, obj_name) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
test_examples.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/utils/test_examples.m
| 1,591 |
utf_8
|
16831be7382a9343beff5cc3fe301e51
|
function test_examples()
%TEST_EXAMPLES Test some of the examples in the `examples/` directory
addpath examples/mnist ;
addpath examples/cifar ;
trainOpts.gpus = [] ;
trainOpts.continue = true ;
num = 1 ;
exps = {} ;
for networkType = {'dagnn', 'simplenn'}
for index = 1:4
clear ex ;
ex.trainOpts = trainOpts ;
ex.networkType = char(networkType) ;
ex.index = index ;
exps{end+1} = ex ;
end
end
if num > 1
if isempty(gcp('nocreate')),
parpool('local',num) ;
end
parfor e = 1:numel(exps)
test_one(exps{e}) ;
end
else
for e = 1:numel(exps)
test_one(exps{e}) ;
end
end
% ------------------------------------------------------------------------
function test_one(ex)
% -------------------------------------------------------------------------
suffix = ['-' ex.networkType] ;
switch ex.index
case 1
cnn_mnist(...
'expDir', ['data/test-mnist' suffix], ...
'batchNormalization', false, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 2
cnn_mnist(...
'expDir', ['data/test-mnist-bnorm' suffix], ...
'batchNormalization', true, ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 3
cnn_cifar(...
'expDir', ['data/test-cifar-lenet' suffix], ...
'modelType', 'lenet', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
case 4
cnn_cifar(...
'expDir', ['data/test-cifar-nin' suffix], ...
'modelType', 'nin', ...
'networkType', ex.networkType, ...
'train', ex.trainOpts) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
simplenn_caffe_compare.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/utils/simplenn_caffe_compare.m
| 5,638 |
utf_8
|
8e9862ffbf247836e6ff7579d1e6dc85
|
function diffStats = simplenn_caffe_compare( net, caffeModelBaseName, testData, varargin)
% SIMPLENN_CAFFE_COMPARE compare the simplenn network and caffe models
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME) Evaluates a forward
% pass of a simplenn network NET and caffe models stored in
% CAFFE_BASE_MODELNAME and numerically compares the network outputs using
% a random input data.
%
% SIMPLENN_CAFFE_COMPARE(NET, CAFFE_BASE_MODELNAME, TEST_DATA) Evaluates
% the simplenn network and Caffe model on a given data. If TEST_DATA is
% an empty array, uses a random input.
%
% RES = SIMPLENN_CAFFE_COMPARE(...) returns a structure with the
% statistics of the differences where each field of a structure RES is
% named after a blob and contains basic statistics:
% `[MIN_DIFF, MEAN_DIFF, MAX_DIFF]`
%
% This script attempts to match the NET layer names and caffe blob names
% and shows the MIN, MEAN and MAX difference between the outputs. For
% caffe model, the mean image stored with the caffe model is used (see
% `simplenn_caffe_deploy` for details). Furthermore the script compares
% the execution time of both networks.
%
% Compiled MatCaffe (usually located in `<caffe_dir>/matlab`, built
% with the `matcaffe` target) must be in path.
%
% SIMPLENN_CAFFE_COMPARE(..., 'OPT', VAL, ...) takes the following
% options:
%
% `numRepetitions`:: `1`
% Evaluate the network multiple times. Useful to compare the execution
% time.
%
% `device`:: `cpu`
% Evaluate the network on the specified device (CPU or GPU). For GPU
% evaluation, the current GPU is used for both Caffe and simplenn.
%
% `silent`:: `false`
% When true, supress all outputs to stdin.
%
% See Also: simplenn_caffe_deploy
% Copyright (C) 2016 Karel Lenc, Zohar Bar-Yehuda
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.numRepetitions = 1;
opts.randScale = 100;
opts.device = 'cpu';
opts.silent = false;
opts = vl_argparse(opts, varargin);
info = @(varargin) fprintf(1, varargin{:});
if opts.silent, info = @(varargin) []; end;
if ~exist('caffe.Net', 'class'), error('MatCaffe not in path.'); end
prototxtFilename = [caffeModelBaseName '.prototxt'];
if ~exist(prototxtFilename, 'file')
error('Caffe net definition `%s` not found', prototxtFilename);
end;
modelFilename = [caffeModelBaseName '.caffemodel'];
if ~exist(prototxtFilename, 'file')
error('Caffe net model `%s` not found', modelFilename);
end;
meanFilename = [caffeModelBaseName, '_mean_image.binaryproto'];
net = vl_simplenn_tidy(net);
net = vl_simplenn_move(net, opts.device);
netBlobNames = [{'data'}, cellfun(@(l) l.name, net.layers, ...
'UniformOutput', false)];
% Load the Caffe model
caffeNet = caffe.Net(prototxtFilename, modelFilename, 'test');
switch opts.device
case 'cpu'
caffe.set_mode_cpu();
case 'gpu'
caffe.set_mode_gpu();
gpuDev = gpuDevice();
caffe.set_device(gpuDev.Index - 1);
end
caffeBlobNames = caffeNet.blob_names';
[caffeLayerFound, caffe2netres] = ismember(caffeBlobNames, netBlobNames);
info('Found %d matches between simplenn layers and caffe blob names.\n',...
sum(caffeLayerFound));
% If testData not supplied, use random input
imSize = net.meta.normalization.imageSize;
if ~exist('testData', 'var') || isempty(testData)
testData = rand(imSize, 'single') * opts.randScale;
end
if ischar(testData), testData = imread(testData); end
testDataSize = [size(testData), 1, 1];
assert(all(testDataSize(1:3) == imSize(1:3)), 'Invalid test data size.');
testData = single(testData);
dataCaffe = matlab_img_to_caffe(testData);
if isfield(net.meta.normalization, 'averageImage') && ...
~isempty(net.meta.normalization.averageImage)
avImage = net.meta.normalization.averageImage;
if numel(avImage) == imSize(3)
avImage = reshape(avImage, 1, 1, imSize(3));
end
testData = bsxfun(@minus, testData, avImage);
end
% Test MatConvNet model
stime = tic;
for rep = 1:opts.numRepetitions
res = vl_simplenn(net, testData, [], [], 'ConserveMemory', false);
end
info('MatConvNet %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
if ~isempty(meanFilename) && exist(meanFilename, 'file')
mean_img_caffe = caffe.io.read_mean(meanFilename);
dataCaffe = bsxfun(@minus, dataCaffe, mean_img_caffe);
end
% Test Caffe model
stime = tic;
for rep = 1:opts.numRepetitions
caffeNet.forward({dataCaffe});
end
info('Caffe %s time: %.1f ms.\n', opts.device, ...
toc(stime)/opts.numRepetitions*1000);
diffStats = struct();
for li = 1:numel(caffeBlobNames)
blob = caffeNet.blobs(caffeBlobNames{li});
caffeData = permute(blob.get_data(), [2, 1, 3, 4]);
if li == 1 && size(caffeData, 3) == 3
caffeData = caffeData(:, :, [3, 2, 1]);
end
mcnData = gather(res(caffe2netres(li)).x);
diff = abs(caffeData(:) - mcnData(:));
diffStats.(caffeBlobNames{li}) = [min(diff), mean(diff), max(diff)]';
end
if ~opts.silent
pp = '% 10s % 10s % 10s % 10s\n';
precp = '% 10.2e';
fprintf(pp, 'Layer name', 'Min', 'Mean', 'Max');
for li = 1:numel(caffeBlobNames)
lstats = diffStats.(caffeBlobNames{li});
fprintf(pp, caffeBlobNames{li}, sprintf(precp, lstats(1)), ...
sprintf(precp, lstats(2)), sprintf(precp, lstats(3)));
end
fprintf('\n');
end
end
function img = matlab_img_to_caffe(img)
img = single(img);
% Convert from HxWxCxN to WxHxCxN per Caffe's convention
img = permute(img, [2 1 3 4]);
if size(img,3) == 3
% Convert from RGB to BGR channel order per Caffe's convention
img = img(:,:, [3 2 1], :);
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_train_dag.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/cnn_train_dag.m
| 16,099 |
utf_8
|
326a535b1d18f74d19e5526a8a5c195b
|
function [net,stats] = cnn_train_dag(net, imdb, getBatch, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
% CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
% the DagNN wrapper instead of the SimpleNN wrapper.
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.derOutputs = {'objective', 1} ;
opts.extractStatsFn = @extractStats ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
if isempty(opts.derOutputs)
error('DEROUTPUTS must be specified when training.\n') ;
end
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(opts.gpus) <= 1
[net, state] = processEpoch(net, state, params, 'val') ;
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if opts.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
state.momentum = num2cell(zeros(1, numel(net.params))) ;
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net.move('gpu') ;
state.momentum = cellfun(@gpuArray, state.momentum, 'uniformoutput', false) ;
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
net.setParameterServer(parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
num = 0 ;
epoch = params.epoch ;
subset = params.(mode) ;
adjustTime = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if strcmp(mode, 'train')
net.mode = 'normal' ;
net.accumulateParamDers = (s ~= 1) ;
net.eval(inputs, params.derOutputs, 'holdOn', s < params.numSubBatches) ;
else
net.mode = 'test' ;
net.vars(11).precious = 1;
net.eval(inputs) ;
end
% test in batch
% imt = inputs{2};
% labels = inputs{end};
% score_batch = squeeze(net.vars(11).value);
% [~, predLabel_batch] = max(score_batch, [], 1);
% acc_batch = 1-mean(labels(:)==predLabel_batch(:));
% % test individually
% predLabel_single = zeros(1, length(labels));
% score_single = zeros(10, length(labels));
% for iii = 1:length(labels)
% curLabel = labels(iii);
% curInput = {inputs{1}, imt(:,:,:,iii), inputs{3}, curLabel};
%
% net.vars(11).precious = 1;
% net.eval(curInput);
%
% curA = squeeze(net.vars(11).value);
% score_single(:, iii) = curA(:);
% [~, curPredLabel] = max(curA, [], 1);
% predLabel_single(iii) = curPredLabel;
% end
% acc_single = 1-mean(labels(:)==predLabel_single(:));
%
% fprintf('\nacc in batch form: %.4f\n', acc_batch);
% fprintf('acc in single form: %.4f\n', acc_single);
% fprintf('score difference: %.4f\n', norm(score_single(:)-score_batch(:)));
end
% Accumulate gradient.
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
state = accumulateGradients(net, state, params, batchSize, parserv) ;
end
% Get statistics.
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats.num = num ;
stats.time = time ;
stats = params.extractStatsFn(stats,net) ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
state.momentum = cellfun(@gather, state.momentum, 'uniformoutput', false) ;
end
net.reset() ;
net.move('cpu') ;
% -------------------------------------------------------------------------
function state = accumulateGradients(net, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for p=1:numel(net.params)
if ~isempty(parserv)
parDer = parserv.pullWithIndex(p) ;
else
parDer = net.params(p).der ;
end
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate ;
net.params(p).value = vl_taccum(...
1 - thisLR, net.params(p).value, ...
(thisLR/batchSize/net.params(p).fanout), parDer) ;
case 'gradient'
thisDecay = params.weightDecay * net.params(p).weightDecay ;
thisLR = params.learningRate * net.params(p).learningRate ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.params(p).value) ;
% Update momentum.
state.momentum{p} = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{p}, ...
-1, parDer) ;
else
delta = state.momentum{p} ;
end
% Update parameters.
net.params(p).value = vl_taccum(...
1, net.params(p).value, thisLR, delta) ;
end
otherwise
error('Unknown training method ''%s'' for parameter ''%s''.', ...
net.params(p).trainMethod, ...
net.params(p).name) ;
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(stats, net)
% -------------------------------------------------------------------------
sel = find(cellfun(@(x) isa(x,'dagnn.Loss'), {net.layers.block})) ;
for i = 1:numel(sel)
stats.(net.layers(sel(i)).outputs{1}) = net.layers(sel(i)).block.average ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net_, state)
% -------------------------------------------------------------------------
net = net_.saveobj() ;
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = dagnn.DagNN.loadobj(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_train.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/cnn_train.m
| 22,309 |
utf_8
|
7cd588eb330fec6caf497e384b4a2734
|
function [net, stats] = cnn_train(net, imdb, getBatch, varargin)
%CNN_TRAIN An example implementation of SGD for training CNNs
% CNN_TRAIN() is an example learner implementing stochastic
% gradient descent with momentum to train a CNN. It can be used
% with different datasets and tasks by providing a suitable
% getBatch function.
%
% The function automatically restarts after each training epoch by
% checkpointing.
%
% The function supports training on CPU or on one or more GPUs
% (specify the list of GPU IDs in the `gpus` option).
% Copyright (C) 2014-16 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.expDir = fullfile('data','exp') ;
opts.continue = true ;
opts.batchSize = 256 ;
opts.numSubBatches = 1 ;
opts.train = [] ;
opts.val = [] ;
opts.gpus = [] ;
opts.prefetch = false ;
opts.numEpochs = 300 ;
opts.learningRate = 0.001 ;
opts.weightDecay = 0.0005 ;
opts.momentum = 0.9 ;
opts.saveMomentum = true ;
opts.nesterovUpdate = false ;
opts.randomSeed = 0 ;
opts.memoryMapFile = fullfile(tempdir, 'matconvnet.bin') ;
opts.profile = false ;
opts.parameterServer.method = 'mmap' ;
opts.parameterServer.prefix = 'mcn' ;
opts.conserveMemory = true ;
opts.backPropDepth = +inf ;
opts.sync = false ;
opts.cudnn = true ;
opts.errorFunction = 'multiclass' ;
opts.errorLabels = {} ;
opts.plotDiagnostics = false ;
opts.plotStatistics = true;
opts = vl_argparse(opts, varargin) ;
if ~exist(opts.expDir, 'dir'), mkdir(opts.expDir) ; end
if isempty(opts.train), opts.train = find(imdb.images.set==1) ; end
if isempty(opts.val), opts.val = find(imdb.images.set==2) ; end
if isnan(opts.train), opts.train = [] ; end
if isnan(opts.val), opts.val = [] ; end
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
net = vl_simplenn_tidy(net); % fill in some eventually missing values
net.layers{end-1}.precious = 1; % do not remove predictions, used for error
vl_simplenn_display(net, 'batchSize', opts.batchSize) ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
for i=1:numel(net.layers)
J = numel(net.layers{i}.weights) ;
if ~isfield(net.layers{i}, 'learningRate')
net.layers{i}.learningRate = ones(1, J) ;
end
if ~isfield(net.layers{i}, 'weightDecay')
net.layers{i}.weightDecay = ones(1, J) ;
end
end
end
% setup error calculation function
hasError = true ;
if isstr(opts.errorFunction)
switch opts.errorFunction
case 'none'
opts.errorFunction = @error_none ;
hasError = false ;
case 'multiclass'
opts.errorFunction = @error_multiclass ;
if isempty(opts.errorLabels), opts.errorLabels = {'top1err', 'top5err'} ; end
case 'binary'
opts.errorFunction = @error_binary ;
if isempty(opts.errorLabels), opts.errorLabels = {'binerr'} ; end
otherwise
error('Unknown error function ''%s''.', opts.errorFunction) ;
end
end
state.getBatch = getBatch ;
stats = [] ;
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('%s: resuming by loading epoch %d\n', mfilename, start) ;
[net, state, stats] = loadState(modelPath(start)) ;
else
state = [] ;
end
for epoch=start+1:opts.numEpochs
% Set the random seed based on the epoch and opts.randomSeed.
% This is important for reproducibility, including when training
% is restarted from a checkpoint.
rng(epoch + opts.randomSeed) ;
prepareGPUs(opts, epoch == start+1) ;
% Train for one epoch.
params = opts ;
params.epoch = epoch ;
params.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
params.train = opts.train(randperm(numel(opts.train))) ; % shuffle
params.val = opts.val(randperm(numel(opts.val))) ;
params.imdb = imdb ;
params.getBatch = getBatch ;
if numel(params.gpus) <= 1
% [net, state] = processEpoch(net, state, params, 'val') ;
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
else
spmd
[net, state] = processEpoch(net, state, params, 'train') ;
[net, state] = processEpoch(net, state, params, 'val') ;
if labindex == 1 && ~evaluateMode
saveState(modelPath(epoch), net, state) ;
end
lastStats = state.stats ;
end
lastStats = accumulateStats(lastStats) ;
end
stats.train(epoch) = lastStats.train ;
stats.val(epoch) = lastStats.val ;
clear lastStats ;
saveStats(modelPath(epoch), stats) ;
if params.plotStatistics
switchFigure(1) ; clf ;
plots = setdiff(...
cat(2,...
fieldnames(stats.train)', ...
fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
print(1, modelFigPath, '-dpdf') ;
end
end
% With multiple GPUs, return one copy
if isa(net, 'Composite'), net = net{1} ; end
% -------------------------------------------------------------------------
function err = error_multiclass(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
[~,predictions] = sort(predictions, 3, 'descend') ;
% be resilient to badly formatted labels
if numel(labels) == size(predictions, 4)
labels = reshape(labels,1,1,1,[]) ;
end
% skip null labels
mass = single(labels(:,:,1,:) > 0) ;
if size(labels,3) == 2
% if there is a second channel in labels, used it as weights
mass = mass .* labels(:,:,2,:) ;
labels(:,:,2,:) = [] ;
end
m = min(5, size(predictions,3)) ;
error = ~bsxfun(@eq, predictions, labels) ;
err(1,1) = sum(sum(sum(mass .* error(:,:,1,:)))) ;
err(2,1) = sum(sum(sum(mass .* min(error(:,:,1:m,:),[],3)))) ;
% -------------------------------------------------------------------------
function err = error_binary(params, labels, res)
% -------------------------------------------------------------------------
predictions = gather(res(end-1).x) ;
error = bsxfun(@times, predictions, labels) < 0 ;
err = sum(error(:)) ;
% -------------------------------------------------------------------------
function err = error_none(params, labels, res)
% -------------------------------------------------------------------------
err = zeros(0,1) ;
% -------------------------------------------------------------------------
function [net, state] = processEpoch(net, state, params, mode)
% -------------------------------------------------------------------------
% Note that net is not strictly needed as an output argument as net
% is a handle class. However, this fixes some aliasing issue in the
% spmd caller.
% initialize with momentum 0
if isempty(state) || isempty(state.momentum)
for i = 1:numel(net.layers)
for j = 1:numel(net.layers{i}.weights)
state.momentum{i}{j} = 0 ;
end
end
end
% move CNN to GPU as needed
numGpus = numel(params.gpus) ;
if numGpus >= 1
net = vl_simplenn_move(net, 'gpu') ;
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gpuArray(state.momentum{i}{j}) ;
end
end
end
if numGpus > 1
parserv = ParameterServer(params.parameterServer) ;
vl_simplenn_start_parserv(net, parserv) ;
else
parserv = [] ;
end
% profile
if params.profile
if numGpus <= 1
profile clear ;
profile on ;
else
mpiprofile reset ;
mpiprofile on ;
end
end
subset = params.(mode) ;
num = 0 ;
stats.num = 0 ; % return something even if subset = []
stats.time = 0 ;
adjustTime = 0 ;
res = [] ;
error = [] ;
start = tic ;
for t=1:params.batchSize:numel(subset)
fprintf('%s: epoch %02d: %3d/%3d:', mode, params.epoch, ...
fix((t-1)/params.batchSize)+1, ceil(numel(subset)/params.batchSize)) ;
batchSize = min(params.batchSize, numel(subset) - t + 1) ;
for s=1:params.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+params.batchSize-1, numel(subset)) ;
batch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
[im, labels] = params.getBatch(params.imdb, batch) ;
if params.prefetch
if s == params.numSubBatches
batchStart = t + (labindex-1) + params.batchSize ;
batchEnd = min(t+2*params.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : params.numSubBatches * numlabs : batchEnd) ;
params.getBatch(params.imdb, nextBatch) ;
end
if numGpus >= 1
im = gpuArray(im) ;
end
if strcmp(mode, 'train')
dzdy = 1 ;
evalMode = 'normal' ;
else
dzdy = [] ;
evalMode = 'test' ;
end
net.layers{end}.class = labels ;
res = vl_simplenn(net, im, dzdy, res, ...
'accumulate', s ~= 1, ...
'mode', evalMode, ...
'conserveMemory', params.conserveMemory, ...
'backPropDepth', params.backPropDepth, ...
'sync', params.sync, ...
'cudnn', params.cudnn, ...
'parameterServer', parserv, ...
'holdOn', s < params.numSubBatches) ;
%
% % test in batch
% score_batch = squeeze(res(end-1).x);
% [~, predLabel_batch] = max(score_batch, [], 1);
% acc_batch = 1-mean(labels(:)==predLabel_batch(:));
% % test individually
% predLabel_single = zeros(1, length(labels));
% score_single = zeros(10, length(labels));
% for iii = 1:length(labels)
% curLabel = labels(iii);
% net.layers{end}.class = curLabel;
% res = vl_simplenn(net, im(:,:,:,iii), dzdy, res, ...
% 'accumulate', s ~= 1, ...
% 'mode', evalMode, ...
% 'conserveMemory', params.conserveMemory, ...
% 'backPropDepth', params.backPropDepth, ...
% 'sync', params.sync, ...
% 'cudnn', params.cudnn, ...
% 'parameterServer', parserv, ...
% 'holdOn', s < params.numSubBatches) ;
% curA = squeeze(res(end-1).x);
% score_single(:, iii) = curA(:);
% [~, curPredLabel] = max(curA, [], 1);
% predLabel_single(iii) = curPredLabel;
% end
% acc_single = 1-mean(labels(:)==predLabel_single(:));
%
% fprintf('\nacc in batch form: %.4f\n', acc_batch);
% fprintf('acc in single form: %.4f\n', acc_single);
% fprintf('score difference: %.4f\n', norm(score_single(:)-score_batch(:)));
% accumulate errors
error = sum([error, [...
sum(double(gather(res(end).x))) ;
reshape(params.errorFunction(params, labels, res),[],1) ; ]],2) ;
end
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(parserv), parserv.sync() ; end
[net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv) ;
end
% get statistics
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats = extractStats(net, params, error / num) ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*params.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf(' %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
for f = setdiff(fieldnames(stats)', {'num', 'time'})
f = char(f) ;
fprintf(' %s: %.3f', f, stats.(f)) ;
end
fprintf('\n') ;
% collect diagnostic statistics
if strcmp(mode, 'train') && params.plotDiagnostics
switchFigure(2) ; clf ;
diagn = [res.stats] ;
diagnvar = horzcat(diagn.variation) ;
diagnpow = horzcat(diagn.power) ;
subplot(2,2,1) ; barh(diagnvar) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnvar), ...
'YTickLabel',horzcat(diagn.label), ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1], ...
'XTick', 10.^(-5:1)) ;
grid on ;
subplot(2,2,2) ; barh(sqrt(diagnpow)) ;
set(gca,'TickLabelInterpreter', 'none', ...
'YTick', 1:numel(diagnpow), ...
'YTickLabel',{diagn.powerLabel}, ...
'YDir', 'reverse', ...
'XScale', 'log', ...
'XLim', [1e-5 1e5], ...
'XTick', 10.^(-5:5)) ;
grid on ;
subplot(2,2,3); plot(squeeze(res(end-1).x)) ;
drawnow ;
end
end
% Save back to state.
state.stats.(mode) = stats ;
if params.profile
if numGpus <= 1
state.prof.(mode) = profile('info') ;
profile off ;
else
state.prof.(mode) = mpiprofile('info');
mpiprofile off ;
end
end
if ~params.saveMomentum
state.momentum = [] ;
else
for i = 1:numel(state.momentum)
for j = 1:numel(state.momentum{i})
state.momentum{i}{j} = gather(state.momentum{i}{j}) ;
end
end
end
net = vl_simplenn_move(net, 'cpu') ;
% -------------------------------------------------------------------------
function [net, res, state] = accumulateGradients(net, res, state, params, batchSize, parserv)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
otherGpus = setdiff(1:numGpus, labindex) ;
for l=numel(net.layers):-1:1
for j=numel(res(l).dzdw):-1:1
if ~isempty(parserv)
tag = sprintf('l%d_%d',l,j) ;
parDer = parserv.pull(tag) ;
else
parDer = res(l).dzdw{j} ;
end
if j == 3 && strcmp(net.layers{l}.type, 'bnorm')
% special case for learning bnorm moments
thisLR = net.layers{l}.learningRate(j) ;
net.layers{l}.weights{j} = vl_taccum(...
1 - thisLR, ...
net.layers{l}.weights{j}, ...
thisLR / batchSize, ...
parDer) ;
else
% Standard gradient training.
thisDecay = params.weightDecay * net.layers{l}.weightDecay(j) ;
thisLR = params.learningRate * net.layers{l}.learningRate(j) ;
if thisLR>0 || thisDecay>0
% Normalize gradient and incorporate weight decay.
parDer = vl_taccum(1/batchSize, parDer, ...
thisDecay, net.layers{l}.weights{j}) ;
% Update momentum.
state.momentum{l}{j} = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
% Nesterov update (aka one step ahead).
if params.nesterovUpdate
delta = vl_taccum(...
params.momentum, state.momentum{l}{j}, ...
-1, parDer) ;
else
delta = state.momentum{l}{j} ;
end
% Update parameters.
net.layers{l}.weights{j} = vl_taccum(...
1, net.layers{l}.weights{j}, ...
thisLR, delta) ;
end
end
% if requested, collect some useful stats for debugging
if params.plotDiagnostics
variation = [] ;
label = '' ;
switch net.layers{l}.type
case {'conv','convt'}
variation = thisLR * mean(abs(state.momentum{l}{j}(:))) ;
power = mean(res(l+1).x(:).^2) ;
if j == 1 % fiters
base = mean(net.layers{l}.weights{j}(:).^2) ;
label = 'filters' ;
else % biases
base = sqrt(power) ;%mean(abs(res(l+1).x(:))) ;
label = 'biases' ;
end
variation = variation / base ;
label = sprintf('%s_%s', net.layers{l}.name, label) ;
end
res(l).stats.variation(j) = variation ;
res(l).stats.power = power ;
res(l).stats.powerLabel = net.layers{l}.name ;
res(l).stats.label{j} = label ;
end
end
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
% initialize stats stucture with same fields and same order as
% stats_{1}
stats__ = stats_{1} ;
names = fieldnames(stats__.(s))' ;
values = zeros(1, numel(names)) ;
fields = cat(1, names, num2cell(values)) ;
stats.(s) = struct(fields{:}) ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function stats = extractStats(net, params, errors)
% -------------------------------------------------------------------------
stats.objective = errors(1) ;
for i = 1:numel(params.errorLabels)
stats.(params.errorLabels{i}) = errors(i+1) ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, state)
% -------------------------------------------------------------------------
save(fileName, 'net', 'state') ;
% -------------------------------------------------------------------------
function saveStats(fileName, stats)
% -------------------------------------------------------------------------
if exist(fileName)
save(fileName, 'stats', '-append') ;
else
save(fileName, 'stats') ;
end
% -------------------------------------------------------------------------
function [net, state, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'state', 'stats') ;
net = vl_simplenn_tidy(net) ;
if isempty(whos('stats'))
error('Epoch ''%s'' was only partially saved. Delete this file and try again.', ...
fileName) ;
end
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
% -------------------------------------------------------------------------
function switchFigure(n)
% -------------------------------------------------------------------------
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
%clear vl_tmove vl_imreadjpeg ;
disp('Clearing mex files') ;
clear mex ;
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(params, cold)
% -------------------------------------------------------------------------
numGpus = numel(params.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename) ;
clearMex() ;
if numGpus == 1
disp(gpuDevice(params.gpus)) ;
else
spmd
clearMex() ;
disp(gpuDevice(params.gpus(labindex))) ;
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_stn_cluttered_mnist.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/spatial_transformer/cnn_stn_cluttered_mnist.m
| 3,872 |
utf_8
|
3235801f70028cc27d54d15ec2964808
|
function [net, info] = cnn_stn_cluttered_mnist(varargin)
%CNN_STN_CLUTTERED_MNIST Demonstrates training a spatial transformer
% The spatial transformer network (STN) is trained on the
% cluttered MNIST dataset.
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.useSpatialTransformer = true ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataPath = fullfile(opts.dataDir,'cluttered-mnist.mat') ;
if opts.useSpatialTransformer
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-stn') ;
else
opts.expDir = fullfile(vl_rootnn, 'data', 'cluttered-mnist-no-stn') ;
end
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.dataURL = 'http://www.vlfeat.org/matconvnet/download/data/cluttered-mnist.mat' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getImdDB(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net = cnn_stn_cluttered_mnist_init([60 60], true) ; % initialize the network
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
fbatch = @(i,b) getBatch(opts.train,i,b);
[net, info] = cnn_train_dag(net, imdb, fbatch, ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 2)) ;
% --------------------------------------------------------------------
% Show transformer
% --------------------------------------------------------------------
figure(100) ; clf ;
v = net.getVarIndex('xST') ;
net.vars(v).precious = true ;
net.eval({'input',imdb.images.data(:,:,:,1:6)}) ;
for t = 1:6
subplot(2,6,t) ; imagesc(imdb.images.data(:,:,:,t)) ; axis image off ;
subplot(2,6,6+t) ; imagesc(net.vars(v).value(:,:,:,t)) ; axis image off ;
colormap gray ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if ~isa(imdb.images.data, 'gpuArray') && numel(opts.gpus) > 0
imdb.images.data = gpuArray(imdb.images.data);
imdb.images.labels = gpuArray(imdb.images.labels);
end
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getImdDB(opts)
% --------------------------------------------------------------------
% Prepare the IMDB structure:
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
if ~exist(opts.dataPath)
fprintf('Downloading %s to %s.\n', opts.dataURL, opts.dataPath) ;
urlwrite(opts.dataURL, opts.dataPath) ;
end
dat = load(opts.dataPath);
set = [ones(1,numel(dat.y_tr)) 2*ones(1,numel(dat.y_vl)) 3*ones(1,numel(dat.y_ts))];
data = single(cat(4,dat.x_tr,dat.x_vl,dat.x_ts));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, dat.y_tr,dat.y_vl,dat.y_ts)) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
fast_rcnn_train.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/fast_rcnn/fast_rcnn_train.m
| 6,399 |
utf_8
|
54b0bc7fa26d672ed6673d3f1832944e
|
function [net, info] = fast_rcnn_train(varargin)
%FAST_RCNN_TRAIN Demonstrates training a Fast-RCNN detector
% Copyright (C) 2016 Hakan Bilen.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','bbox_functions'));
addpath(fullfile(vl_rootnn,'examples','fast_rcnn','datasets'));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
opts.sswDir = fullfile(vl_rootnn, 'data', 'SSW');
opts.expDir = fullfile(vl_rootnn, 'data', 'fast-rcnn-vgg16-pascal07') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.dataDir, 'models', ...
'imagenet-vgg-verydeep-16.mat') ;
opts.piecewise = true; % piecewise training (+bbox regression)
opts.train.gpus = [] ;
opts.train.batchSize = 2 ;
opts.train.numSubBatches = 1 ;
opts.train.continue = true ;
opts.train.prefetch = false ; % does not help for two images in a batch
opts.train.learningRate = 1e-3 / 64 * [ones(1,6) 0.1*ones(1,6)];
opts.train.weightDecay = 0.0005 ;
opts.train.numEpochs = 12 ;
opts.train.derOutputs = {'losscls', 1, 'lossbbox', 1} ;
opts.lite = false ;
opts.numFetchThreads = 2 ;
opts = vl_argparse(opts, varargin) ;
display(opts);
opts.train.expDir = opts.expDir ;
opts.train.numEpochs = numel(opts.train.learningRate) ;
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = fast_rcnn_init(...
'piecewise',opts.piecewise,...
'modelPath',opts.modelPath);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file') == 2
fprintf('Loading imdb...');
imdb = load(opts.imdbPath) ;
else
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir);
end
fprintf('Setting VOC2007 up, this may take a few minutes\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir', opts.dataDir, ...
'sswDir', opts.sswDir, ...
'addFlipped', true, ...
'useDifficult', true) ;
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
fprintf('\n');
end
fprintf('done\n');
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
% use train + val split to train
imdb.images.set(imdb.images.set == 2) = 1;
% minibatch options
bopts = net.meta.normalization;
bopts.useGpu = numel(opts.train.gpus) > 0 ;
bopts.numFgRoisPerImg = 16;
bopts.numRoisPerImg = 64;
bopts.maxScale = 1000;
bopts.scale = 600;
bopts.bgLabel = numel(imdb.classes.name)+1;
bopts.visualize = 0;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
bopts.prefetch = opts.train.prefetch;
[net,info] = cnn_train_dag(net, imdb, @(i,b) ...
getBatch(bopts,i,b), ...
opts.train) ;
% --------------------------------------------------------------------
% Deploy
% --------------------------------------------------------------------
modelPath = fullfile(opts.expDir, 'net-deployed.mat');
if ~exist(modelPath,'file')
net = deployFRCNN(net,imdb);
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
opts.visualize = 0;
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois,labels,btargets] = fast_rcnn_train_get_batch(images,imdb,...
batch, opts);
if opts.prefetch, return; end
nb = numel(labels);
nc = numel(imdb.classes.name) + 1;
% regression error only for positives
instance_weights = zeros(1,1,4*nc,nb,'single');
targets = zeros(1,1,4*nc,nb,'single');
for b=1:nb
if labels(b)>0 && labels(b)~=opts.bgLabel
targets(1,1,4*(labels(b)-1)+1:4*labels(b),b) = btargets(b,:)';
instance_weights(1,1,4*(labels(b)-1)+1:4*labels(b),b) = 1;
end
end
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
targets = gpuArray(targets) ;
instance_weights = gpuArray(instance_weights) ;
end
inputs = {'input', im, 'label', labels, 'rois', rois, 'targets', targets, ...
'instance_weights', instance_weights} ;
% --------------------------------------------------------------------
function net = deployFRCNN(net,imdb)
% --------------------------------------------------------------------
% function net = deployFRCNN(net)
for l = numel(net.layers):-1:1
if isa(net.layers(l).block, 'dagnn.Loss') || ...
isa(net.layers(l).block, 'dagnn.DropOut')
layer = net.layers(l);
net.removeLayer(layer.name);
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
end
net.rebuild();
pfc8 = net.getLayerIndex('predcls') ;
net.addLayer('probcls',dagnn.SoftMax(),net.layers(pfc8).outputs{1},...
'probcls',{});
net.vars(net.getVarIndex('probcls')).precious = true ;
idxBox = net.getLayerIndex('predbbox') ;
if ~isnan(idxBox)
net.vars(net.layers(idxBox).outputIndexes(1)).precious = true ;
% incorporate mean and std to bbox regression parameters
blayer = net.layers(idxBox) ;
filters = net.params(net.getParamIndex(blayer.params{1})).value ;
biases = net.params(net.getParamIndex(blayer.params{2})).value ;
boxMeans = single(imdb.boxes.bboxMeanStd{1}');
boxStds = single(imdb.boxes.bboxMeanStd{2}');
net.params(net.getParamIndex(blayer.params{1})).value = ...
bsxfun(@times,filters,...
reshape([boxStds(:)' zeros(1,4,'single')]',...
[1 1 1 4*numel(net.meta.classes.name)]));
biases = biases .* [boxStds(:)' zeros(1,4,'single')];
net.params(net.getParamIndex(blayer.params{2})).value = ...
bsxfun(@plus,biases, [boxMeans(:)' zeros(1,4,'single')]);
end
net.mode = 'test' ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
fast_rcnn_evaluate.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/fast_rcnn/fast_rcnn_evaluate.m
| 6,941 |
utf_8
|
a54a3f8c3c8e5a8ff7ebe4e2b12ede30
|
function [aps, speed] = fast_rcnn_evaluate(varargin)
%FAST_RCNN_EVALUATE Evaluate a trained Fast-RCNN model on PASCAL VOC 2007
% Copyright (C) 2016 Hakan Bilen.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
addpath(fullfile(vl_rootnn, 'data', 'VOCdevkit', 'VOCcode'));
addpath(genpath(fullfile(vl_rootnn, 'examples', 'fast_rcnn')));
opts.dataDir = fullfile(vl_rootnn, 'data') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.sswDir = fullfile(opts.dataDir, 'SSW');
opts.expDir = fullfile(opts.dataDir, 'fast-rcnn-vgg16-pascal07') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.modelPath = fullfile(opts.expDir, 'net-deployed.mat') ;
opts.gpu = [] ;
opts.numFetchThreads = 1 ;
opts.nmsThresh = 0.3 ;
opts.maxPerImage = 100 ;
opts = vl_argparse(opts, varargin) ;
display(opts) ;
if ~exist(opts.expDir,'dir')
mkdir(opts.expDir) ;
end
if ~isempty(opts.gpu)
gpuDevice(opts.gpu)
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = dagnn.DagNN.loadobj(load(opts.modelPath)) ;
net.mode = 'test' ;
if ~isempty(opts.gpu)
net.move('gpu') ;
end
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath,'file')
fprintf('Loading precomputed imdb...\n');
imdb = load(opts.imdbPath) ;
else
fprintf('Obtaining dataset and imdb...\n');
imdb = cnn_setup_data_voc07_ssw(...
'dataDir',opts.dataDir,...
'sswDir',opts.sswDir);
save(opts.imdbPath,'-struct', 'imdb','-v7.3');
end
fprintf('done\n');
bopts.averageImage = net.meta.normalization.averageImage;
bopts.useGpu = numel(opts.gpu) > 0 ;
bopts.maxScale = 1000;
bopts.bgLabel = 21;
bopts.visualize = 0;
bopts.scale = 600;
bopts.interpolation = net.meta.normalization.interpolation;
bopts.numThreads = opts.numFetchThreads;
% -------------------------------------------------------------------------
% Evaluate
% -------------------------------------------------------------------------
VOCinit;
VOCopts.testset='test';
testIdx = find(imdb.images.set == 3) ;
cls_probs = cell(1,numel(testIdx)) ;
box_deltas = cell(1,numel(testIdx)) ;
boxscores_nms = cell(numel(VOCopts.classes),numel(testIdx)) ;
ids = cell(numel(VOCopts.classes),numel(testIdx)) ;
dataVar = 'input' ;
probVarI = net.getVarIndex('probcls') ;
boxVarI = net.getVarIndex('predbbox') ;
if isnan(probVarI)
dataVar = 'data' ;
probVarI = net.getVarIndex('cls_prob') ;
boxVarI = net.getVarIndex('bbox_pred') ;
end
net.vars(probVarI).precious = true ;
net.vars(boxVarI).precious = true ;
start = tic ;
for t=1:numel(testIdx)
speed = t/toc(start) ;
fprintf('Image %d of %d (%.f HZ)\n', t, numel(testIdx), speed) ;
batch = testIdx(t);
inputs = getBatch(bopts, imdb, batch);
inputs{1} = dataVar ;
net.eval(inputs) ;
cls_probs{t} = squeeze(gather(net.vars(probVarI).value)) ;
box_deltas{t} = squeeze(gather(net.vars(boxVarI).value)) ;
end
% heuristic: keep an average of 40 detections per class per images prior
% to NMS
max_per_set = 40 * numel(testIdx);
% detection thresold for each class (this is adaptively set based on the
% max_per_set constraint)
cls_thresholds = zeros(1,numel(VOCopts.classes));
cls_probs_concat = horzcat(cls_probs{:});
for c = 1:numel(VOCopts.classes)
q = find(strcmp(VOCopts.classes{c}, net.meta.classes.name)) ;
so = sort(cls_probs_concat(q,:),'descend');
cls_thresholds(q) = so(min(max_per_set,numel(so)));
fprintf('Applying NMS for %s\n',VOCopts.classes{c});
for t=1:numel(testIdx)
si = find(cls_probs{t}(q,:) >= cls_thresholds(q)) ;
if isempty(si), continue; end
cls_prob = cls_probs{t}(q,si)';
pbox = imdb.boxes.pbox{testIdx(t)}(si,:);
% back-transform bounding box corrections
delta = box_deltas{t}(4*(q-1)+1:4*q,si)';
pred_box = bbox_transform_inv(pbox, delta);
im_size = imdb.images.size(testIdx(t),[2 1]);
pred_box = bbox_clip(round(pred_box), im_size);
% Threshold. Heuristic: keep at most 100 detection per class per image
% prior to NMS.
boxscore = [pred_box cls_prob];
[~,si] = sort(boxscore(:,5),'descend');
boxscore = boxscore(si,:);
boxscore = boxscore(1:min(size(boxscore,1),opts.maxPerImage),:);
% NMS
pick = bbox_nms(double(boxscore),opts.nmsThresh);
boxscores_nms{c,t} = boxscore(pick,:) ;
ids{c,t} = repmat({imdb.images.name{testIdx(t)}(1:end-4)},numel(pick),1) ;
if 0
figure(1) ; clf ;
idx = boxscores_nms{c,t}(:,5)>0.5;
if sum(idx)==0, continue; end
bbox_draw(imread(fullfile(imdb.imageDir,imdb.images.name{testIdx(t)})), ...
boxscores_nms{c,t}(idx,:)) ;
title(net.meta.classes.name{q}) ;
drawnow ;
pause;
%keyboard
end
end
end
%% PASCAL VOC evaluation
VOCdevkitPath = fullfile(vl_rootnn,'data','VOCdevkit');
aps = zeros(numel(VOCopts.classes),1);
% fix voc folders
VOCopts.imgsetpath = fullfile(VOCdevkitPath,'VOC2007','ImageSets','Main','%s.txt');
VOCopts.annopath = fullfile(VOCdevkitPath,'VOC2007','Annotations','%s.xml');
VOCopts.localdir = fullfile(VOCdevkitPath,'local','VOC2007');
VOCopts.detrespath = fullfile(VOCdevkitPath, 'results', 'VOC2007', 'Main', ['%s_det_', VOCopts.testset, '_%s.txt']);
% write det results to txt files
for c=1:numel(VOCopts.classes)
fid = fopen(sprintf(VOCopts.detrespath,'comp3',VOCopts.classes{c}),'w');
for i=1:numel(testIdx)
if isempty(boxscores_nms{c,i}), continue; end
dets = boxscores_nms{c,i};
for j=1:size(dets,1)
fprintf(fid,'%s %.6f %d %d %d %d\n', ...
imdb.images.name{testIdx(i)}(1:end-4), ...
dets(j,5),dets(j,1:4)) ;
end
end
fclose(fid);
[rec,prec,ap] = VOCevaldet(VOCopts,'comp3',VOCopts.classes{c},0);
fprintf('%s ap %.1f\n',VOCopts.classes{c},100*ap);
aps(c) = ap;
end
fprintf('mean ap %.1f\n',100*mean(aps));
% --------------------------------------------------------------------
function inputs = getBatch(opts, imdb, batch)
% --------------------------------------------------------------------
if isempty(batch)
return;
end
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
opts.prefetch = (nargout == 0);
[im,rois] = fast_rcnn_eval_get_batch(images, imdb, batch, opts);
rois = single(rois);
if opts.useGpu > 0
im = gpuArray(im) ;
rois = gpuArray(rois) ;
end
inputs = {'input', im, 'rois', rois} ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_cifar.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/cifar/cnn_cifar.m
| 5,334 |
utf_8
|
eb9aa887d804ee635c4295a7a397206f
|
function [net, info] = cnn_cifar(varargin)
% CNN_CIFAR Demonstrates MatConvNet on CIFAR-10
% The demo includes two standard model: LeNet and Network in
% Network (NIN). Use the 'modelType' option to choose one.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.modelType = 'lenet' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.expDir = fullfile(vl_rootnn, 'data', ...
sprintf('cifar-%s', opts.modelType)) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data','cifar') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.whitenData = true ;
opts.contrastNormalization = true ;
opts.networkType = 'simplenn' ;
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare model and data
% -------------------------------------------------------------------------
switch opts.modelType
case 'lenet'
net = cnn_cifar_init('networkType', opts.networkType) ;
case 'nin'
net = cnn_cifar_init_nin('networkType', opts.networkType) ;
otherwise
error('Unknown model type ''%s''.', opts.modelType) ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getCifarImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = imdb.meta.classes(:)' ;
% -------------------------------------------------------------------------
% Train
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% -------------------------------------------------------------------------
function fn = getBatch(opts)
% -------------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% -------------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
% -------------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% -------------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if rand > 0.5, images=fliplr(images) ; end
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% -------------------------------------------------------------------------
function imdb = getCifarImdb(opts)
% -------------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
unpackPath = fullfile(opts.dataDir, 'cifar-10-batches-mat');
files = [arrayfun(@(n) sprintf('data_batch_%d.mat', n), 1:5, 'UniformOutput', false) ...
{'test_batch.mat'}];
files = cellfun(@(fn) fullfile(unpackPath, fn), files, 'UniformOutput', false);
file_set = uint8([ones(1, 5), 3]);
if any(cellfun(@(fn) ~exist(fn, 'file'), files))
url = 'http://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz' ;
fprintf('downloading %s\n', url) ;
untar(url, opts.dataDir) ;
end
data = cell(1, numel(files));
labels = cell(1, numel(files));
sets = cell(1, numel(files));
for fi = 1:numel(files)
fd = load(files{fi}) ;
data{fi} = permute(reshape(fd.data',32,32,3,[]),[2 1 3 4]) ;
labels{fi} = fd.labels' + 1; % Index from 1
sets{fi} = repmat(file_set(fi), size(labels{fi}));
end
set = cat(2, sets{:});
data = single(cat(4, data{:}));
% remove mean in any case
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean);
% normalize by image mean and std as suggested in `An Analysis of
% Single-Layer Networks in Unsupervised Feature Learning` Adam
% Coates, Honglak Lee, Andrew Y. Ng
if opts.contrastNormalization
z = reshape(data,[],60000) ;
z = bsxfun(@minus, z, mean(z,1)) ;
n = std(z,0,1) ;
z = bsxfun(@times, z, mean(n) ./ max(n, 40)) ;
data = reshape(z, 32, 32, 3, []) ;
end
if opts.whitenData
z = reshape(data,[],60000) ;
W = z(:,set == 1)*z(:,set == 1)'/60000 ;
[V,D] = eig(W) ;
% the scale is selected to approximately preserve the norm of W
d2 = diag(D) ;
en = sqrt(mean(d2)) ;
z = V*diag(en./max(sqrt(d2), 10))*V'*z ;
data = reshape(z, 32, 32, 3, []) ;
end
clNames = load(fullfile(unpackPath, 'batches.meta.mat'));
imdb.images.data = data ;
imdb.images.labels = single(cat(2, labels{:})) ;
imdb.images.set = set;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = clNames.label_names;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_cifar_init_nin.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/cifar/cnn_cifar_init_nin.m
| 5,561 |
utf_8
|
aca711e04a8cd82821f658922218368c
|
function net = cnn_cifar_init_nin(varargin)
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
% CIFAR-10 model from
% M. Lin, Q. Chen, and S. Yan. Network in network. CoRR,
% abs/1312.4400, 2013.
%
% It reproduces the NIN + Dropout result of Table 1 (<= 10.41% top1 error).
net.layers = {} ;
lr = [1 10] ;
% Block 1
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv1', ...
'weights', {init_weights(5,3,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp1', ...
'weights', {init_weights(1,192,160)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp1') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp2', ...
'weights', {init_weights(1,160,96)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp2') ;
net.layers{end+1} = struct('name', 'pool1', ...
'type', 'pool', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout1', 'rate', 0.5) ;
% Block 2
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv2', ...
'weights', {init_weights(5,96,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 2) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu2') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp3', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp4', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp4') ;
net.layers{end+1} = struct('name', 'pool2', ...
'type', 'pool', ...
'method', 'avg', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'dropout', 'name', 'dropout2', 'rate', 0.5) ;
% Block 3
net.layers{end+1} = struct('type', 'conv', ...
'name', 'conv3', ...
'weights', {init_weights(3,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 1) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu3') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp5', ...
'weights', {init_weights(1,192,192)}, ...
'learningRate', lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp5') ;
net.layers{end+1} = struct('type', 'conv', ...
'name', 'cccp6', ...
'weights', {init_weights(1,192,10)}, ...
'learningRate', 0.001*lr, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end}.weights{1} = 0.1 * net.layers{end}.weights{1} ;
%net.layers{end+1} = struct('type', 'relu', 'name', 'relu_cccp6') ;
net.layers{end+1} = struct('type', 'pool', ...
'name', 'pool3', ...
'method', 'avg', ...
'pool', [7 7], ...
'stride', 1, ...
'pad', 0) ;
% Loss layer
net.layers{end+1} = struct('type', 'softmaxloss') ;
% Meta parameters
net.meta.inputSize = [32 32 3] ;
net.meta.trainOpts.learningRate = [0.002, 0.01, 0.02, 0.04 * ones(1,80), 0.004 * ones(1,10), 0.0004 * ones(1,10)] ;
net.meta.trainOpts.weightDecay = 0.0005 ;
net.meta.trainOpts.batchSize = 100 ;
net.meta.trainOpts.numEpochs = numel(net.meta.trainOpts.learningRate) ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('error', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'error') ;
otherwise
assert(false) ;
end
function weights = init_weights(k,m,n)
weights{1} = randn(k,k,m,n,'single') * sqrt(2/(k*k*m)) ;
weights{2} = zeros(n,1,'single') ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_imagenet_init_resnet.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/imagenet/cnn_imagenet_init_resnet.m
| 6,717 |
utf_8
|
aa905a97830e90dc7d33f75ad078301e
|
function net = cnn_imagenet_init_resnet(varargin)
%CNN_IMAGENET_INIT_RESNET Initialize the ResNet-50 model for ImageNet classification
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts = vl_argparse(opts, varargin) ;
net = dagnn.DagNN() ;
lastAdded.var = 'input' ;
lastAdded.depth = 3 ;
function Conv(name, ksize, depth, varargin)
% Helper function to add a Convolutional + BatchNorm + ReLU
% sequence to the network.
args.relu = true ;
args.downsample = false ;
args.bias = false ;
args = vl_argparse(args, varargin) ;
if args.downsample, stride = 2 ; else stride = 1 ; end
if args.bias, pars = {[name '_f'], [name '_b']} ; else pars = {[name '_f']} ; end
net.addLayer([name '_conv'], ...
dagnn.Conv('size', [ksize ksize lastAdded.depth depth], ...
'stride', stride, ....
'pad', (ksize - 1) / 2, ...
'hasBias', args.bias, ...
'opts', {'cudnnworkspacelimit', opts.cudnnWorkspaceLimit}), ...
lastAdded.var, ...
[name '_conv'], ...
pars) ;
net.addLayer([name '_bn'], ...
dagnn.BatchNorm('numChannels', depth, 'epsilon', 1e-5), ...
[name '_conv'], ...
[name '_bn'], ...
{[name '_bn_w'], [name '_bn_b'], [name '_bn_m']}) ;
lastAdded.depth = depth ;
lastAdded.var = [name '_bn'] ;
if args.relu
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
lastAdded.var, ...
[name '_relu']) ;
lastAdded.var = [name '_relu'] ;
end
end
% -------------------------------------------------------------------------
% Add input section
% -------------------------------------------------------------------------
Conv('conv1', 7, 64, ...
'relu', true, ...
'bias', false, ...
'downsample', true) ;
net.addLayer(...
'conv1_pool' , ...
dagnn.Pooling('poolSize', [3 3], ...
'stride', 2, ...
'pad', 1, ...
'method', 'max'), ...
lastAdded.var, ...
'conv1') ;
lastAdded.var = 'conv1' ;
% -------------------------------------------------------------------------
% Add intermediate sections
% -------------------------------------------------------------------------
for s = 2:5
switch s
case 2, sectionLen = 3 ;
case 3, sectionLen = 4 ; % 8 ;
case 4, sectionLen = 6 ; % 23 ; % 36 ;
case 5, sectionLen = 3 ;
end
% -----------------------------------------------------------------------
% Add intermediate segments for each section
for l = 1:sectionLen
depth = 2^(s+4) ;
sectionInput = lastAdded ;
name = sprintf('conv%d_%d', s, l) ;
% Optional adapter layer
if l == 1
Conv([name '_adapt_conv'], 1, 2^(s+6), 'downsample', s >= 3, 'relu', false) ;
end
sumInput = lastAdded ;
% ABC: 1x1, 3x3, 1x1; downsample if first segment in section from
% section 2 onwards.
lastAdded = sectionInput ;
%Conv([name 'a'], 1, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
%Conv([name 'b'], 3, 2^(s+4)) ;
Conv([name 'a'], 1, 2^(s+4)) ;
Conv([name 'b'], 3, 2^(s+4), 'downsample', (s >= 3) & l == 1) ;
Conv([name 'c'], 1, 2^(s+6), 'relu', false) ;
% Sum layer
net.addLayer([name '_sum'] , ...
dagnn.Sum(), ...
{sumInput.var, lastAdded.var}, ...
[name '_sum']) ;
net.addLayer([name '_relu'] , ...
dagnn.ReLU(), ...
[name '_sum'], ...
name) ;
lastAdded.var = name ;
end
end
net.addLayer('prediction_avg' , ...
dagnn.Pooling('poolSize', [7 7], 'method', 'avg'), ...
lastAdded.var, ...
'prediction_avg') ;
net.addLayer('prediction' , ...
dagnn.Conv('size', [1 1 2048 1000]), ...
'prediction_avg', ...
'prediction', ...
{'prediction_f', 'prediction_b'}) ;
net.addLayer('loss', ...
dagnn.Loss('loss', 'softmaxlog') ,...
{'prediction', 'label'}, ...
'objective') ;
net.addLayer('top1error', ...
dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, ...
'top1error') ;
net.addLayer('top5error', ...
dagnn.Loss('loss', 'topkerror', 'opts', {'topK', 5}), ...
{'prediction', 'label'}, ...
'top5error') ;
% -------------------------------------------------------------------------
% Meta parameters
% -------------------------------------------------------------------------
net.meta.normalization.imageSize = [224 224 3] ;
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions ;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [3/4, 4/3] ;
net.meta.augmentation.jitterScale = [0.4, 1.1] ;
%net.meta.augmentation.jitterSaturation = 0.4 ;
%net.meta.augmentation.jitterContrast = 0.4 ;
net.meta.inputSize = {'input', [net.meta.normalization.imageSize 32]} ;
%lr = logspace(-1, -3, 60) ;
lr = [0.1 * ones(1,30), 0.01*ones(1,30), 0.001*ones(1,30)] ;
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.momentum = 0.9 ;
net.meta.trainOpts.batchSize = 256 ;
net.meta.trainOpts.numSubBatches = 4 ;
net.meta.trainOpts.weightDecay = 0.0001 ;
% Init parameters randomly
net.initParams() ;
% For uniformity with the other ImageNet networks, t
% the input data is *not* normalized to have unit standard deviation,
% whereas this is enforced by batch normalization deeper down.
% The ImageNet standard deviation (for each of R, G, and B) is about 60, so
% we adjust the weights and learing rate accordingly in the first layer.
%
% This simple change improves performance almost +1% top 1 error.
p = net.getParamIndex('conv1_f') ;
net.params(p).value = net.params(p).value / 100 ;
net.params(p).learningRate = net.params(p).learningRate / 100^2 ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, 'dagnn.BatchNorm')
k = net.getParamIndex(net.layers(l).params{3}) ;
net.params(k).learningRate = 0.3 ;
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_imagenet_init.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/imagenet/cnn_imagenet_init.m
| 15,279 |
utf_8
|
43bffc7ab4042d49c4f17c0e44c36bf9
|
function net = cnn_imagenet_init(varargin)
% CNN_IMAGENET_INIT Initialize a standard CNN for ImageNet
opts.scale = 1 ;
opts.initBias = 0 ;
opts.weightDecay = 1 ;
%opts.weightInitMethod = 'xavierimproved' ;
opts.weightInitMethod = 'gaussian' ;
opts.model = 'alexnet' ;
opts.batchNormalization = false ;
opts.networkType = 'simplenn' ;
opts.cudnnWorkspaceLimit = 1024*1024*1204 ; % 1GB
opts.classNames = {} ;
opts.classDescriptions = {} ;
opts.averageImage = zeros(3,1) ;
opts.colorDeviation = zeros(3) ;
opts = vl_argparse(opts, varargin) ;
% Define layers
switch opts.model
case 'alexnet'
net.meta.normalization.imageSize = [227, 227, 3] ;
net = alexnet(net, opts) ;
bs = 256 ;
case 'vgg-f'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_f(net, opts) ;
bs = 256 ;
case {'vgg-m', 'vgg-m-1024'}
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_m(net, opts) ;
bs = 196 ;
case 'vgg-s'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_s(net, opts) ;
bs = 128 ;
case 'vgg-vd-16'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 32 ;
case 'vgg-vd-19'
net.meta.normalization.imageSize = [224, 224, 3] ;
net = vgg_vd(net, opts) ;
bs = 24 ;
otherwise
error('Unknown model ''%s''', opts.model) ;
end
% final touches
switch lower(opts.weightInitMethod)
case {'xavier', 'xavierimproved'}
net.layers{end}.weights{1} = net.layers{end}.weights{1} / 10 ;
end
net.layers{end+1} = struct('type', 'softmaxloss', 'name', 'loss') ;
% Meta parameters
net.meta.inputSize = [net.meta.normalization.imageSize, 32] ;
net.meta.normalization.cropSize = net.meta.normalization.imageSize(1) / 256 ;
net.meta.normalization.averageImage = opts.averageImage ;
net.meta.classes.name = opts.classNames ;
net.meta.classes.description = opts.classDescriptions;
net.meta.augmentation.jitterLocation = true ;
net.meta.augmentation.jitterFlip = true ;
net.meta.augmentation.jitterBrightness = double(0.1 * opts.colorDeviation) ;
net.meta.augmentation.jitterAspect = [2/3, 3/2] ;
if ~opts.batchNormalization
lr = logspace(-2, -4, 60) ;
else
lr = logspace(-1, -4, 20) ;
end
net.meta.trainOpts.learningRate = lr ;
net.meta.trainOpts.numEpochs = numel(lr) ;
net.meta.trainOpts.batchSize = bs ;
net.meta.trainOpts.weightDecay = 0.0005 ;
% Fill in default values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction','label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{'prediction','label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = add_block(net, opts, id, h, w, in, out, stride, pad)
% --------------------------------------------------------------------
info = vl_simplenn_display(net) ;
fc = (h == info.dataSize(1,end) && w == info.dataSize(2,end)) ;
if fc
name = 'fc' ;
else
name = 'conv' ;
end
convOpts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit} ;
net.layers{end+1} = struct('type', 'conv', 'name', sprintf('%s%s', name, id), ...
'weights', {{init_weight(opts, h, w, in, out, 'single'), ...
ones(out, 1, 'single')*opts.initBias}}, ...
'stride', stride, ...
'pad', pad, ...
'dilate', 1, ...
'learningRate', [1 2], ...
'weightDecay', [opts.weightDecay 0], ...
'opts', {convOpts}) ;
if opts.batchNormalization
net.layers{end+1} = struct('type', 'bnorm', 'name', sprintf('bn%s',id), ...
'weights', {{ones(out, 1, 'single'), zeros(out, 1, 'single'), ...
zeros(out, 2, 'single')}}, ...
'epsilon', 1e-4, ...
'learningRate', [2 1 0.1], ...
'weightDecay', [0 0]) ;
end
net.layers{end+1} = struct('type', 'relu', 'name', sprintf('relu%s',id)) ;
% -------------------------------------------------------------------------
function weights = init_weight(opts, h, w, in, out, type)
% -------------------------------------------------------------------------
% See K. He, X. Zhang, S. Ren, and J. Sun. Delving deep into
% rectifiers: Surpassing human-level performance on imagenet
% classification. CoRR, (arXiv:1502.01852v1), 2015.
switch lower(opts.weightInitMethod)
case 'gaussian'
sc = 0.01/opts.scale ;
weights = randn(h, w, in, out, type)*sc;
case 'xavier'
sc = sqrt(3/(h*w*in)) ;
weights = (rand(h, w, in, out, type)*2 - 1)*sc ;
case 'xavierimproved'
sc = sqrt(2/(h*w*out)) ;
weights = randn(h, w, in, out, type)*sc ;
otherwise
error('Unknown weight initialization method''%s''', opts.weightInitMethod) ;
end
% --------------------------------------------------------------------
function net = add_norm(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'normalize', ...
'name', sprintf('norm%s', id), ...
'param', [5 1 0.0001/5 0.75]) ;
end
% --------------------------------------------------------------------
function net = add_dropout(net, opts, id)
% --------------------------------------------------------------------
if ~opts.batchNormalization
net.layers{end+1} = struct('type', 'dropout', ...
'name', sprintf('dropout%s', id), ...
'rate', 0.5) ;
end
% --------------------------------------------------------------------
function net = alexnet(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 96, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 48, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 384, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 192, 384, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 192, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_s(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 2 0 2]) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 1, 0) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 3, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_m(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 7, 7, 3, 96, 2, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2', 5, 5, 96, 256, 2, 1) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '3', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 512, 512, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
switch opts.model
case 'vgg-m'
bottleneck = 4096 ;
case 'vgg-m-1024'
bottleneck = 1024 ;
end
net = add_block(net, opts, '7', 1, 1, 4096, bottleneck, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, bottleneck, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_f(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1', 11, 11, 3, 64, 4, 0) ;
net = add_norm(net, opts, '1') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', [0 1 0 1]) ;
net = add_block(net, opts, '2', 5, 5, 64, 256, 1, 2) ;
net = add_norm(net, opts, '2') ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '4', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '5', 3, 3, 256, 256, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [3 3], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 6, 6, 256, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
% --------------------------------------------------------------------
function net = vgg_vd(net, opts)
% --------------------------------------------------------------------
net.layers = {} ;
net = add_block(net, opts, '1_1', 3, 3, 3, 64, 1, 1) ;
net = add_block(net, opts, '1_2', 3, 3, 64, 64, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool1', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '2_1', 3, 3, 64, 128, 1, 1) ;
net = add_block(net, opts, '2_2', 3, 3, 128, 128, 1, 1) ;
net.layers{end+1} = struct('type', 'pool', 'name', 'pool2', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '3_1', 3, 3, 128, 256, 1, 1) ;
net = add_block(net, opts, '3_2', 3, 3, 256, 256, 1, 1) ;
net = add_block(net, opts, '3_3', 3, 3, 256, 256, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '3_4', 3, 3, 256, 256, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool3', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '4_1', 3, 3, 256, 512, 1, 1) ;
net = add_block(net, opts, '4_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '4_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '4_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool4', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '5_1', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_2', 3, 3, 512, 512, 1, 1) ;
net = add_block(net, opts, '5_3', 3, 3, 512, 512, 1, 1) ;
if strcmp(opts.model, 'vgg-vd-19')
net = add_block(net, opts, '5_4', 3, 3, 512, 512, 1, 1) ;
end
net.layers{end+1} = struct('type', 'pool', 'name', 'pool5', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net = add_block(net, opts, '6', 7, 7, 512, 4096, 1, 0) ;
net = add_dropout(net, opts, '6') ;
net = add_block(net, opts, '7', 1, 1, 4096, 4096, 1, 0) ;
net = add_dropout(net, opts, '7') ;
net = add_block(net, opts, '8', 1, 1, 4096, 1000, 1, 0) ;
net.layers(end) = [] ;
if opts.batchNormalization, net.layers(end) = [] ; end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_imagenet.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/imagenet/cnn_imagenet.m
| 6,211 |
utf_8
|
f11556c91bb9796f533c8f624ad8adbd
|
function [net, info] = cnn_imagenet(varargin)
%CNN_IMAGENET Demonstrates training a CNN on ImageNet
% This demo demonstrates training the AlexNet, VGG-F, VGG-S, VGG-M,
% VGG-VD-16, and VGG-VD-19 architectures on ImageNet data.
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile(vl_rootnn, 'data','ILSVRC2012') ;
opts.modelType = 'alexnet' ;
opts.network = [] ;
opts.networkType = 'simplenn' ;
opts.batchNormalization = true ;
opts.weightInitMethod = 'gaussian' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.modelType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
sfx = [sfx '-' opts.networkType] ;
opts.expDir = fullfile(vl_rootnn, 'data', ['imagenet12-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.numFetchThreads = 12 ;
opts.lite = false ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% -------------------------------------------------------------------------
% Prepare data
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% Compute image statistics (mean, RGB covariances, etc.)
imageStatsPath = fullfile(opts.expDir, 'imageStats.mat') ;
if exist(imageStatsPath)
load(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
else
train = find(imdb.images.set == 1) ;
images = fullfile(imdb.imageDir, imdb.images.name(train(1:100:end))) ;
[averageImage, rgbMean, rgbCovariance] = getImageStats(images, ...
'imageSize', [256 256], ...
'numThreads', opts.numFetchThreads, ...
'gpus', opts.train.gpus) ;
save(imageStatsPath, 'averageImage', 'rgbMean', 'rgbCovariance') ;
end
[v,d] = eig(rgbCovariance) ;
rgbDeviation = v*sqrt(d) ;
clear v d ;
% -------------------------------------------------------------------------
% Prepare model
% -------------------------------------------------------------------------
if isempty(opts.network)
switch opts.modelType
case 'resnet-50'
net = cnn_imagenet_init_resnet('averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
opts.networkType = 'dagnn' ;
otherwise
net = cnn_imagenet_init('model', opts.modelType, ...
'batchNormalization', opts.batchNormalization, ...
'weightInitMethod', opts.weightInitMethod, ...
'networkType', opts.networkType, ...
'averageImage', rgbMean, ...
'colorDeviation', rgbDeviation, ...
'classNames', imdb.classes.name, ...
'classDescriptions', imdb.classes.description) ;
end
else
net = opts.network ;
opts.network = [] ;
end
% -------------------------------------------------------------------------
% Learn
% -------------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainFn = @cnn_train ;
case 'dagnn', trainFn = @cnn_train_dag ;
end
[net, info] = trainFn(net, imdb, getBatchFn(opts, net.meta), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train) ;
% -------------------------------------------------------------------------
% Deploy
% -------------------------------------------------------------------------
net = cnn_imagenet_deploy(net) ;
modelPath = fullfile(opts.expDir, 'net-deployed.mat')
switch opts.networkType
case 'simplenn'
save(modelPath, '-struct', 'net') ;
case 'dagnn'
net_ = net.saveobj() ;
save(modelPath, '-struct', 'net_') ;
clear net_ ;
end
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', meta.normalization.cropSize, ...
'subtractAverage', mu) ;
% Copy the parameters for data augmentation
bopts.train = bopts.test ;
for f = fieldnames(meta.augmentation)'
f = char(f) ;
bopts.train.(f) = meta.augmentation.(f) ;
end
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_imagenet_deploy.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/imagenet/cnn_imagenet_deploy.m
| 6,585 |
utf_8
|
2f3e6d216fa697ff9adfce33e75d44d8
|
function net = cnn_imagenet_deploy(net)
%CNN_IMAGENET_DEPLOY Deploy a CNN
isDag = isa(net, 'dagnn.DagNN') ;
if isDag
dagRemoveLayersOfType(net, 'dagnn.Loss') ;
dagRemoveLayersOfType(net, 'dagnn.DropOut') ;
else
net = simpleRemoveLayersOfType(net, 'softmaxloss') ;
net = simpleRemoveLayersOfType(net, 'dropout') ;
end
if isDag
net.addLayer('prob', dagnn.SoftMax(), 'prediction', 'prob', {}) ;
else
net.layers{end+1} = struct('name', 'prob', 'type', 'softmax') ;
end
if isDag
dagMergeBatchNorm(net) ;
dagRemoveLayersOfType(net, 'dagnn.BatchNorm') ;
else
net = simpleMergeBatchNorm(net) ;
net = simpleRemoveLayersOfType(net, 'bnorm') ;
end
if ~isDag
net = simpleRemoveMomentum(net) ;
end
% Switch to use MatConvNet default memory limit for CuDNN (512 MB)
if ~isDag
for l = simpleFindLayersOfType(net, 'conv')
net.layers{l}.opts = removeCuDNNMemoryLimit(net.layers{l}.opts) ;
end
else
for name = dagFindLayersOfType(net, 'dagnn.Conv')
l = net.getLayerIndex(char(name)) ;
net.layers(l).block.opts = removeCuDNNMemoryLimit(net.layers(l).block.opts) ;
end
end
% -------------------------------------------------------------------------
function opts = removeCuDNNMemoryLimit(opts)
% -------------------------------------------------------------------------
remove = false(1, numel(opts)) ;
for i = 1:numel(opts)
if isstr(opts{i}) && strcmp(lower(opts{i}), 'CudnnWorkspaceLimit')
remove([i i+1]) = true ;
end
end
opts = opts(~remove) ;
% -------------------------------------------------------------------------
function net = simpleRemoveMomentum(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if isfield(net.layers{l}, 'momentum')
net.layers{l} = rmfield(net.layers{l}, 'momentum') ;
end
end
% -------------------------------------------------------------------------
function layers = simpleFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = find(cellfun(@(x)strcmp(x.type, type), net.layers)) ;
% -------------------------------------------------------------------------
function net = simpleRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = simpleFindLayersOfType(net, type) ;
net.layers(layers) = [] ;
% -------------------------------------------------------------------------
function layers = dagFindLayersWithOutput(net, outVarName)
% -------------------------------------------------------------------------
layers = {} ;
for l = 1:numel(net.layers)
if any(strcmp(net.layers(l).outputs, outVarName))
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
% -------------------------------------------------------------------------
function dagRemoveLayersOfType(net, type)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, type) ;
for i = 1:numel(names)
layer = net.layers(net.getLayerIndex(names{i})) ;
net.removeLayer(names{i}) ;
net.renameVar(layer.outputs{1}, layer.inputs{1}, 'quiet', true) ;
end
% -------------------------------------------------------------------------
function dagMergeBatchNorm(net)
% -------------------------------------------------------------------------
names = dagFindLayersOfType(net, 'dagnn.BatchNorm') ;
for name = names
name = char(name) ;
layer = net.layers(net.getLayerIndex(name)) ;
% merge into previous conv layer
playerName = dagFindLayersWithOutput(net, layer.inputs{1}) ;
playerName = playerName{1} ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
if ~isa(player.block, 'dagnn.Conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
% if the convolution layer does not have a bias,
% recreate it to have one
if ~player.block.hasBias
block = player.block ;
block.hasBias = true ;
net.renameLayer(playerName, 'tmp') ;
net.addLayer(playerName, ...
block, ...
player.inputs, ...
player.outputs, ...
{player.params{1}, sprintf('%s_b',playerName)}) ;
net.removeLayer('tmp') ;
playerIndex = net.getLayerIndex(playerName) ;
player = net.layers(playerIndex) ;
biases = net.getParamIndex(player.params{2}) ;
net.params(biases).value = zeros(block.size(4), 1, 'single') ;
end
filters = net.getParamIndex(player.params{1}) ;
biases = net.getParamIndex(player.params{2}) ;
multipliers = net.getParamIndex(layer.params{1}) ;
offsets = net.getParamIndex(layer.params{2}) ;
moments = net.getParamIndex(layer.params{3}) ;
[filtersValue, biasesValue] = mergeBatchNorm(...
net.params(filters).value, ...
net.params(biases).value, ...
net.params(multipliers).value, ...
net.params(offsets).value, ...
net.params(moments).value) ;
net.params(filters).value = filtersValue ;
net.params(biases).value = biasesValue ;
end
% -------------------------------------------------------------------------
function net = simpleMergeBatchNorm(net)
% -------------------------------------------------------------------------
for l = 1:numel(net.layers)
if strcmp(net.layers{l}.type, 'bnorm')
if ~strcmp(net.layers{l-1}.type, 'conv')
error('Batch normalization cannot be merged as it is not preceded by a conv layer.') ;
end
[filters, biases] = mergeBatchNorm(...
net.layers{l-1}.weights{1}, ...
net.layers{l-1}.weights{2}, ...
net.layers{l}.weights{1}, ...
net.layers{l}.weights{2}, ...
net.layers{l}.weights{3}) ;
net.layers{l-1}.weights = {filters, biases} ;
end
end
% -------------------------------------------------------------------------
function [filters, biases] = mergeBatchNorm(filters, biases, multipliers, offsets, moments)
% -------------------------------------------------------------------------
% wk / sqrt(sigmak^2 + eps)
% bk - wk muk / sqrt(sigmak^2 + eps)
a = multipliers(:) ./ moments(:,2) ;
b = offsets(:) - moments(:,1) .* a ;
biases(:) = biases(:) + b(:) ;
sz = size(filters) ;
numFilters = sz(4) ;
filters = reshape(bsxfun(@times, reshape(filters, [], numFilters), a'), sz) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_imagenet_evaluate.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/imagenet/cnn_imagenet_evaluate.m
| 5,089 |
utf_8
|
f22247bd3614223cad4301daa91f6bd7
|
function info = cnn_imagenet_evaluate(varargin)
% CNN_IMAGENET_EVALUATE Evauate MatConvNet models on ImageNet
run(fullfile(fileparts(mfilename('fullpath')), ...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.dataDir = fullfile('data', 'ILSVRC2012') ;
opts.expDir = fullfile('data', 'imagenet12-eval-vgg-f') ;
opts.modelPath = fullfile('data', 'models', 'imagenet-vgg-f.mat') ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.networkType = [] ;
opts.lite = false ;
opts.numFetchThreads = 12 ;
opts.train.batchSize = 128 ;
opts.train.numEpochs = 1 ;
opts.train.gpus = [] ;
opts.train.prefetch = true ;
opts.train.expDir = opts.expDir ;
opts = vl_argparse(opts, varargin) ;
display(opts);
% -------------------------------------------------------------------------
% Database initialization
% -------------------------------------------------------------------------
if exist(opts.imdbPath)
imdb = load(opts.imdbPath) ;
imdb.imageDir = fullfile(opts.dataDir, 'images');
else
imdb = cnn_imagenet_setup_data('dataDir', opts.dataDir, 'lite', opts.lite) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
% -------------------------------------------------------------------------
% Network initialization
% -------------------------------------------------------------------------
net = load(opts.modelPath) ;
if isfield(net, 'net') ;
net = net.net ;
end
% Cannot use isa('dagnn.DagNN') because it is not an object yet
isDag = isfield(net, 'params') ;
if isDag
opts.networkType = 'dagnn' ;
net = dagnn.DagNN.loadobj(net) ;
trainfn = @cnn_train_dag ;
% Drop existing loss layers
drop = arrayfun(@(x) isa(x.block,'dagnn.Loss'), net.layers) ;
for n = {net.layers(drop).name}
net.removeLayer(n) ;
end
% Extract raw predictions from softmax
sftmx = arrayfun(@(x) isa(x.block,'dagnn.SoftMax'), net.layers) ;
predVar = 'prediction' ;
for n = {net.layers(sftmx).name}
% check if output
l = net.getLayerIndex(n) ;
v = net.getVarIndex(net.layers(l).outputs{1}) ;
if net.vars(v).fanout == 0
% remove this layer and update prediction variable
predVar = net.layers(l).inputs{1} ;
net.removeLayer(n) ;
end
end
% Add custom objective and loss layers on top of raw predictions
net.addLayer('objective', dagnn.Loss('loss', 'softmaxlog'), ...
{predVar,'label'}, 'objective') ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{predVar,'label'}, 'top1err') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topK',5}), ...
{predVar,'label'}, 'top5err') ;
% Make sure that the input is called 'input'
v = net.getVarIndex('data') ;
if ~isnan(v)
net.renameVar('data', 'input') ;
end
% Swtich to test mode
net.mode = 'test' ;
else
opts.networkType = 'simplenn' ;
net = vl_simplenn_tidy(net) ;
trainfn = @cnn_train ;
net.layers{end}.type = 'softmaxloss' ; % softmax -> softmaxloss
end
% Synchronize label indexes used in IMDB with the ones used in NET
imdb = cnn_imagenet_sync_labels(imdb, net);
% Run evaluation
[net, info] = trainfn(net, imdb, getBatchFn(opts, net.meta), ...
opts.train, ...
'train', NaN, ...
'val', find(imdb.images.set==2)) ;
% -------------------------------------------------------------------------
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
if isfield(meta.normalization, 'keepAspect')
keepAspect = meta.normalization.keepAspect ;
else
keepAspect = true ;
end
if numel(meta.normalization.averageImage) == 3
mu = double(meta.normalization.averageImage(:)) ;
else
mu = imresize(single(meta.normalization.averageImage), ...
meta.normalization.imageSize(1:2)) ;
end
useGpu = numel(opts.train.gpus) > 0 ;
bopts.test = struct(...
'useGpu', useGpu, ...
'numThreads', opts.numFetchThreads, ...
'imageSize', meta.normalization.imageSize(1:2), ...
'cropSize', max(meta.normalization.imageSize(1:2)) / 256, ...
'subtractAverage', mu, ...
'keepAspect', keepAspect) ;
fn = @(x,y) getBatch(bopts,useGpu,lower(opts.networkType),x,y) ;
% -------------------------------------------------------------------------
function varargout = getBatch(opts, useGpu, networkType, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
if ~isempty(batch) && imdb.images.set(batch(1)) == 1
phase = 'train' ;
else
phase = 'test' ;
end
data = getImageBatch(images, opts.(phase), 'prefetch', nargout == 0) ;
if nargout > 0
labels = imdb.images.label(batch) ;
switch networkType
case 'simplenn'
varargout = {data, labels} ;
case 'dagnn'
varargout{1} = {'input', data, 'label', labels} ;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_mnist_init.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/mnist/cnn_mnist_init.m
| 3,111 |
utf_8
|
367b1185af58e108aec40b61818ec6e7
|
function net = cnn_mnist_init(varargin)
% CNN_MNIST_LENET Initialize a CNN similar for MNIST
opts.batchNormalization = true ;
opts.networkType = 'simplenn' ;
opts = vl_argparse(opts, varargin) ;
rng('default');
rng(0) ;
f=1/100 ;
net.layers = {} ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,1,20, 'single'), zeros(1, 20, 'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(5,5,20,50, 'single'),zeros(1,50,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'pool', ...
'method', 'max', ...
'pool', [2 2], ...
'stride', 2, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(4,4,50,500, 'single'), zeros(1,500,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'relu') ;
net.layers{end+1} = struct('type', 'conv', ...
'weights', {{f*randn(1,1,500,10, 'single'), zeros(1,10,'single')}}, ...
'stride', 1, ...
'pad', 0) ;
net.layers{end+1} = struct('type', 'softmaxloss') ;
% optionally switch to batch normalization
if opts.batchNormalization
net = insertBnorm(net, 1) ;
net = insertBnorm(net, 4) ;
net = insertBnorm(net, 7) ;
end
% Meta parameters
net.meta.inputSize = [28 28 1] ;
net.meta.trainOpts.learningRate = 0.001 ;
net.meta.trainOpts.numEpochs = 20 ;
net.meta.trainOpts.batchSize = 100 ;
% Fill in defaul values
net = vl_simplenn_tidy(net) ;
% Switch to DagNN if requested
switch lower(opts.networkType)
case 'simplenn'
% done
case 'dagnn'
net = dagnn.DagNN.fromSimpleNN(net, 'canonicalNames', true) ;
net.addLayer('top1err', dagnn.Loss('loss', 'classerror'), ...
{'prediction', 'label'}, 'error') ;
net.addLayer('top5err', dagnn.Loss('loss', 'topkerror', ...
'opts', {'topk', 5}), {'prediction', 'label'}, 'top5err') ;
otherwise
assert(false) ;
end
% --------------------------------------------------------------------
function net = insertBnorm(net, l)
% --------------------------------------------------------------------
assert(isfield(net.layers{l}, 'weights'));
ndim = size(net.layers{l}.weights{1}, 4);
layer = struct('type', 'bnorm', ...
'weights', {{ones(ndim, 1, 'single'), zeros(ndim, 1, 'single')}}, ...
'learningRate', [1 1 0.05], ...
'weightDecay', [0 0]) ;
net.layers{l}.biases = [] ;
net.layers = horzcat(net.layers(1:l), layer, net.layers(l+1:end)) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
cnn_mnist.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/examples/mnist/cnn_mnist.m
| 4,662 |
utf_8
|
39844185155240d4f0ebfcf8db493148
|
function [net, info] = cnn_mnist(varargin)
%CNN_MNIST Demonstrates MatConvNet on MNIST
run(fullfile(fileparts(mfilename('fullpath')),...
'..', '..', 'matlab', 'vl_setupnn.m')) ;
opts.batchNormalization = false ;
opts.network = [] ;
% opts.networkType = 'simplenn' ; % dagnn, simplenn
opts.networkType = 'dagnn' ;
[opts, varargin] = vl_argparse(opts, varargin) ;
sfx = opts.networkType ;
if opts.batchNormalization, sfx = [sfx '-bnorm'] ; end
opts.expDir = fullfile(vl_rootnn, 'data', ['mnist-baseline-' sfx]) ;
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.dataDir = fullfile(vl_rootnn, 'data', 'mnist') ;
opts.imdbPath = fullfile(opts.expDir, 'imdb.mat');
opts.train = struct() ;
opts = vl_argparse(opts, varargin) ;
if ~isfield(opts.train, 'gpus'), opts.train.gpus = []; end;
% --------------------------------------------------------------------
% Prepare data
% --------------------------------------------------------------------
if isempty(opts.network)
net = cnn_mnist_init('batchNormalization', opts.batchNormalization, ...
'networkType', opts.networkType) ;
else
net = opts.network ;
opts.network = [] ;
end
if exist(opts.imdbPath, 'file')
imdb = load(opts.imdbPath) ;
else
imdb = getMnistImdb(opts) ;
mkdir(opts.expDir) ;
save(opts.imdbPath, '-struct', 'imdb') ;
end
net.meta.classes.name = arrayfun(@(x)sprintf('%d',x),1:10,'UniformOutput',false) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
switch opts.networkType
case 'simplenn', trainfn = @cnn_train ;
case 'dagnn', trainfn = @cnn_train_dag ;
end
[net, info] = trainfn(net, imdb, getBatch(opts), ...
'expDir', opts.expDir, ...
net.meta.trainOpts, ...
opts.train, ...
'val', find(imdb.images.set == 3)) ;
% --------------------------------------------------------------------
function fn = getBatch(opts)
% --------------------------------------------------------------------
switch lower(opts.networkType)
case 'simplenn'
fn = @(x,y) getSimpleNNBatch(x,y) ;
case 'dagnn'
bopts = struct('numGpus', numel(opts.train.gpus)) ;
fn = @(x,y) getDagNNBatch(bopts,x,y) ;
end
% --------------------------------------------------------------------
function [images, labels] = getSimpleNNBatch(imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
% --------------------------------------------------------------------
function inputs = getDagNNBatch(opts, imdb, batch)
% --------------------------------------------------------------------
images = imdb.images.data(:,:,:,batch) ;
labels = imdb.images.labels(1,batch) ;
if opts.numGpus > 0
images = gpuArray(images) ;
end
inputs = {'input', images, 'label', labels} ;
% --------------------------------------------------------------------
function imdb = getMnistImdb(opts)
% --------------------------------------------------------------------
% Preapre the imdb structure, returns image data with mean image subtracted
files = {'train-images-idx3-ubyte', ...
'train-labels-idx1-ubyte', ...
't10k-images-idx3-ubyte', ...
't10k-labels-idx1-ubyte'} ;
if ~exist(opts.dataDir, 'dir')
mkdir(opts.dataDir) ;
end
for i=1:4
if ~exist(fullfile(opts.dataDir, files{i}), 'file')
url = sprintf('http://yann.lecun.com/exdb/mnist/%s.gz',files{i}) ;
fprintf('downloading %s\n', url) ;
gunzip(url, opts.dataDir) ;
end
end
f=fopen(fullfile(opts.dataDir, 'train-images-idx3-ubyte'),'r') ;
x1=fread(f,inf,'uint8');
fclose(f) ;
x1=permute(reshape(x1(17:end),28,28,60e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 't10k-images-idx3-ubyte'),'r') ;
x2=fread(f,inf,'uint8');
fclose(f) ;
x2=permute(reshape(x2(17:end),28,28,10e3),[2 1 3]) ;
f=fopen(fullfile(opts.dataDir, 'train-labels-idx1-ubyte'),'r') ;
y1=fread(f,inf,'uint8');
fclose(f) ;
y1=double(y1(9:end)')+1 ;
f=fopen(fullfile(opts.dataDir, 't10k-labels-idx1-ubyte'),'r') ;
y2=fread(f,inf,'uint8');
fclose(f) ;
y2=double(y2(9:end)')+1 ;
set = [ones(1,numel(y1)) 3*ones(1,numel(y2))];
data = single(reshape(cat(3, x1, x2),28,28,1,[]));
dataMean = mean(data(:,:,:,set == 1), 4);
data = bsxfun(@minus, data, dataMean) ;
imdb.images.data = data ;
imdb.images.data_mean = dataMean;
imdb.images.labels = cat(2, y1, y2) ;
imdb.images.set = set ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = arrayfun(@(x)sprintf('%d',x),0:9,'uniformoutput',false) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_nnloss.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/vl_nnloss.m
| 12,021 |
utf_8
|
1f4bacf5f0df0f547019f23730c5f742
|
function y = vl_nnloss(x,c,dzdy,varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logisticlog`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
%
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
hasIgnoreLabel = any(c(:) == 0);
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
% disp(labelSize);
% disp(inputSize);
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights)
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
else
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
ci = unique(ci);
y(ci) = y(ci) - 1 ; % CUDA execution problem -- not unique values in large input
% y = gather(y);
% y(ci) = y(ci) - 1;
% y = gpuArray(y);
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_compilenn.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/vl_compilenn.m
| 30,050 |
utf_8
|
6339b625106e6c7b479e57c2b9aa578e
|
function vl_compilenn(varargin)
%VL_COMPILENN Compile the MatConvNet toolbox.
% The `vl_compilenn()` function compiles the MEX files in the
% MatConvNet toolbox. See below for the requirements for compiling
% CPU and GPU code, respectively.
%
% `vl_compilenn('OPTION', ARG, ...)` accepts the following options:
%
% `EnableGpu`:: `false`
% Set to true in order to enable GPU support.
%
% `Verbose`:: 0
% Set the verbosity level (0, 1 or 2).
%
% `Debug`:: `false`
% Set to true to compile the binaries with debugging
% information.
%
% `CudaMethod`:: Linux & Mac OS X: `mex`; Windows: `nvcc`
% Choose the method used to compile the CUDA code. There are two
% methods:
%
% * The **`mex`** method uses the MATLAB MEX command with the
% configuration file
% `<MatConvNet>/matlab/src/config/mex_CUDA_<arch>.[sh/xml]`
% This configuration file is in XML format since MATLAB 8.3
% (R2014a) and is a Shell script for earlier versions. This
% is, principle, the preferred method as it uses the
% MATLAB-sanctioned compiler options.
%
% * The **`nvcc`** method calls the NVIDIA CUDA compiler `nvcc`
% directly to compile CUDA source code into object files.
%
% This method allows to use a CUDA toolkit version that is not
% the one that officially supported by a particular MATALB
% version (see below). It is also the default method for
% compilation under Windows and with CuDNN.
%
% `CudaRoot`:: guessed automatically
% This option specifies the path to the CUDA toolkit to use for
% compilation.
%
% `EnableImreadJpeg`:: `true`
% Set this option to `true` to compile `vl_imreadjpeg`.
%
% `EnableDouble`:: `true`
% Set this option to `true` to compile the support for DOUBLE
% data types.
%
% `ImageLibrary`:: `libjpeg` (Linux), `gdiplus` (Windows), `quartz` (Mac)
% The image library to use for `vl_impreadjpeg`.
%
% `ImageLibraryCompileFlags`:: platform dependent
% A cell-array of additional flags to use when compiling
% `vl_imreadjpeg`.
%
% `ImageLibraryLinkFlags`:: platform dependent
% A cell-array of additional flags to use when linking
% `vl_imreadjpeg`.
%
% `EnableCudnn`:: `false`
% Set to `true` to compile CuDNN support. See CuDNN
% documentation for the Hardware/CUDA version requirements.
%
% `CudnnRoot`:: `'local/'`
% Directory containing the unpacked binaries and header files of
% the CuDNN library.
%
% ## Compiling the CPU code
%
% By default, the `EnableGpu` option is switched to off, such that
% the GPU code support is not compiled in.
%
% Generally, you only need a 64bit C/C++ compiler (usually Xcode, GCC or
% Visual Studio for Mac, Linux, and Windows respectively). The
% compiler can be setup in MATLAB using the
%
% mex -setup
%
% command.
%
% ## Compiling the GPU code
%
% In order to compile the GPU code, set the `EnableGpu` option to
% `true`. For this to work you will need:
%
% * To satisfy all the requirements to compile the CPU code (see
% above).
%
% * A NVIDIA GPU with at least *compute capability 2.0*.
%
% * The *MATALB Parallel Computing Toolbox*. This can be purchased
% from Mathworks (type `ver` in MATLAB to see if this toolbox is
% already comprised in your MATLAB installation; it often is).
%
% * A copy of the *CUDA Devkit*, which can be downloaded for free
% from NVIDIA. Note that each MATLAB version requires a
% particular CUDA Devkit version:
%
% | MATLAB version | Release | CUDA Devkit |
% |----------------|---------|--------------|
% | 8.2 | 2013b | 5.5 |
% | 8.3 | 2014a | 5.5 |
% | 8.4 | 2014b | 6.0 |
% | 8.6 | 2015b | 7.0 |
% | 9.0 | 2016a | 7.5 |
%
% Different versions of CUDA may work using the hack described
% above (i.e. setting the `CudaMethod` to `nvcc`).
%
% The following configurations have been tested successfully:
%
% * Windows 7 x64, MATLAB R2014a, Visual C++ 2010, 2013 and CUDA Toolkit
% 6.5. VS 2015 CPU version only (not supported by CUDA Toolkit yet).
% * Windows 8 x64, MATLAB R2014a, Visual C++ 2013 and CUDA
% Toolkit 6.5.
% * Mac OS X 10.9, 10.10, 10.11, MATLAB R2013a to R2016a, Xcode, CUDA
% Toolkit 5.5 to 7.5.
% * GNU/Linux, MATALB R2014a/R2015a/R2015b/R2016a, gcc/g++, CUDA Toolkit 5.5/6.5/7.5.
%
% Compilation on Windows with MinGW compiler (the default mex compiler in
% Matlab) is not supported. For Windows, please reconfigure mex to use
% Visual Studio C/C++ compiler.
% Furthermore your GPU card must have ComputeCapability >= 2.0 (see
% output of `gpuDevice()`) in order to be able to run the GPU code.
% To change the compute capabilities, for `mex` `CudaMethod` edit
% the particular config file. For the 'nvcc' method, compute
% capability is guessed based on the GPUDEVICE output. You can
% override it by setting the 'CudaArch' parameter (e.g. in case of
% multiple GPUs with various architectures).
%
% See also: [Compliling MatConvNet](../install.md#compiling),
% [Compiling MEX files containing CUDA
% code](http://mathworks.com/help/distcomp/run-mex-functions-containing-cuda-code.html),
% `vl_setup()`, `vl_imreadjpeg()`.
% Copyright (C) 2014-16 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% Get MatConvNet root directory
root = fileparts(fileparts(mfilename('fullpath'))) ;
addpath(fullfile(root, 'matlab')) ;
% --------------------------------------------------------------------
% Parse options
% --------------------------------------------------------------------
opts.enableGpu = false;
opts.enableImreadJpeg = true;
opts.enableCudnn = false;
opts.enableDouble = true;
opts.imageLibrary = [] ;
opts.imageLibraryCompileFlags = {} ;
opts.imageLibraryLinkFlags = [] ;
opts.verbose = 0;
opts.debug = false;
opts.cudaMethod = [] ;
opts.cudaRoot = [] ;
opts.cudaArch = [] ;
opts.defCudaArch = [...
'-gencode=arch=compute_20,code=\"sm_20,compute_20\" '...
'-gencode=arch=compute_30,code=\"sm_30,compute_30\"'];
opts.cudnnRoot = 'local/cudnn' ;
opts = vl_argparse(opts, varargin);
% --------------------------------------------------------------------
% Files to compile
% --------------------------------------------------------------------
arch = computer('arch') ;
if isempty(opts.imageLibrary)
switch arch
case 'glnxa64', opts.imageLibrary = 'libjpeg' ;
case 'maci64', opts.imageLibrary = 'quartz' ;
case 'win64', opts.imageLibrary = 'gdiplus' ;
end
end
if isempty(opts.imageLibraryLinkFlags)
switch opts.imageLibrary
case 'libjpeg', opts.imageLibraryLinkFlags = {'-ljpeg'} ;
case 'quartz', opts.imageLibraryLinkFlags = {'-framework Cocoa -framework ImageIO'} ;
case 'gdiplus', opts.imageLibraryLinkFlags = {'gdiplus.lib'} ;
end
end
lib_src = {} ;
mex_src = {} ;
% Files that are compiled as CPP or CU depending on whether GPU support
% is enabled.
if opts.enableGpu, ext = 'cu' ; else ext='cpp' ; end
lib_src{end+1} = fullfile(root,'matlab','src','bits',['data.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['datamex.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnconv.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnfullyconnected.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnsubsample.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnpooling.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnnormalize.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbnorm.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbias.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnbilinearsampler.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src','bits',['nnroipooling.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconv.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnconvt.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnpool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnnormalize.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbnorm.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnbilinearsampler.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_nnroipool.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src',['vl_taccummex.' ext]) ;
switch arch
case {'glnxa64','maci64'}
% not yet supported in windows
mex_src{end+1} = fullfile(root,'matlab','src',['vl_tmove.' ext]) ;
end
% CPU-specific files
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','tinythread.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_cpu.cpp') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','imread.cpp') ;
% GPU-specific files
if opts.enableGpu
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','im2row_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','subsample_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','copy_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','pooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','normalize_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bnorm_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','bilinearsampler_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','roipooling_gpu.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','datacu.cu') ;
mex_src{end+1} = fullfile(root,'matlab','src','vl_cudatool.cu') ;
end
% cuDNN-specific files
if opts.enableCudnn
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnconv_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbias_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnpooling_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbilinearsampler_cudnn.cu') ;
lib_src{end+1} = fullfile(root,'matlab','src','bits','impl','nnbnorm_cudnn.cu') ;
end
% Other files
if opts.enableImreadJpeg
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg.' ext]) ;
mex_src{end+1} = fullfile(root,'matlab','src', ['vl_imreadjpeg_old.' ext]) ;
lib_src{end+1} = fullfile(root,'matlab','src', 'bits', 'impl', ['imread_' opts.imageLibrary '.cpp']) ;
end
% --------------------------------------------------------------------
% Setup CUDA toolkit
% --------------------------------------------------------------------
if opts.enableGpu
opts.verbose && fprintf('%s: * CUDA configuration *\n', mfilename) ;
% Find the CUDA Devkit
if isempty(opts.cudaRoot), opts.cudaRoot = search_cuda_devkit(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: using CUDA Devkit ''%s''.\n', ...
mfilename, opts.cudaRoot) ;
opts.nvccPath = fullfile(opts.cudaRoot, 'bin', 'nvcc') ;
switch arch
case 'win64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib', 'x64') ;
case 'maci64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib') ;
case 'glnxa64', opts.cudaLibDir = fullfile(opts.cudaRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
% Set the nvcc method as default for Win platforms
if strcmp(arch, 'win64') && isempty(opts.cudaMethod)
opts.cudaMethod = 'nvcc';
end
% Activate the CUDA Devkit
cuver = activate_nvcc(opts.nvccPath) ;
opts.verbose && fprintf('%s:\tCUDA: using NVCC ''%s'' (%d).\n', ...
mfilename, opts.nvccPath, cuver) ;
% Set the CUDA arch string (select GPU architecture)
if isempty(opts.cudaArch), opts.cudaArch = get_cuda_arch(opts) ; end
opts.verbose && fprintf('%s:\tCUDA: NVCC architecture string: ''%s''.\n', ...
mfilename, opts.cudaArch) ;
end
if opts.enableCudnn
opts.cudnnIncludeDir = fullfile(opts.cudnnRoot, 'include') ;
switch arch
case 'win64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib', 'x64') ;
case 'maci64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib') ;
case 'glnxa64', opts.cudnnLibDir = fullfile(opts.cudnnRoot, 'lib64') ;
otherwise, error('Unsupported architecture ''%s''.', arch) ;
end
end
% --------------------------------------------------------------------
% Compiler options
% --------------------------------------------------------------------
% Build directories
mex_dir = fullfile(root, 'matlab', 'mex') ;
bld_dir = fullfile(mex_dir, '.build');
if ~exist(fullfile(bld_dir,'bits','impl'), 'dir')
mkdir(fullfile(bld_dir,'bits','impl')) ;
end
% Compiler flags
flags.cc = {} ;
flags.ccpass = {} ;
flags.ccoptim = {} ;
flags.link = {} ;
flags.linklibs = {} ;
flags.linkpass = {} ;
flags.nvccpass = {char(opts.cudaArch)} ;
if opts.verbose > 1
flags.cc{end+1} = '-v' ;
end
if opts.debug
flags.cc{end+1} = '-g' ;
flags.nvccpass{end+1} = '-O0' ;
else
flags.cc{end+1} = '-DNDEBUG' ;
flags.nvccpass{end+1} = '-O3' ;
end
if opts.enableGpu
flags.cc{end+1} = '-DENABLE_GPU' ;
end
if opts.enableCudnn
flags.cc{end+1} = '-DENABLE_CUDNN' ;
flags.cc{end+1} = ['-I"' opts.cudnnIncludeDir '"'] ;
end
if opts.enableDouble
flags.cc{end+1} = '-DENABLE_DOUBLE' ;
end
flags.link{end+1} = '-lmwblas' ;
switch arch
case {'maci64'}
case {'glnxa64'}
flags.linklibs{end+1} = '-lrt' ;
case {'win64'}
% VisualC does not pass this even if available in the CPU architecture
flags.cc{end+1} = '-D__SSSE3__' ;
end
if opts.enableImreadJpeg
flags.cc = horzcat(flags.cc, opts.imageLibraryCompileFlags) ;
flags.linklibs = horzcat(flags.linklibs, opts.imageLibraryLinkFlags) ;
end
if opts.enableGpu
flags.link = horzcat(flags.link, {['-L"' opts.cudaLibDir '"'], '-lcudart', '-lcublas'}) ;
switch arch
case {'maci64', 'glnxa64'}
flags.link{end+1} = '-lmwgpu' ;
case 'win64'
flags.link{end+1} = '-lgpu' ;
end
if opts.enableCudnn
flags.link{end+1} = ['-L"' opts.cudnnLibDir '"'] ;
flags.link{end+1} = '-lcudnn' ;
end
end
switch arch
case {'maci64'}
flags.ccpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.linkpass{end+1} = '-mmacosx-version-min=10.9' ;
flags.ccoptim{end+1} = '-mssse3 -ffast-math' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
if opts.enableGpu && cuver < 70000
% CUDA prior to 7.0 on Mac require GCC libstdc++ instead of the native
% clang libc++. This should go away in the future.
flags.ccpass{end+1} = '-stdlib=libstdc++' ;
flags.linkpass{end+1} = '-stdlib=libstdc++' ;
if ~verLessThan('matlab', '8.5.0')
% Complicating matters, MATLAB 8.5.0 links to clang's libc++ by
% default when linking MEX files overriding the option above. We
% force it to use GCC libstdc++
flags.linkpass{end+1} = '-L"$MATLABROOT/bin/maci64" -lmx -lmex -lmat -lstdc++' ;
end
end
case {'glnxa64'}
flags.ccoptim{end+1} = '-mssse3 -ftree-vect-loop-version -ffast-math -funroll-all-loops' ;
flags.nvccpass{end+1} = '-Xcompiler -fPIC -D_FORCE_INLINES' ;
if opts.enableGpu
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudaLibDir) ;
end
if opts.enableGpu && opts.enableCudnn
flags.linkpass{end+1} = sprintf('-Wl,-rpath -Wl,"%s"', opts.cudnnLibDir) ;
end
case {'win64'}
flags.nvccpass{end+1} = '-Xcompiler /MD' ;
cl_path = fileparts(check_clpath()); % check whether cl.exe in path
flags.nvccpass{end+1} = sprintf('--compiler-bindir "%s"', cl_path) ;
end
% --------------------------------------------------------------------
% Command flags
% --------------------------------------------------------------------
flags.mexcc = horzcat(flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' strjoin(flags.ccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' strjoin(flags.ccoptim)]}) ;
if ~ispc, flags.mexcc{end+1} = '-cxx'; end
% mex: compile GPU
flags.mexcu= horzcat({'-f' mex_cuda_config(root)}, ...
flags.cc, ...
{'-largeArrayDims'}, ...
{['CXXFLAGS=$CXXFLAGS ' quote_nvcc(flags.ccpass) ' ' strjoin(flags.nvccpass)]}, ...
{['CXXOPTIMFLAGS=$CXXOPTIMFLAGS ' quote_nvcc(flags.ccoptim)]}) ;
% mex: link
flags.mexlink = horzcat(flags.cc, flags.link, ...
{'-largeArrayDims'}, ...
{['LDFLAGS=$LDFLAGS ', strjoin(flags.linkpass)]}, ...
{['LINKLIBS=', strjoin(flags.linklibs), ' $LINKLIBS']}) ;
% nvcc: compile GPU
flags.nvcc = horzcat(flags.cc, ...
{opts.cudaArch}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'extern', 'include'))}, ...
{sprintf('-I"%s"', fullfile(matlabroot, 'toolbox','distcomp','gpu','extern','include'))}, ...
{quote_nvcc(flags.ccpass)}, ...
{quote_nvcc(flags.ccoptim)}, ...
flags.nvccpass) ;
if opts.verbose
fprintf('%s: * Compiler and linker configurations *\n', mfilename) ;
fprintf('%s: \tintermediate build products directory: %s\n', mfilename, bld_dir) ;
fprintf('%s: \tMEX files: %s/\n', mfilename, mex_dir) ;
fprintf('%s: \tMEX options [CC CPU]: %s\n', mfilename, strjoin(flags.mexcc)) ;
fprintf('%s: \tMEX options [LINK]: %s\n', mfilename, strjoin(flags.mexlink)) ;
end
if opts.verbose && opts.enableGpu
fprintf('%s: \tMEX options [CC GPU]: %s\n', mfilename, strjoin(flags.mexcu)) ;
end
if opts.verbose && opts.enableGpu && strcmp(opts.cudaMethod,'nvcc')
fprintf('%s: \tNVCC options [CC GPU]: %s\n', mfilename, strjoin(flags.nvcc)) ;
end
if opts.verbose && opts.enableImreadJpeg
fprintf('%s: * Reading images *\n', mfilename) ;
fprintf('%s: \tvl_imreadjpeg enabled\n', mfilename) ;
fprintf('%s: \timage library: %s\n', mfilename, opts.imageLibrary) ;
fprintf('%s: \timage library compile flags: %s\n', mfilename, strjoin(opts.imageLibraryCompileFlags)) ;
fprintf('%s: \timage library link flags: %s\n', mfilename, strjoin(opts.imageLibraryLinkFlags)) ;
end
% --------------------------------------------------------------------
% Compile
% --------------------------------------------------------------------
% Intermediate object files
srcs = horzcat(lib_src,mex_src) ;
for i = 1:numel(horzcat(lib_src, mex_src))
[~,~,ext] = fileparts(srcs{i}) ; ext(1) = [] ;
objfile = toobj(bld_dir,srcs{i});
if strcmp(ext,'cu')
if strcmp(opts.cudaMethod,'nvcc')
nvcc_compile(opts, srcs{i}, objfile, flags.nvcc) ;
else
mex_compile(opts, srcs{i}, objfile, flags.mexcu) ;
end
else
mex_compile(opts, srcs{i}, objfile, flags.mexcc) ;
end
assert(exist(objfile, 'file') ~= 0, 'Compilation of %s failed.', objfile);
end
% Link into MEX files
for i = 1:numel(mex_src)
objs = toobj(bld_dir, [mex_src(i), lib_src]) ;
mex_link(opts, objs, mex_dir, flags.mexlink) ;
end
% Reset path adding the mex subdirectory just created
vl_setupnn() ;
% --------------------------------------------------------------------
% Utility functions
% --------------------------------------------------------------------
% --------------------------------------------------------------------
function objs = toobj(bld_dir,srcs)
% --------------------------------------------------------------------
str = fullfile('matlab','src') ;
multiple = iscell(srcs) ;
if ~multiple, srcs = {srcs} ; end
objs = cell(1, numel(srcs));
for t = 1:numel(srcs)
i = strfind(srcs{t},str);
objs{t} = fullfile(bld_dir, srcs{t}(i+numel(str):end)) ;
end
if ~multiple, objs = objs{1} ; end
objs = regexprep(objs,'.cpp$',['.' objext]) ;
objs = regexprep(objs,'.cu$',['.' objext]) ;
objs = regexprep(objs,'.c$',['.' objext]) ;
% --------------------------------------------------------------------
function mex_compile(opts, src, tgt, mex_opts)
% --------------------------------------------------------------------
mopts = {'-outdir', fileparts(tgt), src, '-c', mex_opts{:}} ;
opts.verbose && fprintf('%s: MEX CC: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function nvcc_compile(opts, src, tgt, nvcc_opts)
% --------------------------------------------------------------------
nvcc_path = fullfile(opts.cudaRoot, 'bin', 'nvcc');
nvcc_cmd = sprintf('"%s" -c "%s" %s -o "%s"', ...
nvcc_path, src, ...
strjoin(nvcc_opts), tgt);
opts.verbose && fprintf('%s: NVCC CC: %s\n', mfilename, nvcc_cmd) ;
status = system(nvcc_cmd);
if status, error('Command %s failed.', nvcc_cmd); end;
% --------------------------------------------------------------------
function mex_link(opts, objs, mex_dir, mex_flags)
% --------------------------------------------------------------------
mopts = {'-outdir', mex_dir, mex_flags{:}, objs{:}} ;
opts.verbose && fprintf('%s: MEX LINK: %s\n', mfilename, strjoin(mopts)) ;
mex(mopts{:}) ;
% --------------------------------------------------------------------
function ext = objext()
% --------------------------------------------------------------------
% Get the extension for an 'object' file for the current computer
% architecture
switch computer('arch')
case 'win64', ext = 'obj';
case {'maci64', 'glnxa64'}, ext = 'o' ;
otherwise, error('Unsupported architecture %s.', computer) ;
end
% --------------------------------------------------------------------
function conf_file = mex_cuda_config(root)
% --------------------------------------------------------------------
% Get mex CUDA config file
mver = [1e4 1e2 1] * sscanf(version, '%d.%d.%d') ;
if mver <= 80200, ext = 'sh' ; else ext = 'xml' ; end
arch = computer('arch') ;
switch arch
case {'win64'}
config_dir = fullfile(matlabroot, 'toolbox', ...
'distcomp', 'gpu', 'extern', ...
'src', 'mex', arch) ;
case {'maci64', 'glnxa64'}
config_dir = fullfile(root, 'matlab', 'src', 'config') ;
end
conf_file = fullfile(config_dir, ['mex_CUDA_' arch '.' ext]);
fprintf('%s:\tCUDA: MEX config file: ''%s''\n', mfilename, conf_file);
% --------------------------------------------------------------------
function cl_path = check_clpath()
% --------------------------------------------------------------------
% Checks whether the cl.exe is in the path (needed for the nvcc). If
% not, tries to guess the location out of mex configuration.
cc = mex.getCompilerConfigurations('c++');
if isempty(cc)
error(['Mex is not configured.'...
'Run "mex -setup" to configure your compiler. See ',...
'http://www.mathworks.com/support/compilers ', ...
'for supported compilers for your platform.']);
end
cl_path = fullfile(cc.Location, 'VC', 'bin', 'amd64');
[status, ~] = system('cl.exe -help');
if status == 1
warning('CL.EXE not found in PATH. Trying to guess out of mex setup.');
prev_path = getenv('PATH');
setenv('PATH', [prev_path ';' cl_path]);
status = system('cl.exe');
if status == 1
setenv('PATH', prev_path);
error('Unable to find cl.exe');
else
fprintf('Location of cl.exe (%s) successfully added to your PATH.\n', ...
cl_path);
end
end
% -------------------------------------------------------------------------
function paths = which_nvcc()
% -------------------------------------------------------------------------
switch computer('arch')
case 'win64'
[~, paths] = system('where nvcc.exe');
paths = strtrim(paths);
paths = paths(strfind(paths, '.exe'));
case {'maci64', 'glnxa64'}
[~, paths] = system('which nvcc');
paths = strtrim(paths) ;
end
% -------------------------------------------------------------------------
function cuda_root = search_cuda_devkit(opts)
% -------------------------------------------------------------------------
% This function tries to to locate a working copy of the CUDA Devkit.
opts.verbose && fprintf(['%s:\tCUDA: searching for the CUDA Devkit' ...
' (use the option ''CudaRoot'' to override):\n'], mfilename);
% Propose a number of candidate paths for NVCC
paths = {getenv('MW_NVCC_PATH')} ;
paths = [paths, which_nvcc()] ;
for v = {'5.5', '6.0', '6.5', '7.0', '7.5', '8.0', '8.5', '9.0'}
switch computer('arch')
case 'glnxa64'
paths{end+1} = sprintf('/usr/local/cuda-%s/bin/nvcc', char(v)) ;
case 'maci64'
paths{end+1} = sprintf('/Developer/NVIDIA/CUDA-%s/bin/nvcc', char(v)) ;
case 'win64'
paths{end+1} = sprintf('C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v%s\\bin\\nvcc.exe', char(v)) ;
end
end
paths{end+1} = sprintf('/usr/local/cuda/bin/nvcc') ;
% Validate each candidate NVCC path
for i=1:numel(paths)
nvcc(i).path = paths{i} ;
[nvcc(i).isvalid, nvcc(i).version] = validate_nvcc(paths{i}) ;
end
if opts.verbose
fprintf('\t| %5s | %5s | %-70s |\n', 'valid', 'ver', 'NVCC path') ;
for i=1:numel(paths)
fprintf('\t| %5d | %5d | %-70s |\n', ...
nvcc(i).isvalid, nvcc(i).version, nvcc(i).path) ;
end
end
% Pick an entry
index = find([nvcc.isvalid]) ;
if isempty(index)
error('Could not find a valid NVCC executable\n') ;
end
[~, newest] = max([nvcc(index).version]);
nvcc = nvcc(index(newest)) ;
cuda_root = fileparts(fileparts(nvcc.path)) ;
if opts.verbose
fprintf('%s:\tCUDA: choosing NVCC compiler ''%s'' (version %d)\n', ...
mfilename, nvcc.path, nvcc.version) ;
end
% -------------------------------------------------------------------------
function [valid, cuver] = validate_nvcc(nvccPath)
% -------------------------------------------------------------------------
[status, output] = system(sprintf('"%s" --version', nvccPath)) ;
valid = (status == 0) ;
if ~valid
cuver = 0 ;
return ;
end
match = regexp(output, 'V(\d+\.\d+\.\d+)', 'match') ;
if isempty(match), valid = false ; return ; end
cuver = [1e4 1e2 1] * sscanf(match{1}, 'V%d.%d.%d') ;
% --------------------------------------------------------------------
function cuver = activate_nvcc(nvccPath)
% --------------------------------------------------------------------
% Validate the NVCC compiler installation
[valid, cuver] = validate_nvcc(nvccPath) ;
if ~valid
error('The NVCC compiler ''%s'' does not appear to be valid.', nvccPath) ;
end
% Make sure that NVCC is visible by MEX by setting the MW_NVCC_PATH
% environment variable to the NVCC compiler path
if ~strcmp(getenv('MW_NVCC_PATH'), nvccPath)
warning('Setting the ''MW_NVCC_PATH'' environment variable to ''%s''', nvccPath) ;
setenv('MW_NVCC_PATH', nvccPath) ;
end
% In some operating systems and MATLAB versions, NVCC must also be
% available in the command line search path. Make sure that this is%
% the case.
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
warning('NVCC not found in the command line path or the one found does not matches ''%s''.', nvccPath);
nvccDir = fileparts(nvccPath) ;
prevPath = getenv('PATH') ;
switch computer
case 'PCWIN64', separator = ';' ;
case {'GLNXA64', 'MACI64'}, separator = ':' ;
end
setenv('PATH', [nvccDir separator prevPath]) ;
[valid_, cuver_] = validate_nvcc('nvcc') ;
if ~valid_ || cuver_ ~= cuver
setenv('PATH', prevPath) ;
error('Unable to set the command line path to point to ''%s'' correctly.', nvccPath) ;
else
fprintf('Location of NVCC (%s) added to your command search PATH.\n', nvccDir) ;
end
end
% -------------------------------------------------------------------------
function str = quote_nvcc(str)
% -------------------------------------------------------------------------
if iscell(str), str = strjoin(str) ; end
str = strrep(strtrim(str), ' ', ',') ;
if ~isempty(str), str = ['-Xcompiler ' str] ; end
% --------------------------------------------------------------------
function cudaArch = get_cuda_arch(opts)
% --------------------------------------------------------------------
opts.verbose && fprintf('%s:\tCUDA: determining GPU compute capability (use the ''CudaArch'' option to override)\n', mfilename);
try
gpu_device = gpuDevice();
arch_code = strrep(gpu_device.ComputeCapability, '.', '');
cudaArch = ...
sprintf('-gencode=arch=compute_%s,code=\\\"sm_%s,compute_%s\\\" ', ...
arch_code, arch_code, arch_code) ;
catch
opts.verbose && fprintf(['%s:\tCUDA: cannot determine the capabilities of the installed GPU; ' ...
'falling back to default\n'], mfilename);
cudaArch = opts.defCudaArch;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
getVarReceptiveFields.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/+dagnn/@DagNN/getVarReceptiveFields.m
| 3,635 |
utf_8
|
6d61896e475e64e9f05f10303eee7ade
|
function rfs = getVarReceptiveFields(obj, var)
%GETVARRECEPTIVEFIELDS Get the receptive field of a variable
% RFS = GETVARRECEPTIVEFIELDS(OBJ, VAR) gets the receptivie fields RFS of
% all the variables of the DagNN OBJ into variable VAR. VAR is a variable
% name or index.
%
% RFS has one entry for each variable in the DagNN following the same
% format as has DAGNN.GETRECEPTIVEFIELDS(). For example, RFS(i) is the
% receptive field of the i-th variable in the DagNN into variable VAR. If
% the i-th variable is not a descendent of VAR in the DAG, then there is
% no receptive field, indicated by `rfs(i).size == []`. If the receptive
% field cannot be computed (e.g. because it depends on the values of
% variables and not just on the network topology, or if it cannot be
% expressed as a sliding window), then `rfs(i).size = [NaN NaN]`.
% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi. All rights reserved.
%
% This file is part of the VLFeat library and is made available under the
% terms of the BSD license (see the COPYING file).
if ~isnumeric(var)
var_n = obj.getVarIndex(var) ;
if isnan(var_n)
error('Variable %s not found.', var_n);
end
var = var_n;
end
nv = numel(obj.vars) ;
nw = numel(var) ;
rfs = struct('size', cell(nw, nv), 'stride', cell(nw, nv), 'offset', cell(nw,nv)) ;
for w = 1:numel(var)
rfs(w,var(w)).size = [1 1] ;
rfs(w,var(w)).stride = [1 1] ;
rfs(w,var(w)).offset = [1 1] ;
end
for l = obj.executionOrder
% visit all blocks and get their receptive fields
in = obj.layers(l).inputIndexes ;
out = obj.layers(l).outputIndexes ;
blockRfs = obj.layers(l).block.getReceptiveFields() ;
for w = 1:numel(var)
% find the receptive fields in each of the inputs of the block
for i = 1:numel(in)
for j = 1:numel(out)
rf = composeReceptiveFields(rfs(w, in(i)), blockRfs(i,j)) ;
rfs(w, out(j)) = resolveReceptiveFields([rfs(w, out(j)), rf]) ;
end
end
end
end
end
% -------------------------------------------------------------------------
function rf = composeReceptiveFields(rf1, rf2)
% -------------------------------------------------------------------------
if isempty(rf1.size) || isempty(rf2.size)
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
return ;
end
rf.size = rf1.stride .* (rf2.size - 1) + rf1.size ;
rf.stride = rf1.stride .* rf2.stride ;
rf.offset = rf1.stride .* (rf2.offset - 1) + rf1.offset ;
end
% -------------------------------------------------------------------------
function rf = resolveReceptiveFields(rfs)
% -------------------------------------------------------------------------
rf.size = [] ;
rf.stride = [] ;
rf.offset = [] ;
for i = 1:numel(rfs)
if isempty(rfs(i).size), continue ; end
if isnan(rfs(i).size)
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break ;
end
if isempty(rf.size)
rf = rfs(i) ;
else
if ~isequal(rf.stride,rfs(i).stride)
% incompatible geometry; this cannot be represented by a sliding
% window RF field and may denotes an error in the network structure
rf.size = [NaN NaN] ;
rf.stride = [NaN NaN] ;
rf.offset = [NaN NaN] ;
break;
else
% the two RFs have the same stride, so they can be recombined
% the new RF is just large enough to contain both of them
a = rf.offset - (rf.size-1)/2 ;
b = rf.offset + (rf.size-1)/2 ;
c = rfs(i).offset - (rfs(i).size-1)/2 ;
d = rfs(i).offset + (rfs(i).size-1)/2 ;
e = min(a,c) ;
f = max(b,d) ;
rf.offset = (e+f)/2 ;
rf.size = f-e+1 ;
end
end
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
rebuild.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/+dagnn/@DagNN/rebuild.m
| 3,243 |
utf_8
|
e368536d9e70c805d8424cdd6b593960
|
function rebuild(obj)
%REBUILD Rebuild the internal data structures of a DagNN object
% REBUILD(obj) rebuilds the internal data structures
% of the DagNN obj. It is an helper function used internally
% to update the network when layers are added or removed.
varFanIn = zeros(1, numel(obj.vars)) ;
varFanOut = zeros(1, numel(obj.vars)) ;
parFanOut = zeros(1, numel(obj.params)) ;
for l = 1:numel(obj.layers)
ii = obj.getVarIndex(obj.layers(l).inputs) ;
oi = obj.getVarIndex(obj.layers(l).outputs) ;
pi = obj.getParamIndex(obj.layers(l).params) ;
obj.layers(l).inputIndexes = ii ;
obj.layers(l).outputIndexes = oi ;
obj.layers(l).paramIndexes = pi ;
varFanOut(ii) = varFanOut(ii) + 1 ;
varFanIn(oi) = varFanIn(oi) + 1 ;
parFanOut(pi) = parFanOut(pi) + 1 ;
end
[obj.vars.fanin] = tolist(num2cell(varFanIn)) ;
[obj.vars.fanout] = tolist(num2cell(varFanOut)) ;
if ~isempty(parFanOut)
[obj.params.fanout] = tolist(num2cell(parFanOut)) ;
end
% dump unused variables
keep = (varFanIn + varFanOut) > 0 ;
obj.vars = obj.vars(keep) ;
varRemap = cumsum(keep) ;
% dump unused parameters
keep = parFanOut > 0 ;
obj.params = obj.params(keep) ;
parRemap = cumsum(keep) ;
% update the indexes to account for removed layers, variables and parameters
for l = 1:numel(obj.layers)
obj.layers(l).inputIndexes = varRemap(obj.layers(l).inputIndexes) ;
obj.layers(l).outputIndexes = varRemap(obj.layers(l).outputIndexes) ;
obj.layers(l).paramIndexes = parRemap(obj.layers(l).paramIndexes) ;
obj.layers(l).block.layerIndex = l ;
end
% update the variable and parameter names hash maps
obj.varNames = cell2struct(num2cell(1:numel(obj.vars)), {obj.vars.name}, 2) ;
obj.paramNames = cell2struct(num2cell(1:numel(obj.params)), {obj.params.name}, 2) ;
obj.layerNames = cell2struct(num2cell(1:numel(obj.layers)), {obj.layers.name}, 2) ;
% determine the execution order again (and check for consistency)
obj.executionOrder = getOrder(obj) ;
% --------------------------------------------------------------------
function order = getOrder(obj)
% --------------------------------------------------------------------
hops = cell(1, numel(obj.vars)) ;
for l = 1:numel(obj.layers)
for v = obj.layers(l).inputIndexes
hops{v}(end+1) = l ;
end
end
order = zeros(1, numel(obj.layers)) ;
for l = 1:numel(obj.layers)
if order(l) == 0
order = dagSort(obj, hops, order, l) ;
end
end
if any(order == -1)
warning('The network graph contains a cycle') ;
end
[~,order] = sort(order, 'descend') ;
% --------------------------------------------------------------------
function order = dagSort(obj, hops, order, layer)
% --------------------------------------------------------------------
if order(layer) > 0, return ; end
order(layer) = -1 ; % mark as open
n = 0 ;
for o = obj.layers(layer).outputIndexes ;
for child = hops{o}
if order(child) == -1
return ;
end
if order(child) == 0
order = dagSort(obj, hops, order, child) ;
end
n = max(n, order(child)) ;
end
end
order(layer) = n + 1 ;
% --------------------------------------------------------------------
function varargout = tolist(x)
% --------------------------------------------------------------------
[varargout{1:numel(x)}] = x{:} ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
print.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/+dagnn/@DagNN/print.m
| 15,032 |
utf_8
|
7da4e68e624f559f815ee3076d9dd966
|
function str = print(obj, inputSizes, varargin)
%PRINT Print information about the DagNN object
% PRINT(OBJ) displays a summary of the functions and parameters in the network.
% STR = PRINT(OBJ) returns the summary as a string instead of printing it.
%
% PRINT(OBJ, INPUTSIZES) where INPUTSIZES is a cell array of the type
% {'input1nam', input1size, 'input2name', input2size, ...} prints
% information using the specified size for each of the listed inputs.
%
% PRINT(___, 'OPT', VAL, ...) accepts the following options:
%
% `All`:: false
% Display all the information below.
%
% `Layers`:: '*'
% Specify which layers to print. This can be either a list of
% indexes, a cell array of array names, or the string '*', meaning
% all layers.
%
% `Parameters`:: '*'
% Specify which parameters to print, similar to the option above.
%
% `Variables`:: []
% Specify which variables to print, similar to the option above.
%
% `Dependencies`:: false
% Whether to display the dependency (geometric transformation)
% of each variables from each input.
%
% `Format`:: 'ascii'
% Choose between `ascii`, `latex`, `csv`, 'digraph', and `dot`.
% The first three format print tables; `digraph` uses the plot function
% for a `digraph` (supported in MATLAB>=R2015b) and the last one
% prints a graph in `dot` format. In case of zero outputs, it
% attmepts to compile and visualise the dot graph using `dot` command
% and `start` (Windows), `display` (Linux) or `open` (Mac OSX) on your system.
% In the latter case, all variables and layers are included in the
% graph, regardless of the other parameters.
%
% `FigurePath`:: 'tempname.pdf'
% Sets the path where any generated `dot` figure will be saved. Currently,
% this is useful only in combination with the format `dot`.
% By default, a unique temporary filename is used (`tempname`
% is replaced with a `tempname()` call). The extension specifies the
% output format (passed to dot as a `-Text` parameter).
% If not extension provided, PDF used by default.
% Additionally, stores the .dot file used to generate the figure to
% the same location.
%
% `dotArgs`:: ''
% Additional dot arguments. E.g. '-Gsize="7"' to generate a smaller
% output (for a review of the network structure etc.).
%
% `MaxNumColumns`:: 18
% Maximum number of columns in each table.
%
% See also: DAGNN, DAGNN.GETVARSIZES().
if nargin > 1 && ischar(inputSizes)
% called directly with options, skipping second argument
varargin = {inputSizes, varargin{:}} ;
inputSizes = {} ;
end
opts.all = false ;
opts.format = 'ascii' ;
opts.figurePath = 'tempname.pdf' ;
opts.dotArgs = '';
[opts, varargin] = vl_argparse(opts, varargin) ;
opts.layers = '*' ;
opts.parameters = [] ;
opts.variables = [] ;
if opts.all || nargin > 1
opts.variables = '*' ;
end
if opts.all
opts.parameters = '*' ;
end
opts.memory = true ;
opts.dependencies = opts.all ;
opts.maxNumColumns = 18 ;
opts = vl_argparse(opts, varargin) ;
if nargin == 1, inputSizes = {} ; end
varSizes = obj.getVarSizes(inputSizes) ;
paramSizes = cellfun(@size, {obj.params.value}, 'UniformOutput', false) ;
str = {''} ;
if strcmpi(opts.format, 'dot')
str = printDot(obj, varSizes, paramSizes, opts) ;
if nargout == 0
displayDot(str, opts) ;
end
return ;
end
if strcmpi(opts.format,'digraph')
str = printdigraph(obj, varSizes) ;
return ;
end
if ~isempty(opts.layers)
table = {'func', '-', 'type', 'inputs', 'outputs', 'params', 'pad', 'stride'} ;
for l = select(obj, 'layers', opts.layers)
layer = obj.layers(l) ;
table{l+1,1} = layer.name ;
table{l+1,2} = '-' ;
table{l+1,3} = player(class(layer.block)) ;
table{l+1,4} = strtrim(sprintf('%s ', layer.inputs{:})) ;
table{l+1,5} = strtrim(sprintf('%s ', layer.outputs{:})) ;
table{l+1,6} = strtrim(sprintf('%s ', layer.params{:})) ;
if isprop(layer.block, 'pad')
table{l+1,7} = pdims(layer.block.pad) ;
else
table{l+1,7} = 'n/a' ;
end
if isprop(layer.block, 'stride')
table{l+1,8} = pdims(layer.block.stride) ;
else
table{l+1,8} = 'n/a' ;
end
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.parameters)
table = {'param', '-', 'dims', 'mem', 'fanout'} ;
for v = select(obj, 'params', opts.parameters)
table{v+1,1} = obj.params(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(paramSizes{v}) ;
table{v+1,4} = pmem(prod(paramSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.params(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if ~isempty(opts.variables)
table = {'var', '-', 'dims', 'mem', 'fanin', 'fanout'} ;
for v = select(obj, 'vars', opts.variables)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(varSizes{v}) ;
table{v+1,4} = pmem(prod(varSizes{v}) * 4) ;
table{v+1,5} = sprintf('%d',obj.vars(v).fanin) ;
table{v+1,6} = sprintf('%d',obj.vars(v).fanout) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.memory
paramMem = sum(cellfun(@getMem, paramSizes)) ;
varMem = sum(cellfun(@getMem, varSizes)) ;
table = {'params', 'vars', 'total'} ;
table{2,1} = pmem(paramMem) ;
table{2,2} = pmem(varMem) ;
table{2,3} = pmem(paramMem + varMem) ;
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
if opts.dependencies
% print variable to input dependencies
inputs = obj.getInputs() ;
rfs = obj.getVarReceptiveFields(inputs) ;
for i = 1:size(rfs,1)
table = {sprintf('rf in ''%s''', inputs{i}), '-', 'size', 'stride', 'offset'} ;
for v = 1:size(rfs,2)
table{v+1,1} = obj.vars(v).name ;
table{v+1,2} = '-' ;
table{v+1,3} = pdims(rfs(i,v).size) ;
table{v+1,4} = pdims(rfs(i,v).stride) ;
table{v+1,5} = pdims(rfs(i,v).offset) ;
end
str{end+1} = printtable(opts, table') ;
str{end+1} = sprintf('\n') ;
end
end
% finish
str = horzcat(str{:}) ;
if nargout == 0,
fprintf('%s',str) ;
clear str ;
end
end
% -------------------------------------------------------------------------
function str = printtable(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = printtablechunk(opts, table(:, [1 sel])) ;
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function str = printtablechunk(opts, table)
% -------------------------------------------------------------------------
str = {''} ;
switch opts.format
case 'ascii'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
case 'latex'
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1}= sprintf('\\end{tabular}\n') ;
case 'csv'
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds,', sizes(j)) ;
str{end+1} = sprintf(fmt, ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
otherwise
error('Uknown format %s', opts.format) ;
end
str = horzcat(str{:}) ;
end
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
end
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(isnan(x))
s = 'n/a' ;
return ;
end
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
end
% -------------------------------------------------------------------------
function x = player(x)
% -------------------------------------------------------------------------
if numel(x) < 7, return ; end
if x(1:6) == 'dagnn.', x = x(7:end) ; end
end
% -------------------------------------------------------------------------
function m = getMem(sz)
% -------------------------------------------------------------------------
m = prod(sz) * 4 ;
if isnan(m), m = 0 ; end
end
% -------------------------------------------------------------------------
function sel = select(obj, type, pattern)
% -------------------------------------------------------------------------
if isnumeric(pattern)
sel = pattern ;
else
if isstr(pattern)
if strcmp(pattern, '*')
sel = 1:numel(obj.(type)) ;
return ;
else
pattern = {pattern} ;
end
end
sel = find(cellfun(@(x) any(strcmp(x, pattern)), {obj.(type).name})) ;
end
end
% -------------------------------------------------------------------------
function h = printdigraph(net, varSizes)
% -------------------------------------------------------------------------
if exist('digraph') ~= 2
error('MATLAB graph support not present.');
end
s = []; t = []; w = [];
varsNames = {net.vars.name};
layerNames = {net.layers.name};
numVars = numel(varsNames);
spatSize = cellfun(@(vs) vs(1), varSizes);
spatSize(isnan(spatSize)) = 1;
varChannels = cellfun(@(vs) vs(3), varSizes);
varChannels(isnan(varChannels)) = 0;
for li = 1:numel(layerNames)
l = net.layers(li); lidx = numVars + li;
s = [s l.inputIndexes];
t = [t lidx*ones(1, numel(l.inputIndexes))];
w = [w spatSize(l.inputIndexes)];
s = [s lidx*ones(1, numel(l.outputIndexes))];
t = [t l.outputIndexes];
w = [w spatSize(l.outputIndexes)];
end
nodeNames = [varsNames, layerNames];
g = digraph(s, t, w);
lw = 5*g.Edges.Weight/max([g.Edges.Weight; 5]);
h = plot(g, 'NodeLabel', nodeNames, 'LineWidth', lw);
highlight(h, numVars+1:numVars+numel(layerNames), 'MarkerSize', 8, 'Marker', 's');
highlight(h, 1:numVars, 'MarkerSize', 5, 'Marker', 's');
cmap = copper;
varNvalRel = varChannels./max(varChannels);
for vi = 1:numel(varChannels)
highlight(h, vi, 'NodeColor', cmap(max(round(varNvalRel(vi)*64), 1),:));
end
axis off;
layout(h, 'force');
end
% -------------------------------------------------------------------------
function str = printDot(net, varSizes, paramSizes, otps)
% -------------------------------------------------------------------------
str = {} ;
str{end+1} = sprintf('digraph DagNN {\n\tfontsize=12\n') ;
font_style = 'fontsize=12 fontname="helvetica"';
for v = 1:numel(net.vars)
label=sprintf('{{%s} | {%s | %s }}', net.vars(v).name, pdims(varSizes{v}), pmem(4*prod(varSizes{v}))) ;
str{end+1} = sprintf('\tvar_%s [label="%s" shape=record style="solid,rounded,filled" color=cornsilk4 fillcolor=beige %s ]\n', ...
net.vars(v).name, label, font_style) ;
end
for p = 1:numel(net.params)
label=sprintf('{{%s} | {%s | %s }}', net.params(p).name, pdims(paramSizes{p}), pmem(4*prod(paramSizes{p}))) ;
str{end+1} = sprintf('\tpar_%s [label="%s" shape=record style="solid,rounded,filled" color=lightsteelblue4 fillcolor=lightsteelblue %s ]\n', ...
net.params(p).name, label, font_style) ;
end
for l = 1:numel(net.layers)
label = sprintf('{ %s | %s }', net.layers(l).name, class(net.layers(l).block)) ;
str{end+1} = sprintf('\t%s [label="%s" shape=record style="bold,filled" color="tomato4" fillcolor="tomato" %s ]\n', ...
net.layers(l).name, label, font_style) ;
for i = 1:numel(net.layers(l).inputs)
str{end+1} = sprintf('\tvar_%s->%s [weight=10]\n', ...
net.layers(l).inputs{i}, ...
net.layers(l).name) ;
end
for o = 1:numel(net.layers(l).outputs)
str{end+1} = sprintf('\t%s->var_%s [weight=10]\n', ...
net.layers(l).name, ...
net.layers(l).outputs{o}) ;
end
for p = 1:numel(net.layers(l).params)
str{end+1} = sprintf('\tpar_%s->%s [weight=1]\n', ...
net.layers(l).params{p}, ...
net.layers(l).name) ;
end
end
str{end+1} = sprintf('}\n') ;
str = cat(2,str{:}) ;
end
% -------------------------------------------------------------------------
function displayDot(str, opts)
% -------------------------------------------------------------------------
%mwdot = fullfile(matlabroot, 'bin', computer('arch'), 'mwdot') ;
dotPaths = {'/opt/local/bin/dot', 'dot'} ;
if ismember(computer, {'PCWIN64', 'PCWIN'})
winPath = 'c:\Program Files (x86)';
dpath = dir(fullfile(winPath, 'Graphviz*'));
if ~isempty(dpath)
dotPaths = [{fullfile(winPath, dpath.name, 'bin', 'dot.exe')}, dotPaths];
end
end
dotExe = '' ;
for i = 1:numel(dotPaths)
[~,~,ext] = fileparts(dotPaths{i});
if exist(dotPaths{i},'file') && ~strcmp(ext, '.m')
dotExe = dotPaths{i} ;
break;
end
end
if isempty(dotExe)
warning('Could not genereate a figure because the `dot` utility could not be found.') ;
return ;
end
[path, figName, ext] = fileparts(opts.figurePath) ;
if isempty(ext), ext = '.pdf' ; end
if strcmp(figName, 'tempname')
figName = tempname();
end
in = fullfile(path, [ figName, '.dot' ]) ;
out = fullfile(path, [ figName, ext ]) ;
f = fopen(in, 'w') ; fwrite(f, str) ; fclose(f) ;
cmd = sprintf('"%s" -T%s %s -o "%s" "%s"', dotExe, ext(2:end), ...
opts.dotArgs, out, in) ;
[status, result] = system(cmd) ;
if status ~= 0
error('Unable to run %s\n%s', cmd, result) ;
end
if ~isempty(strtrim(result))
fprintf('Dot output:\n%s\n', result) ;
end
%f = fopen(out,'r') ; file=fread(f, 'char=>char')' ; fclose(f) ;
switch computer
case {'PCWIN64', 'PCWIN'}
system(sprintf('start "" "%s"', out)) ;
case 'MACI64'
system(sprintf('open "%s"', out)) ;
case 'GLNXA64'
system(sprintf('display "%s"', out)) ;
otherwise
fprintf('The figure saved at "%s"\n', out) ;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
fromSimpleNN.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/+dagnn/@DagNN/fromSimpleNN.m
| 7,258 |
utf_8
|
83f914aec610125592263d74249f54a7
|
function obj = fromSimpleNN(net, varargin)
% FROMSIMPLENN Initialize a DagNN object from a SimpleNN network
% FROMSIMPLENN(NET) initializes the DagNN object from the
% specified CNN using the SimpleNN format.
%
% SimpleNN objects are linear chains of computational layers. These
% layers exchange information through variables and parameters that
% are not explicitly named. Hence, FROMSIMPLENN() uses a number of
% rules to assign such names automatically:
%
% * From the input to the output of the CNN, variables are called
% `x0` (input of the first layer), `x1`, `x2`, .... In this
% manner `xi` is the output of the i-th layer.
%
% * Any loss layer requires two inputs, the second being a label.
% These are called `label` (for the first such layers), and then
% `label2`, `label3`,... for any other similar layer.
%
% Additionally, given the option `CanonicalNames` the function can
% change the names of some variables to make them more convenient to
% use. With this option turned on:
%
% * The network input is called `input` instead of `x0`.
%
% * The output of each SoftMax layer is called `prob` (or `prob2`,
% ...).
%
% * The output of each Loss layer is called `objective` (or `
% objective2`, ...).
%
% * The input of each SoftMax or Loss layer of type *softmax log
% loss* is called `prediction` (or `prediction2`, ...). If a Loss
% layer immediately follows a SoftMax layer, then the rule above
% takes precendence and the input name is not changed.
%
% FROMSIMPLENN(___, 'OPT', VAL, ...) accepts the following options:
%
% `CanonicalNames`:: false
% If `true` use the rules above to assign more meaningful
% names to some of the variables.
% Copyright (C) 2015 Karel Lenc and Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.canonicalNames = false ;
opts = vl_argparse(opts, varargin) ;
import dagnn.*
obj = DagNN() ;
net = vl_simplenn_move(net, 'cpu') ;
net = vl_simplenn_tidy(net) ;
% copy meta-information as is
obj.meta = net.meta ;
for l = 1:numel(net.layers)
inputs = {sprintf('x%d',l-1)} ;
outputs = {sprintf('x%d',l)} ;
params = struct(...
'name', {}, ...
'value', {}, ...
'learningRate', [], ...
'weightDecay', []) ;
if isfield(net.layers{l}, 'name')
name = net.layers{l}.name ;
else
name = sprintf('layer%d',l) ;
end
switch net.layers{l}.type
case {'conv', 'convt'}
sz = size(net.layers{l}.weights{1}) ;
hasBias = ~isempty(net.layers{l}.weights{2}) ;
params(1).name = sprintf('%sf',name) ;
params(1).value = net.layers{l}.weights{1} ;
if hasBias
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
end
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
if hasBias
params(2).learningRate = net.layers{l}.learningRate(2) ;
end
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
if hasBias
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
end
end
switch net.layers{l}.type
case 'conv'
block = Conv() ;
block.size = sz ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.dilate = net.layers{l}.dilate ;
case 'convt'
block = ConvTranspose() ;
block.size = sz ;
block.upsample = net.layers{l}.upsample ;
block.crop = net.layers{l}.crop ;
block.numGroups = net.layers{l}.numGroups ;
end
block.hasBias = hasBias ;
block.opts = net.layers{l}.opts ;
case 'pool'
block = Pooling() ;
block.method = net.layers{l}.method ;
block.poolSize = net.layers{l}.pool ;
block.pad = net.layers{l}.pad ;
block.stride = net.layers{l}.stride ;
block.opts = net.layers{l}.opts ;
case {'normalize', 'lrn'}
block = LRN() ;
block.param = net.layers{l}.param ;
case {'dropout'}
block = DropOut() ;
block.rate = net.layers{l}.rate ;
case {'relu'}
block = ReLU() ;
block.leak = net.layers{l}.leak ;
case {'sigmoid'}
block = Sigmoid() ;
case {'softmax'}
block = SoftMax() ;
case {'softmaxloss'}
block = Loss('loss', 'softmaxlog') ;
% The loss has two inputs
inputs{2} = getNewVarName(obj, 'label') ;
case {'bnorm'}
block = BatchNorm() ;
params(1).name = sprintf('%sm',name) ;
params(1).value = net.layers{l}.weights{1} ;
params(2).name = sprintf('%sb',name) ;
params(2).value = net.layers{l}.weights{2} ;
params(3).name = sprintf('%sx',name) ;
params(3).value = net.layers{l}.weights{3} ;
if isfield(net.layers{l},'learningRate')
params(1).learningRate = net.layers{l}.learningRate(1) ;
params(2).learningRate = net.layers{l}.learningRate(2) ;
params(3).learningRate = net.layers{l}.learningRate(3) ;
end
if isfield(net.layers{l},'weightDecay')
params(1).weightDecay = net.layers{l}.weightDecay(1) ;
params(2).weightDecay = net.layers{l}.weightDecay(2) ;
params(3).weightDecay = 0 ;
end
otherwise
error([net.layers{l}.type ' is unsupported']) ;
end
obj.addLayer(...
name, ...
block, ...
inputs, ...
outputs, ...
{params.name}) ;
for p = 1:numel(params)
pindex = obj.getParamIndex(params(p).name) ;
if ~isempty(params(p).value)
obj.params(pindex).value = params(p).value ;
end
if ~isempty(params(p).learningRate)
obj.params(pindex).learningRate = params(p).learningRate ;
end
if ~isempty(params(p).weightDecay)
obj.params(pindex).weightDecay = params(p).weightDecay ;
end
end
end
% --------------------------------------------------------------------
% Rename variables to canonical names
% --------------------------------------------------------------------
if opts.canonicalNames
for l = 1:numel(obj.layers)
if l == 1
obj.renameVar(obj.layers(l).inputs{1}, 'input') ;
end
if isa(obj.layers(l).block, 'dagnn.SoftMax')
obj.renameVar(obj.layers(l).outputs{1}, getNewVarName(obj, 'prob')) ;
obj.renameVar(obj.layers(l).inputs{1}, getNewVarName(obj, 'prediction')) ;
end
if isa(obj.layers(l).block, 'dagnn.Loss')
obj.renameVar(obj.layers(l).outputs{1}, 'objective') ;
if isempty(regexp(obj.layers(l).inputs{1}, '^prob.*'))
obj.renameVar(obj.layers(l).inputs{1}, ...
getNewVarName(obj, 'prediction')) ;
end
end
end
end
if isfield(obj.meta, 'inputs')
obj.meta.inputs(1).name = obj.layers(1).inputs{1} ;
end
% --------------------------------------------------------------------
function name = getNewVarName(obj, prefix)
% --------------------------------------------------------------------
t = 0 ;
name = prefix ;
while any(strcmp(name, {obj.vars.name}))
t = t + 1 ;
name = sprintf('%s%d', prefix, t) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_simplenn_display.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/simplenn/vl_simplenn_display.m
| 12,455 |
utf_8
|
65bb29cd7c27b68c75fdd27acbd63e2b
|
function [info, str] = vl_simplenn_display(net, varargin)
%VL_SIMPLENN_DISPLAY Display the structure of a SimpleNN network.
% VL_SIMPLENN_DISPLAY(NET) prints statistics about the network NET.
%
% INFO = VL_SIMPLENN_DISPLAY(NET) returns instead a structure INFO
% with several statistics for each layer of the network NET.
%
% [INFO, STR] = VL_SIMPLENN_DISPLAY(...) returns also a string STR
% with the text that would otherwise be printed.
%
% The function accepts the following options:
%
% `inputSize`:: auto
% Specifies the size of the input tensor X that will be passed to
% the network as input. This information is used in order to
% estiamte the memory required to process the network. When this
% option is not used, VL_SIMPLENN_DISPLAY() tires to use values
% in the NET structure to guess the input size:
% NET.META.INPUTSIZE and NET.META.NORMALIZATION.IMAGESIZE
% (assuming a batch size of one image, unless otherwise specified
% by the `batchSize` option).
%
% `batchSize`:: []
% Specifies the number of data points in a batch in estimating
% the memory consumption, overriding the last dimension of
% `inputSize`.
%
% `maxNumColumns`:: 18
% Maximum number of columns in a table. Wider tables are broken
% into multiple smaller ones.
%
% `format`:: `'ascii'`
% One of `'ascii'`, `'latex'`, or `'csv'`.
%
% See also: VL_SIMPLENN().
% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.inputSize = [] ;
opts.batchSize = [] ;
opts.maxNumColumns = 18 ;
opts.format = 'ascii' ;
opts = vl_argparse(opts, varargin) ;
% determine input size, using first the option, then net.meta.inputSize,
% and eventually net.meta.normalization.imageSize, if any
if isempty(opts.inputSize)
tmp = [] ;
opts.inputSize = [NaN;NaN;NaN;1] ;
if isfield(net, 'meta')
if isfield(net.meta, 'inputSize')
tmp = net.meta.inputSize(:) ;
elseif isfield(net.meta, 'normalization') && ...
isfield(net.meta.normalization, 'imageSize')
tmp = net.meta.normalization.imageSize ;
end
opts.inputSize(1:numel(tmp)) = tmp(:) ;
end
end
if ~isempty(opts.batchSize)
opts.inputSize(4) = opts.batchSize ;
end
fields={'layer', 'type', 'name', '-', ...
'support', 'filtd', 'filtdil', 'nfilt', 'stride', 'pad', '-', ...
'rfsize', 'rfoffset', 'rfstride', '-', ...
'dsize', 'ddepth', 'dnum', '-', ...
'xmem', 'wmem'};
% get the support, stride, and padding of the operators
for l = 1:numel(net.layers)
ly = net.layers{l} ;
switch ly.type
case 'conv'
ks = max([size(ly.weights{1},1) ; size(ly.weights{1},2)],1) ;
ks = (ks - 1) .* ly.dilate + 1 ;
info.support(1:2,l) = ks ;
case 'pool'
info.support(1:2,l) = ly.pool(:) ;
otherwise
info.support(1:2,l) = [1;1] ;
end
if isfield(ly, 'stride')
info.stride(1:2,l) = ly.stride(:) ;
else
info.stride(1:2,l) = 1 ;
end
if isfield(ly, 'pad')
info.pad(1:4,l) = ly.pad(:) ;
else
info.pad(1:4,l) = 0 ;
end
% operator applied to the input image
info.receptiveFieldSize(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
(info.support(1:2,1:l)-1),2) ;
info.receptiveFieldOffset(1:2,l) = 1 + ...
sum(cumprod([[1;1], info.stride(1:2,1:l-1)],2) .* ...
((info.support(1:2,1:l)-1)/2 - info.pad([1 3],1:l)),2) ;
info.receptiveFieldStride = cumprod(info.stride,2) ;
end
% get the dimensions of the data
info.dataSize(1:4,1) = opts.inputSize(:) ;
for l = 1:numel(net.layers)
ly = net.layers{l} ;
if strcmp(ly.type, 'custom') && isfield(ly, 'getForwardSize')
sz = ly.getForwardSize(ly, info.dataSize(:,l)) ;
info.dataSize(:,l+1) = sz(:) ;
continue ;
end
info.dataSize(1, l+1) = floor((info.dataSize(1,l) + ...
sum(info.pad(1:2,l)) - ...
info.support(1,l)) / info.stride(1,l)) + 1 ;
info.dataSize(2, l+1) = floor((info.dataSize(2,l) + ...
sum(info.pad(3:4,l)) - ...
info.support(2,l)) / info.stride(2,l)) + 1 ;
info.dataSize(3, l+1) = info.dataSize(3,l) ;
info.dataSize(4, l+1) = info.dataSize(4,l) ;
switch ly.type
case 'conv'
if isfield(ly, 'weights')
f = ly.weights{1} ;
else
f = ly.filters ;
end
if size(f, 3) ~= 0
info.dataSize(3, l+1) = size(f,4) ;
end
case {'loss', 'softmaxloss'}
info.dataSize(3:4, l+1) = 1 ;
case 'custom'
info.dataSize(3,l+1) = NaN ;
end
end
if nargout == 1, return ; end
% print table
table = {} ;
wmem = 0 ;
xmem = 0 ;
for wi=1:numel(fields)
w = fields{wi} ;
switch w
case 'type', s = 'type' ;
case 'stride', s = 'stride' ;
case 'rfsize', s = 'rf size' ;
case 'rfstride', s = 'rf stride' ;
case 'rfoffset', s = 'rf offset' ;
case 'dsize', s = 'data size' ;
case 'ddepth', s = 'data depth' ;
case 'dnum', s = 'data num' ;
case 'nfilt', s = 'num filts' ;
case 'filtd', s = 'filt dim' ;
case 'filtdil', s = 'filt dilat' ;
case 'wmem', s = 'param mem' ;
case 'xmem', s = 'data mem' ;
otherwise, s = char(w) ;
end
table{wi,1} = s ;
% do input pseudo-layer
for l=0:numel(net.layers)
switch char(w)
case '-', s='-' ;
case 'layer', s=sprintf('%d', l) ;
case 'dsize', s=pdims(info.dataSize(1:2,l+1)) ;
case 'ddepth', s=sprintf('%d', info.dataSize(3,l+1)) ;
case 'dnum', s=sprintf('%d', info.dataSize(4,l+1)) ;
case 'xmem'
a = prod(info.dataSize(:,l+1)) * 4 ;
s = pmem(a) ;
xmem = xmem + a ;
otherwise
if l == 0
if strcmp(char(w),'type'), s = 'input';
else s = 'n/a' ; end
else
ly=net.layers{l} ;
switch char(w)
case 'name'
if isfield(ly, 'name')
s=ly.name ;
else
s='' ;
end
case 'type'
switch ly.type
case 'normalize', s='norm';
case 'pool'
if strcmpi(ly.method,'avg'), s='apool'; else s='mpool'; end
case 'softmax', s='softmx' ;
case 'softmaxloss', s='softmxl' ;
otherwise s=ly.type ;
end
case 'nfilt'
switch ly.type
case 'conv'
if isfield(ly, 'weights'), a = size(ly.weights{1},4) ;
else, a = size(ly.filters,4) ; end
s=sprintf('%d',a) ;
otherwise
s='n/a' ;
end
case 'filtd'
switch ly.type
case 'conv'
s=sprintf('%d',size(ly.weights{1},3)) ;
otherwise
s='n/a' ;
end
case 'filtdil'
switch ly.type
case 'conv'
s=sprintf('%d',ly.dilate) ;
otherwise
s='n/a' ;
end
case 'support'
s = pdims(info.support(:,l)) ;
case 'stride'
s = pdims(info.stride(:,l)) ;
case 'pad'
s = pdims(info.pad(:,l)) ;
case 'rfsize'
s = pdims(info.receptiveFieldSize(:,l)) ;
case 'rfoffset'
s = pdims(info.receptiveFieldOffset(:,l)) ;
case 'rfstride'
s = pdims(info.receptiveFieldStride(:,l)) ;
case 'wmem'
a = 0 ;
if isfield(ly, 'weights') ;
for j=1:numel(ly.weights)
a = a + numel(ly.weights{j}) * 4 ;
end
end
% Legacy code to be removed
if isfield(ly, 'filters') ;
a = a + numel(ly.filters) * 4 ;
end
if isfield(ly, 'biases') ;
a = a + numel(ly.biases) * 4 ;
end
s = pmem(a) ;
wmem = wmem + a ;
end
end
end
table{wi,l+2} = s ;
end
end
str = {} ;
for i=2:opts.maxNumColumns:size(table,2)
sel = i:min(i+opts.maxNumColumns-1,size(table,2)) ;
str{end+1} = ptable(opts, table(:,[1 sel])) ;
end
table = {...
'parameter memory', sprintf('%s (%.2g parameters)', pmem(wmem), wmem/4);
'data memory', sprintf('%s (for batch size %d)', pmem(xmem), info.dataSize(4,1))} ;
str{end+1} = ptable(opts, table) ;
str = horzcat(str{:}) ;
if nargout == 0
fprintf('%s', str) ;
clear info str ;
end
% -------------------------------------------------------------------------
function str = ptable(opts, table)
% -------------------------------------------------------------------------
switch opts.format
case 'ascii', str = pascii(table) ;
case 'latex', str = platex(table) ;
case 'csv', str = pcsv(table) ;
end
str = horzcat(str,sprintf('\n')) ;
% -------------------------------------------------------------------------
function s = pmem(x)
% -------------------------------------------------------------------------
if isnan(x), s = 'NaN' ;
elseif x < 1024^1, s = sprintf('%.0fB', x) ;
elseif x < 1024^2, s = sprintf('%.0fKB', x / 1024) ;
elseif x < 1024^3, s = sprintf('%.0fMB', x / 1024^2) ;
else s = sprintf('%.0fGB', x / 1024^3) ;
end
% -------------------------------------------------------------------------
function s = pdims(x)
% -------------------------------------------------------------------------
if all(x==x(1))
s = sprintf('%.4g', x(1)) ;
else
s = sprintf('%.4gx', x(:)) ;
s(end) = [] ;
end
% -------------------------------------------------------------------------
function str = pascii(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
for i=1:size(table,1)
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds|', sizes(j)) ;
if isequal(s,'-'), s=repmat('-', 1, sizes(j)) ; end
str{end+1} = sprintf(fmt, s) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = pcsv(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) + 2 ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), continue ; end
for j=1:size(table,2)
s = table{i,j} ;
str{end+1} = sprintf('%s,', ['"' s '"']) ;
end
str{end+1} = sprintf('\n') ;
end
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function str = platex(table)
% -------------------------------------------------------------------------
str = {} ;
sizes = max(cellfun(@(x) numel(x), table),[],1) ;
str{end+1} = sprintf('\\begin{tabular}{%s}\n', repmat('c', 1, numel(sizes))) ;
for i=1:size(table,1)
if isequal(table{i,1},'-'), str{end+1} = sprintf('\\hline\n') ; continue ; end
for j=1:size(table,2)
s = table{i,j} ;
fmt = sprintf('%%%ds', sizes(j)) ;
str{end+1} = sprintf(fmt, latexesc(s)) ;
if j<size(table,2), str{end+1} = sprintf('&') ; end
end
str{end+1} = sprintf('\\\\\n') ;
end
str{end+1} = sprintf('\\end{tabular}\n') ;
str = horzcat(str{:}) ;
% -------------------------------------------------------------------------
function s = latexesc(s)
% -------------------------------------------------------------------------
s = strrep(s,'\','\\') ;
s = strrep(s,'_','\char`_') ;
% -------------------------------------------------------------------------
function [cpuMem,gpuMem] = xmem(s, cpuMem, gpuMem)
% -------------------------------------------------------------------------
if nargin <= 1
cpuMem = 0 ;
gpuMem = 0 ;
end
if isstruct(s)
for f=fieldnames(s)'
f = char(f) ;
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s(i).(f), cpuMem, gpuMem) ;
end
end
elseif iscell(s)
for i=1:numel(s)
[cpuMem,gpuMem] = xmem(s{i}, cpuMem, gpuMem) ;
end
elseif isnumeric(s)
if isa(s, 'single')
mult = 4 ;
else
mult = 8 ;
end
if isa(s,'gpuArray')
gpuMem = gpuMem + mult * numel(s) ;
else
cpuMem = cpuMem + mult * numel(s) ;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_test_economic_relu.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/matconvnet-1.0-beta23_modifiedDagnn/matlab/xtest/vl_test_economic_relu.m
| 790 |
utf_8
|
35a3dbe98b9a2f080ee5f911630ab6f3
|
% VL_TEST_ECONOMIC_RELU
function vl_test_economic_relu()
x = randn(11,12,8,'single');
w = randn(5,6,8,9,'single');
b = randn(1,9,'single') ;
net.layers{1} = struct('type', 'conv', ...
'filters', w, ...
'biases', b, ...
'stride', 1, ...
'pad', 0);
net.layers{2} = struct('type', 'relu') ;
res = vl_simplenn(net, x) ;
dzdy = randn(size(res(end).x), 'like', res(end).x) ;
clear res ;
res_ = vl_simplenn(net, x, dzdy) ;
res__ = vl_simplenn(net, x, dzdy, [], 'conserveMemory', true) ;
a=whos('res_') ;
b=whos('res__') ;
assert(a.bytes > b.bytes) ;
vl_testsim(res_(1).dzdx,res__(1).dzdx,1e-4) ;
vl_testsim(res_(1).dzdw{1},res__(1).dzdw{1},1e-4) ;
vl_testsim(res_(1).dzdw{2},res__(1).dzdw{2},1e-4) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
switchFigure.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/myFunctions/switchFigure.m
| 142 |
utf_8
|
eeda5d7fca9d055f8636347f3cc56aa8
|
function switchFigure(n)
if get(0,'CurrentFigure') ~= n
try
set(0,'CurrentFigure',n) ;
catch
figure(n) ;
end
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
myfindLastCheckpoint.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/libs/myFunctions/myfindLastCheckpoint.m
| 432 |
utf_8
|
673b6d6d681d7b5f31b4982a68ac07af
|
% -------------------------------------------------------------------------
function epoch = myfindLastCheckpoint(modelDir, prefixStr)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, sprintf('%snet-epoch-*.mat', prefixStr))) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_nnloss_modified.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo1_tutorial_instance_segmentation/fun4MeanShift/vl_nnloss_modified.m
| 16,226 |
utf_8
|
928ff76f02b6600caa8becbfc152dbc1
|
function y = vl_nnloss_modified(x, c, varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logistic`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if ~isempty(varargin) && ~ischar(varargin{1}) % passed in dzdy
dzdy = varargin{1} ;
varargin(1) = [] ;
else
dzdy = [] ;
end
opts.marginMat = [] ;
opts.marginAlpha_ = 1 ;
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
switch lower(opts.loss)
case {'cosinesimilaritylogloss', 'cosinesimilaritymmloss', 'cosinesimilarityregloss', 'cosinesimilarityregloss_full', ...
'cosinesimlaritylogloss', 'cosinesimlaritymmloss', 'cosinesimlarityregloss', 'cosinesimlarityregloss_full', ...
'cosinesimlairtylogloss', 'cosinesimlairtymmloss', 'cosinesimlairtyregloss', 'cosinesimlairtyregloss_full', ...
'cosinesimilarityabsregloss', 'cosinesimilarityabsregloss_full'}
hasIgnoreLabel = 0;
otherwise
hasIgnoreLabel = any(c(:) == 0);
end
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
c = gpuArray(c);
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
case {'cosinesimilaritylogloss', 'cosinesimilaritymmloss', 'cosinesimilarityregloss', 'cosinesimilarityregloss_full', ...
'cosinesimlaritylogloss', 'cosinesimlaritymmloss', 'cosinesimlarityregloss', 'cosinesimlarityregloss_full', ...
'cosinesimlairtylogloss', 'cosinesimlairtymmloss', 'cosinesimlairtyregloss', 'cosinesimlairtyregloss_full',...
'cosinesimilarityabsregloss', 'cosinesimilarityabsregloss_full'}
assert(labelSize(1) == inputSize(1)) ;
assert(labelSize(2) == inputSize(2)) ;
assert(labelSize(3) == inputSize(3)) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = opts.instanceWeights;
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights) && isempty(strfind(lower(opts.loss), 'cosinesimilarity')) && isempty(strfind(lower(opts.loss), 'cosinesimlarity'))
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
% instanceWeights = c;
% instanceWeights(instanceWeights~=11) = 3;
% instanceWeights(instanceWeights==11) = 1;
% instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights) ;
elseif isempty(instanceWeights) && ~isempty(strfind(lower(opts.loss), 'cosinesimilarity')) && ~isempty(strfind(lower(opts.loss), 'cosinesimlarity'))
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
else
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
case 'cosinesimilaritylogloss'
t = - (log(x).*c + log(1-x).*(1-c));
case {'cosinesimilaritymmloss', 'cosinesimlaritymmloss', 'cosinesimlairtymmloss'}
if isempty(opts.marginMat)
t = max(0, x-opts.marginAlpha_) .* (1-c) ;
else
t = max(0, x-opts.marginMat) .* (1-c) ;
end
case {'cosinesimilarityregloss', 'cosinesimlarityregloss', 'cosinesimlairtyregloss'}
t = c.* ((x-c).^2); % including positive pairs only
case {'cosinesimilarityregloss_full', 'cosinesimlarityregloss_full', 'cosinesimlairtyregloss_full'}
t = ((x-c).^2); % including positive and negative pairs
case {'cosinesimilarityabsregloss', 'cosinesimlarityabsregloss', 'cosinesimlairtyabsregloss'}
t = c.* (c-x); % including positive pairs only
case {'cosinesimilarityabsregloss_full', 'cosinesimlarityabsregloss_full', 'cosinesimlairtyabsregloss_full'}
t = (c-x); % including positive pairs only
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
y(ci) = y(ci) - 1 ;
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
% t = max(0, 1 - x(ci)) ;
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
case {'cosinesimilaritylogloss', 'cosinesimlaritylogloss', 'cosinesimlairtylogloss'}
y = -dzdy .* ( c./x - (1-c) ./ (1-x) );
case {'cosinesimilaritymmloss', 'cosinesimlaritymmloss', 'cosinesimlairtymmloss'}
if isempty(opts.marginMat)
% t = max(0, x-opts.marginAlpha_) .* (1-c) ;
y = x - opts.marginAlpha_;
y(y<0) = 0;
y = y.* (1-c);
y = dzdy .* y;
else
y = x - opts.marginMat;
y(y<0) = 0;
y = y.* (1-c);
y = dzdy .* y;
end
case {'cosinesimilarityregloss', 'cosinesimlarityregloss', 'cosinesimlairtyregloss'}
y = c.* dzdy .* (x-c); % including positive pairs only
case {'cosinesimilarityregloss_full', 'cosinesimlarityregloss_full', 'cosinesimlairtyregloss_full'}
y = dzdy .* (x-c); % including positive and negative pairs
case {'cosinesimilarityabsregloss', 'cosinesimlarityabsregloss', 'cosinesimlairtyabsregloss'}
%t = c.* (c-x); % including positive pairs only
y = c.* dzdy .* (-x); % including positive pairs only
case {'cosinesimilarityabsregloss_full', 'cosinesimlarityabsregloss_full', 'cosinesimlairtyabsregloss_full'}
%t = (c-x); % including positive pairs only
y = dzdy .* (-x); % including positive pairs only
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
getBatchWrapper4toyDigitV2.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo1_tutorial_instance_segmentation/fun4MeanShift/getBatchWrapper4toyDigitV2.m
| 795 |
utf_8
|
d4dd7f6389ff6f9829ff67027a84bc94
|
% return a get batch function
% -------------------------------------------------------------------------
function fn = getBatchWrapper4toyDigitV2(opts)
% -------------------------------------------------------------------------
fn = @(images, mode) getBatch_dict4toyDigitV2(images, mode, opts) ;
end
% -------------------------------------------------------------------------
function [imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getBatch_dict4toyDigitV2(images, mode, opts)
% -------------------------------------------------------------------------
%images = strcat([imdb.path_to_dataset filesep], imdb.(mode).(batch) ) ;
[imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getImgBatch4toyDigitV2(images, mode, opts, 'prefetch', nargout == 0) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
vl_nnloss_modified.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo4_InstSegTraining_VOC2012/vl_nnloss_modified.m
| 16,226 |
utf_8
|
928ff76f02b6600caa8becbfc152dbc1
|
function y = vl_nnloss_modified(x, c, varargin)
%VL_NNLOSS CNN categorical or attribute loss.
% Y = VL_NNLOSS(X, C) computes the loss incurred by the prediction
% scores X given the categorical labels C.
%
% The prediction scores X are organised as a field of prediction
% vectors, represented by a H x W x D x N array. The first two
% dimensions, H and W, are spatial and correspond to the height and
% width of the field; the third dimension D is the number of
% categories or classes; finally, the dimension N is the number of
% data items (images) packed in the array.
%
% While often one has H = W = 1, the case W, H > 1 is useful in
% dense labelling problems such as image segmentation. In the latter
% case, the loss is summed across pixels (contributions can be
% weighed using the `InstanceWeights` option described below).
%
% The array C contains the categorical labels. In the simplest case,
% C is an array of integers in the range [1, D] with N elements
% specifying one label for each of the N images. If H, W > 1, the
% same label is implicitly applied to all spatial locations.
%
% In the second form, C has dimension H x W x 1 x N and specifies a
% categorical label for each spatial location.
%
% In the third form, C has dimension H x W x D x N and specifies
% attributes rather than categories. Here elements in C are either
% +1 or -1 and C, where +1 denotes that an attribute is present and
% -1 that it is not. The key difference is that multiple attributes
% can be active at the same time, while categories are mutually
% exclusive. By default, the loss is *summed* across attributes
% (unless otherwise specified using the `InstanceWeights` option
% described below).
%
% DZDX = VL_NNLOSS(X, C, DZDY) computes the derivative of the block
% projected onto the output derivative DZDY. DZDX and DZDY have the
% same dimensions as X and Y respectively.
%
% VL_NNLOSS() supports several loss functions, which can be selected
% by using the option `type` described below. When each scalar c in
% C is interpreted as a categorical label (first two forms above),
% the following losses can be used:
%
% Classification error:: `classerror`
% L(X,c) = (argmax_q X(q) ~= c). Note that the classification
% error derivative is flat; therefore this loss is useful for
% assessment, but not for training a model.
%
% Top-K classification error:: `topkerror`
% L(X,c) = (rank X(c) in X <= K). The top rank is the one with
% highest score. For K=1, this is the same as the
% classification error. K is controlled by the `topK` option.
%
% Log loss:: `log`
% L(X,c) = - log(X(c)). This function assumes that X(c) is the
% predicted probability of class c (hence the vector X must be non
% negative and sum to one).
%
% Softmax log loss (multinomial logistic loss):: `softmaxlog`
% L(X,c) = - log(P(c)) where P(c) = exp(X(c)) / sum_q exp(X(q)).
% This is the same as the `log` loss, but renormalizes the
% predictions using the softmax function.
%
% Multiclass hinge loss:: `mhinge`
% L(X,c) = max{0, 1 - X(c)}. This function assumes that X(c) is
% the score margin for class c against the other classes. See
% also the `mmhinge` loss below.
%
% Multiclass structured hinge loss:: `mshinge`
% L(X,c) = max{0, 1 - M(c)} where M(c) = X(c) - max_{q ~= c}
% X(q). This is the same as the `mhinge` loss, but computes the
% margin between the prediction scores first. This is also known
% the Crammer-Singer loss, an example of a structured prediction
% loss.
%
% When C is a vector of binary attribures c in (+1,-1), each scalar
% prediction score x is interpreted as voting for the presence or
% absence of a particular attribute. The following losses can be
% used:
%
% Binary classification error:: `binaryerror`
% L(x,c) = (sign(x - t) ~= c). t is a threshold that can be
% specified using the `threshold` option and defaults to zero. If
% x is a probability, it should be set to 0.5.
%
% Binary log loss:: `binarylog`
% L(x,c) = - log(c(x-0.5) + 0.5). x is assumed to be the
% probability that the attribute is active (c=+1). Hence x must be
% a number in the range [0,1]. This is the binary version of the
% `log` loss.
%
% Logistic log loss:: `logistic`
% L(x,c) = log(1 + exp(- cx)). This is the same as the `binarylog`
% loss, but implicitly normalizes the score x into a probability
% using the logistic (sigmoid) function: p = sigmoid(x) = 1 / (1 +
% exp(-x)). This is also equivalent to `softmaxlog` loss where
% class c=+1 is assigned score x and class c=-1 is assigned score
% 0.
%
% Hinge loss:: `hinge`
% L(x,c) = max{0, 1 - cx}. This is the standard hinge loss for
% binary classification. This is equivalent to the `mshinge` loss
% if class c=+1 is assigned score x and class c=-1 is assigned
% score 0.
%
% VL_NNLOSS(...,'OPT', VALUE, ...) supports these additionals
% options:
%
% InstanceWeights:: []
% Allows to weight the loss as L'(x,c) = WGT L(x,c), where WGT is
% a per-instance weight extracted from the array
% `InstanceWeights`. For categorical losses, this is either a H x
% W x 1 or a H x W x 1 x N array. For attribute losses, this is
% either a H x W x D or a H x W x D x N array.
%
% TopK:: 5
% Top-K value for the top-K error. Note that K should not
% exceed the number of labels.
%
% See also: VL_NNSOFTMAX().
% Copyright (C) 2014-15 Andrea Vedaldi.
% Copyright (C) 2016 Karel Lenc.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if ~isempty(varargin) && ~ischar(varargin{1}) % passed in dzdy
dzdy = varargin{1} ;
varargin(1) = [] ;
else
dzdy = [] ;
end
opts.marginMat = [] ;
opts.marginAlpha_ = 1 ;
opts.instanceWeights = [] ;
opts.classWeights = [] ;
opts.threshold = 0 ;
opts.loss = 'softmaxlog' ;
opts.topK = 5 ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
inputSize = [size(x,1) size(x,2) size(x,3) size(x,4)] ;
% Form 1: C has one label per image. In this case, get C in form 2 or
% form 3.
c = gather(c) ;
if numel(c) == inputSize(4)
c = reshape(c, [1 1 1 inputSize(4)]) ;
c = repmat(c, inputSize(1:2)) ;
end
switch lower(opts.loss)
case {'cosinesimilaritylogloss', 'cosinesimilaritymmloss', 'cosinesimilarityregloss', 'cosinesimilarityregloss_full', ...
'cosinesimlaritylogloss', 'cosinesimlaritymmloss', 'cosinesimlarityregloss', 'cosinesimlarityregloss_full', ...
'cosinesimlairtylogloss', 'cosinesimlairtymmloss', 'cosinesimlairtyregloss', 'cosinesimlairtyregloss_full', ...
'cosinesimilarityabsregloss', 'cosinesimilarityabsregloss_full'}
hasIgnoreLabel = 0;
otherwise
hasIgnoreLabel = any(c(:) == 0);
end
% --------------------------------------------------------------------
% Spatial weighting
% --------------------------------------------------------------------
% work around a bug in MATLAB, where native cast() would slow
% progressively
if isa(x, 'gpuArray')
switch classUnderlying(x) ;
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
c = gpuArray(c);
else
switch class(x)
case 'single', cast = @(z) single(z) ;
case 'double', cast = @(z) double(z) ;
end
end
labelSize = [size(c,1) size(c,2) size(c,3) size(c,4)] ;
assert(isequal(labelSize(1:2), inputSize(1:2))) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = [] ;
switch lower(opts.loss)
case {'classerror', 'topkerror', 'log', 'softmaxlog', 'mhinge', 'mshinge'}
% there must be one categorical label per prediction vector
assert(labelSize(3) == 1) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c(:,:,1,:) ~= 0) ;
end
case {'binaryerror', 'binarylog', 'logistic', 'hinge'}
% there must be one categorical label per prediction scalar
assert(labelSize(3) == inputSize(3)) ;
if hasIgnoreLabel
% null labels denote instances that should be skipped
instanceWeights = cast(c ~= 0) ;
end
case {'cosinesimilaritylogloss', 'cosinesimilaritymmloss', 'cosinesimilarityregloss', 'cosinesimilarityregloss_full', ...
'cosinesimlaritylogloss', 'cosinesimlaritymmloss', 'cosinesimlarityregloss', 'cosinesimlarityregloss_full', ...
'cosinesimlairtylogloss', 'cosinesimlairtymmloss', 'cosinesimlairtyregloss', 'cosinesimlairtyregloss_full',...
'cosinesimilarityabsregloss', 'cosinesimilarityabsregloss_full'}
assert(labelSize(1) == inputSize(1)) ;
assert(labelSize(2) == inputSize(2)) ;
assert(labelSize(3) == inputSize(3)) ;
assert(labelSize(4) == inputSize(4)) ;
instanceWeights = opts.instanceWeights;
otherwise
error('Unknown loss ''%s''.', opts.loss) ;
end
if ~isempty(opts.instanceWeights)
% important: this code needs to broadcast opts.instanceWeights to
% an array of the same size as c
if isempty(instanceWeights) && isempty(strfind(lower(opts.loss), 'cosinesimilarity')) && isempty(strfind(lower(opts.loss), 'cosinesimlarity'))
instanceWeights = bsxfun(@times, onesLike(c), opts.instanceWeights) ;
% instanceWeights = c;
% instanceWeights(instanceWeights~=11) = 3;
% instanceWeights(instanceWeights==11) = 1;
% instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights) ;
elseif isempty(instanceWeights) && ~isempty(strfind(lower(opts.loss), 'cosinesimilarity')) && ~isempty(strfind(lower(opts.loss), 'cosinesimlarity'))
instanceWeights = bsxfun(@times, instanceWeights, opts.instanceWeights);
else
end
end
% --------------------------------------------------------------------
% Do the work
% --------------------------------------------------------------------
switch lower(opts.loss)
case {'log', 'softmaxlog', 'mhinge', 'mshinge'}
% from category labels to indexes
numPixelsPerImage = prod(inputSize(1:2)) ;
numPixels = numPixelsPerImage * inputSize(4) ;
imageVolume = numPixelsPerImage * inputSize(3) ;
n = reshape(0:numPixels-1,labelSize) ;
offset = 1 + mod(n, numPixelsPerImage) + ...
imageVolume * fix(n / numPixelsPerImage) ;
ci = offset + numPixelsPerImage * max(c - 1,0) ;
end
if nargin <= 2 || isempty(dzdy)
switch lower(opts.loss)
case 'classerror'
[~,chat] = max(x,[],3) ;
t = cast(c ~= chat) ;
case 'topkerror'
[~,predictions] = sort(x,3,'descend') ;
t = 1 - sum(bsxfun(@eq, c, predictions(:,:,1:opts.topK,:)), 3) ;
case 'log'
t = - log(x(ci)) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
t = Xmax + log(sum(ex,3)) - x(ci) ;
case 'mhinge'
t = max(0, 1 - x(ci)) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
t = max(0, 1 - x(ci) + max(Q,[],3)) ;
case 'binaryerror'
t = cast(sign(x - opts.threshold) ~= c) ;
case 'binarylog'
t = -log(c.*(x-0.5) + 0.5) ;
case 'logistic'
%t = log(1 + exp(-c.*X)) ;
a = -c.*x ;
b = max(0, a) ;
t = b + log(exp(-b) + exp(a-b)) ;
case 'hinge'
t = max(0, 1 - c.*x) ;
case 'cosinesimilaritylogloss'
t = - (log(x).*c + log(1-x).*(1-c));
case {'cosinesimilaritymmloss', 'cosinesimlaritymmloss', 'cosinesimlairtymmloss'}
if isempty(opts.marginMat)
t = max(0, x-opts.marginAlpha_) .* (1-c) ;
else
t = max(0, x-opts.marginMat) .* (1-c) ;
end
case {'cosinesimilarityregloss', 'cosinesimlarityregloss', 'cosinesimlairtyregloss'}
t = c.* ((x-c).^2); % including positive pairs only
case {'cosinesimilarityregloss_full', 'cosinesimlarityregloss_full', 'cosinesimlairtyregloss_full'}
t = ((x-c).^2); % including positive and negative pairs
case {'cosinesimilarityabsregloss', 'cosinesimlarityabsregloss', 'cosinesimlairtyabsregloss'}
t = c.* (c-x); % including positive pairs only
case {'cosinesimilarityabsregloss_full', 'cosinesimlarityabsregloss_full', 'cosinesimlairtyabsregloss_full'}
t = (c-x); % including positive pairs only
end
if ~isempty(instanceWeights)
y = instanceWeights(:)' * t(:) ;
else
y = sum(t(:));
end
else
if ~isempty(instanceWeights)
dzdy = dzdy * instanceWeights ;
end
switch lower(opts.loss)
case {'classerror', 'topkerror'}
y = zerosLike(x) ;
case 'log'
y = zerosLike(x) ;
y(ci) = - dzdy ./ max(x(ci), 1e-8) ;
case 'softmaxlog'
Xmax = max(x,[],3) ;
ex = exp(bsxfun(@minus, x, Xmax)) ;
y = bsxfun(@rdivide, ex, sum(ex,3)) ;
y(ci) = y(ci) - 1 ;
y = bsxfun(@times, dzdy, y) ;
case 'mhinge'
% t = max(0, 1 - x(ci)) ;
y = zerosLike(x) ;
y(ci) = - dzdy .* (x(ci) < 1) ;
case 'mshinge'
Q = x ;
Q(ci) = -inf ;
[~, q] = max(Q,[],3) ;
qi = offset + numPixelsPerImage * (q - 1) ;
W = dzdy .* (x(ci) - x(qi) < 1) ;
y = zerosLike(x) ;
y(ci) = - W ;
y(qi) = + W ;
case 'binaryerror'
y = zerosLike(x) ;
case 'binarylog'
y = - dzdy ./ (x + (c-1)*0.5) ;
case 'logistic'
% t = exp(-Y.*X) / (1 + exp(-Y.*X)) .* (-Y)
% t = 1 / (1 + exp(Y.*X)) .* (-Y)
y = - dzdy .* c ./ (1 + exp(c.*x)) ;
case 'hinge'
y = - dzdy .* c .* (c.*x < 1) ;
case {'cosinesimilaritylogloss', 'cosinesimlaritylogloss', 'cosinesimlairtylogloss'}
y = -dzdy .* ( c./x - (1-c) ./ (1-x) );
case {'cosinesimilaritymmloss', 'cosinesimlaritymmloss', 'cosinesimlairtymmloss'}
if isempty(opts.marginMat)
% t = max(0, x-opts.marginAlpha_) .* (1-c) ;
y = x - opts.marginAlpha_;
y(y<0) = 0;
y = y.* (1-c);
y = dzdy .* y;
else
y = x - opts.marginMat;
y(y<0) = 0;
y = y.* (1-c);
y = dzdy .* y;
end
case {'cosinesimilarityregloss', 'cosinesimlarityregloss', 'cosinesimlairtyregloss'}
y = c.* dzdy .* (x-c); % including positive pairs only
case {'cosinesimilarityregloss_full', 'cosinesimlarityregloss_full', 'cosinesimlairtyregloss_full'}
y = dzdy .* (x-c); % including positive and negative pairs
case {'cosinesimilarityabsregloss', 'cosinesimlarityabsregloss', 'cosinesimlairtyabsregloss'}
%t = c.* (c-x); % including positive pairs only
y = c.* dzdy .* (-x); % including positive pairs only
case {'cosinesimilarityabsregloss_full', 'cosinesimlarityabsregloss_full', 'cosinesimlairtyabsregloss_full'}
%t = (c-x); % including positive pairs only
y = dzdy .* (-x); % including positive pairs only
end
end
% --------------------------------------------------------------------
function y = zerosLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.zeros(size(x),classUnderlying(x)) ;
else
y = zeros(size(x),'like',x) ;
end
% --------------------------------------------------------------------
function y = onesLike(x)
% --------------------------------------------------------------------
if isa(x,'gpuArray')
y = gpuArray.ones(size(x),classUnderlying(x)) ;
else
y = ones(size(x),'like',x) ;
end
|
github
|
aimerykong/Recurrent-Pixel-Embedding-for-Instance-Grouping-master
|
getBatchWrapper_augVOC2012.m
|
.m
|
Recurrent-Pixel-Embedding-for-Instance-Grouping-master/demo4_InstSegTraining_VOC2012/getBatchWrapper_augVOC2012.m
| 460 |
utf_8
|
08f8928d4415a1bfaecc30c16de254f7
|
% return a get batch function
% -------------------------------------------------------------------------
function fn = getBatchWrapper_augVOC2012(opts)
fn = @(images, mode) getBatch_dict(images, mode, opts) ;
end
function [imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getBatch_dict(images, mode, opts)
[imBatch, semanticMaskBatch, instanceMaskBatch, weightBatch] = getImgBatch_augVOC2012(images, mode, opts, 'prefetch', nargout == 0) ;
end
|
github
|
thejihuijin/VideoDilation-master
|
sc.m
|
.m
|
VideoDilation-master/saliency/sc.m
| 38,646 |
utf_8
|
26cc0ce889b98168991324c9e25bf156
|
function I = sc(I, varargin)
%SC Display/output truecolor images with a range of colormaps
%
% Examples:
% sc(image)
% sc(image, limits)
% sc(image, map)
% sc(image, limits, map)
% sc(image, map, limits)
% sc(..., col1, mask1, col2, mask2,...)
% out = sc(...)
% sc
%
% Generates a truecolor RGB image based on the input values in 'image' and
% any maximum and minimum limits specified, using the colormap specified.
% The image is displayed on screen if there is no output argument.
%
% SC has these advantages over MATLAB image rendering functions:
% - images can be displayed or output; makes combining/overlaying images
% simple.
% - images are rendered/output in truecolor (RGB [0,1]); no nasty
% discretization of the input data.
% - many special, built-in colormaps for viewing various types of data.
% - linearly interpolates user defined linear and non-linear colormaps.
% - no border and automatic, integer magnification (unless figure is
% docked or maximized) for better display.
% - multiple images can be generated for export simultaneously.
%
% For a demonstration, simply call SC without any input arguments.
%
% IN:
% image - MxNxCxP or 3xMxNxP image array. MxN are the dimensions of the
% image(s), C is the number of channels, and P the number of
% images. If P > 1, images can only be exported, not displayed.
% limits - [min max] where values in image less than min will be set to
% min and values greater than max will be set to max.
% map - Kx3 or Kx4 user defined colormap matrix, where the optional 4th
% column is the relative distance between colours along the scale,
% or a string containing the name of the colormap to use to create
% the output image. Default: 'none', which is RGB for 3-channel
% images, grayscale otherwise. Conversion of multi-channel images
% to intensity for intensity-based colormaps is done using the L2
% norm. Most MATLAB colormaps are supported. All named colormaps
% can be reversed by prefixing '-' to the string. This maintains
% integrity of the colorbar. Special, non-MATLAB colormaps are:
% 'contrast' - a high contrast colormap for intensity images that
% maintains intensity scale when converted to grayscale,
% for example when printing in black & white.
% 'prob' - first channel is plotted as hue, and the other channels
% modulate intensity. Useful for laying probabilites over
% images.
% 'prob_jet' - first channel is plotted as jet colormap, and the other
% channels modulate intensity.
% 'diff' - intensity values are marked blue for > 0 and red for < 0.
% Darker colour means larger absolute value. For multi-
% channel images, the L2 norm of the other channels sets
% green level. 3 channel images are converted to YUV and
% images with more that 3 channels are projected onto the
% principle components first.
% 'compress' - compress many channels to RGB while maximizing
% variance.
% 'flow' - display two channels representing a 2d Cartesian vector as
% hue for angle and intensity for magnitude (darker colour
% indicates a larger magnitude).
% 'phase' - first channel is intensity, second channel is phase in
% radians. Darker colour means greater intensity, hue
% represents phase from 0 to 2 pi.
% 'stereo' - pair of concatenated images used to generate a red/cyan
% anaglyph.
% 'stereo_col' - pair of concatenated RGB images used to generate a
% colour anaglyph.
% 'rand' - gives an index image a random colormap. Useful for viewing
% segmentations.
% 'rgb2gray' - converts an RGB image to grayscale in the same fashion
% as MATLAB's rgb2gray (in the image processing toolbox).
% col/mask pairs - Pairs of parameters for coloring specific parts of the
% image differently. The first (col) parameter can be
% a MATLAB color specifier, e.g. 'b' or [0.5 0 1], or
% one of the colormaps named above, or an MxNx3 RGB
% image. The second (mask) paramater should be an MxN
% logical array indicating those pixels (true) whose
% color should come from the specified color parameter.
% If there is only one col parameter, without a mask
% pair, then mask = any(isnan(I, 3)), i.e. the mask is
% assumed to indicate the location of NaNs. Note that
% col/mask pairs are applied in order, painting over
% previous pixel values.
%
% OUT:
% out - MxNx3xP truecolour (double) RGB image array in range [0, 1]
%
% See also IMAGE, IMAGESC, IMSHOW, COLORMAP, COLORBAR.
% $Id: sc.m,v 1.81 2008/12/10 23:14:43 ojw Exp $
% Copyright: Oliver Woodford, 2007
%
% Code from the Matlab toolbox avialable at
% https://users.soe.ucsc.edu/~milanfar/research/rokaf/.html/SaliencyDetection.html#Matlab
%
%% Check for arguments
if nargin == 0
% If there are no input arguments then run the demo
if nargout > 0
error('Output expected from no inputs!');
end
demo; % Run the demo
return
end
%% Size our image(s)
[y x c n] = size(I);
I = reshape(I, y, x, c, n);
%% Check if image is given with RGB colour along the first dimension
if y == 3 && c > 3
% Flip colour to 3rd dimension
I = permute(I, [2 3 1 4]);
[y x c n] = size(I);
end
%% Don't do much if I is empty
if isempty(I)
if nargout == 0
% Clear the current axes if we were supposed to display the image
cla; axis off;
else
% Create an empty array with the correct dimensions
I = zeros(y, x, (c~=0)*3, n);
end
return
end
%% Check for multiple images
% If we have a non-singleton 4th dimension we want to display the images in
% a 3x4 grid and use buttons to cycle through them
if n > 1
if nargout > 0
% Return transformed images in an YxXx3xN array
A = zeros(y, x, 3, n);
for a = 1:n
A(:,:,:,a) = sc(I(:,:,:,a), varargin{:});
end
I = A;
else
% Removed functionality
fprintf([' SC no longer supports the display of multiple images. The\n'...
' functionality has been incorporated into an improved version\n'...
' of MONTAGE, available on the MATLAB File Exchange at:\n'...
' http://www.mathworks.com/matlabcentral/fileexchange/22387\n']);
clear I;
end
return
end
%% Parse the input arguments coming after I (1st input)
[map limits mask] = parse_inputs(I, varargin, y, x);
%% Call the rendering function
I = reshape(double(real(I)), y*x, c); % Only work with real doubles
if ~ischar(map)
% Table-based colormap
reverseMap = false;
[I limits] = interp_map(I, limits, reverseMap, map);
else
% If map starts with a '-' sign, invert the colourmap
reverseMap = map(1) == '-';
map = lower(map(reverseMap+1:end));
% Predefined colormap
[I limits] = colormap_switch(I, map, limits, reverseMap, c);
end
%% Update any masked pixels
I = reshape(I, y*x, 3);
for a = 1:size(mask, 2)
I(mask{2,a},1) = mask{1,a}(:,1);
I(mask{2,a},2) = mask{1,a}(:,2);
I(mask{2,a},3) = mask{1,a}(:,3);
end
I = reshape(I, [y x 3]); % Reshape to correct size
%% Only display if the output isn't used
if nargout == 0
display_image(I, map, limits, reverseMap);
% Don't print out the matrix if we've forgotten the ";"
clear I
end
return
%% Colormap switch
function [I limits] = colormap_switch(I, map, limits, reverseMap, c)
% Large switch statement for all the colourmaps
switch map
%% Prism
case 'prism'
% Similar to the MATLAB internal prism colormap, but only works on
% index images, assigning each index (or rounded float) to a
% different colour
[I limits] = index_im(I);
% Generate prism colourmap
map = prism(6);
if reverseMap
map = map(end:-1:1,:); % Reverse the map
end
% Lookup the colours
I = mod(I, 6) + 1;
I = map(I,:);
%% Rand
case 'rand'
% Assigns a random colour to each index
[I limits num_vals] = index_im(I);
% Generate random colourmap
map = rand(num_vals, 3);
% Lookup the colours
I = map(I,:);
%% Diff
case 'diff'
% Show positive as blue and negative as red, white is 0
switch c
case 1
I(:,2:3) = 0;
case 2
% Second channel can only have absolute value
I(:,3) = abs(I(:,2));
case 3
% Diff of RGB images - convert to YUV first
I = rgb2yuv(I);
I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(2);
otherwise
% Use difference along principle component, and other
% channels to modulate second channel
I = calc_prin_comps(I);
I(:,3) = sqrt(sum(I(:,2:end) .^ 2, 2)) ./ sqrt(c - 1);
I(:,4:end) = [];
end
% Generate limits
if isempty(limits)
limits = [min(I(:,1)) max(I(:,1))];
end
limits = max(abs(limits));
if limits
% Scale
if c > 1
I(:,[1 3]) = I(:,[1 3]) / limits;
else
I = I / (limits * 0.5);
end
end
% Colour
M = I(:,1) > 0;
I(:,2) = -I(:,1) .* ~M;
I(:,1) = I(:,1) .* M;
if reverseMap
% Swap first two channels
I = I(:,[2 1 3]);
end
%I = 1 - I * [1 0.4 1; 0.4 1 1; 1 1 0.4]; % (Green/Red)
I = 1 - I * [1 1 0.4; 0.4 1 1; 1 0.4 1]; % (Blue/Red)
I = min(max(reshape(I, numel(I), 1), 0), 1);
limits = [-limits limits]; % For colourbar
%% Flow
case 'flow'
% Calculate amplitude and phase, and use 'phase'
if c ~= 2
error('''flow'' requires two channels');
end
A = sqrt(sum(I .^ 2, 2));
if isempty(limits)
limits = [min(A) max(A)*2];
else
limits = [0 max(abs(limits)*sqrt(2))*2];
end
I(:,1) = atan2(I(:,2), I(:,1));
I(:,2) = A;
if reverseMap
% Invert the amplitude
I(:,2) = -I(:,2);
limits = -limits([2 1]);
end
I = phase_helper(I, limits, 2); % Last parameter tunes how saturated colors can get
% Set NaNs (unknown flow) to 0
I(isnan(I)) = reverseMap;
limits = []; % This colourmap doesn't have a valid colourbar
%% Phase
case 'phase'
% Plot amplitude as intensity and angle as hue
if c < 2
error('''phase'' requires two channels');
end
if isempty(limits)
limits = [min(I(:,1)) max(I(:,1))];
end
if reverseMap
% Invert the phase
I(:,2) = -I(:,2);
end
I = I(:,[2 1]);
if diff(limits)
I = phase_helper(I, limits, 1.3); % Last parameter tunes how saturated colors can get
else
% No intensity - just cycle hsv
I = hsv_helper(mod(I(:,1) / (2 * pi), 1));
end
limits = []; % This colourmap doesn't have a valid colourbar
%% RGB2Grey
case {'rgb2grey', 'rgb2gray'}
% Compress RGB to greyscale
[I limits] = rgb2grey(I, limits, reverseMap);
%% RGB2YUV
case 'rgb2yuv'
% Convert RGB to YUV - not for displaying or saving to disk!
[I limits] = rgb2yuv(I);
%% YUV2RGB
case 'yuv2rgb'
% Convert YUV to RGB - undo conversion of rgb2yuv
if c ~= 3
error('''yuv2rgb'' requires a 3 channel image');
end
I = reshape(I, y*x, 3);
I = I * [1 1 1; 0, -0.39465, 2.03211; 1.13983, -0.58060 0];
I = reshape(I, y, x, 3);
I = sc(I, limits);
limits = []; % This colourmap doesn't have a valid colourbar
%% Prob
case 'prob'
% Plot first channel as grey variation of 'bled' and modulate
% according to other channels
if c > 1
A = rgb2grey(I(:,2:end), [], false);
I = I(:,1);
else
A = 0.5;
end
[I limits] = bled(I, limits, reverseMap);
I = normalize(A + I, [-0.1 1.3]);
%% Prob_jet
case 'prob_jet'
% Plot first channel as 'jet' and modulate according to other
% channels
if c > 1
A = rgb2grey(I(:,2:end), [], false);
I = I(:,1);
else
A = 0.5;
end
[I limits] = jet_helper(I, limits, reverseMap);
I = normalize(A + I, [0.2 1.8]);
%% Compress
case 'compress'
% Compress to RGB, maximizing variance
% Determine and scale to limits
I = normalize(I, limits);
if reverseMap
% Invert after everything
I = 1 - I;
end
% Zero mean
meanCol = mean(I, 1);
isBsx = exist('bsxfun', 'builtin');
if isBsx
I = bsxfun(@minus, I, meanCol);
else
I = I - meanCol(ones(x*y, 1, 'uint8'),:);
end
% Calculate top 3 principle components
I = calc_prin_comps(I, 3);
% Normalize each channel independently
if isBsx
I = bsxfun(@minus, I, min(I, [], 1));
I = bsxfun(@times, I, 1./max(I, [], 1));
else
for a = 1:3
I(:,a) = I(:,a) - min(I(:,a));
I(:,a) = I(:,a) / max(I(:,a));
end
end
% Put components in order of human eyes' response to channels
I = I(:,[2 1 3]);
limits = []; % This colourmap doesn't have a valid colourbar
%% Stereo (anaglyph)
case 'stereo'
% Convert 2 colour images to intensity images
% Show first channel as red and second channel as cyan
A = rgb2grey(I(:,1:floor(end/2)), limits, false);
I = rgb2grey(I(:,floor(end/2)+1:end), limits, false);
if reverseMap
I(:,2:3) = A(:,1:2); % Make first image cyan
else
I(:,1) = A(:,1); % Make first image red
end
limits = []; % This colourmap doesn't have a valid colourbar
%% Coloured anaglyph
case 'stereo_col'
if c ~= 6
error('''stereo_col'' requires a 6 channel image');
end
I = normalize(I, limits);
% Red channel from one image, green and blue from the other
if reverseMap
I(:,1) = I(:,4); % Make second image red
else
I(:,2:3) = I(:,5:6); % Make first image red
end
I = I(:,1:3);
limits = []; % This colourmap doesn't have a valid colourbar
%% None
case 'none'
% No colour map - just output the image
if c ~= 3
[I limits] = grey(I, limits, reverseMap);
else
I = intensity(I(:), limits, reverseMap);
limits = [];
end
%% Grey
case {'gray', 'grey'}
% Greyscale
[I limits] = grey(I, limits, reverseMap);
%% Jet
case 'jet'
% Dark blue to dark red, through green
[I limits] = jet_helper(I, limits, reverseMap);
%% Hot
case 'hot'
% Black to white through red and yellow
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 1 0 0 3; 1 1 0 2; 1 1 1 1]);
%% Contrast
case 'contrast'
% A high contrast, full-colour map that goes from black to white
% linearly when converted to greyscale, and passes through all the
% corners of the RGB colour cube
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 114; 0 0 1 185; 1 0 0 114; 1 0 1 174;...
0 1 0 114; 0 1 1 185; 1 1 0 114; 1 1 1 0]);
%% HSV
case 'hsv'
% Cycle through hues
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = hsv_helper(I);
%% Bone
case 'bone'
% Greyscale with a blue tint
[I limits] = interp_map(I, limits, reverseMap, [0 0 0 3; 21 21 29 3; 42 50 50 2; 64 64 64 1]/64);
%% Colourcube
case {'colorcube', 'colourcube'}
% Psychedelic colourmap inspired by MATLAB's version
[I limits] = intensity(I, limits, reverseMap); % Intensity map
step = 4;
I = I * (step * (1 - eps));
J = I * step;
K = floor(J);
I = cat(3, mod(K, step)/(step-1), J - floor(K), mod(floor(I), step)/(step-1));
%% Cool
case 'cool'
% Cyan through to magenta
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I, 1-I, ones(size(I))];
%% Spring
case 'spring'
% Magenta through to yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [ones(size(I)), I, 1-I];
%% Summer
case 'summer'
% Darkish green through to pale yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I, 0.5+I*0.5, 0.4*ones(size(I))];
%% Autumn
case 'autumn'
% Red through to yellow
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [ones(size(I)), I, zeros(size(I))];
%% Winter
case 'winter'
% Blue through to turquoise
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [zeros(size(I)), I, 1-I*0.5];
%% Copper
case 'copper'
% Black through to copper
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = [I*(1/0.8), I*0.78, I*0.5];
I = min(max(reshape(I, numel(I), 1), 0), 1); % Truncate
%% Pink
case 'pink'
% Greyscale with a pink tint
[I limits] = intensity(I, limits, reverseMap); % Intensity map
J = I * (2 / 3);
I = [I, I-1/3, I-2/3];
I = reshape(max(min(I(:), 1/3), 0), [], 3);
I = I + J(:,[1 1 1]);
I = sqrt(I);
%% Bled
case 'bled'
% Black to red, through blue
[I limits] = bled(I, limits, reverseMap);
%% Earth
case 'earth'
% High contrast, converts to linear scale in grey, strong
% shades of green
table = [0 0 0; 0 0.1104 0.0583; 0.1661 0.1540 0.0248; 0.1085 0.2848 0.1286;...
0.2643 0.3339 0.0939; 0.2653 0.4381 0.1808; 0.3178 0.5053 0.3239;...
0.4858 0.5380 0.3413; 0.6005 0.5748 0.4776; 0.5698 0.6803 0.6415;...
0.5639 0.7929 0.7040; 0.6700 0.8626 0.6931; 0.8552 0.8967 0.6585;...
1 0.9210 0.7803; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Pinker
case 'pinker'
% High contrast, converts to linear scale in grey, strong
% shades of pink
table = [0 0 0; 0.0455 0.0635 0.1801; 0.2425 0.0873 0.1677;...
0.2089 0.2092 0.2546; 0.3111 0.2841 0.2274; 0.4785 0.3137 0.2624;...
0.5781 0.3580 0.3997; 0.5778 0.4510 0.5483; 0.5650 0.5682 0.6047;...
0.6803 0.6375 0.5722; 0.8454 0.6725 0.5855; 0.9801 0.7032 0.7007;...
1 0.7777 0.8915; 0.9645 0.8964 1; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Pastel
case 'pastel'
% High contrast, converts to linear scale in grey, strong
% pastel shades
table = [0 0 0; 0.4709 0 0.018; 0 0.3557 0.6747; 0.8422 0.1356 0.8525;
0.4688 0.6753 0.3057; 1 0.6893 0.0934; 0.9035 1 0; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Bright
case 'bright'
% High contrast, converts to linear scale in grey, strong
% saturated shades
table = [0 0 0; 0.3071 0.0107 0.3925; 0.007 0.289 1; 1 0.0832 0.7084;
1 0.4447 0.1001; 0.5776 0.8360 0.4458; 0.9035 1 0; 1 1 1];
[I limits] = interp_map(I, limits, reverseMap, table);
%% Jet2
case 'jet2'
% Like jet, but starts in black and goes to saturated red
[I limits] = interp_map(I, limits, reverseMap, [0 0 0; 0.5 0 0.5; 0 0 0.9; 0 1 1; 0 1 0; 1 1 0; 1 0 0]);
%% Hot2
case 'hot2'
% Like hot, but equally spaced
[I limits] = intensity(I, limits, reverseMap); % Intensity map
I = I * 3;
I = [I, I-1, I-2];
I = min(max(I(:), 0), 1); % Truncate
%% Bone2
case 'bone2'
% Like bone, but equally spaced
[I limits] = intensity(I, limits, reverseMap); % Intensity map
J = [I-2/3, I-1/3, I];
J = reshape(max(min(J(:), 1/3), 0), [], 3) * (2 / 5);
I = I * (13 / 15);
I = J + I(:,[1 1 1]);
%% Unknown colourmap
otherwise
error('Colormap ''%s'' not recognised.', map);
end
return
%% Display image
function display_image(I, map, limits, reverseMap)
% Clear the axes
cla(gca, 'reset');
% Display the image - using image() is fast
hIm = image(I);
% Get handles to the figure and axes (now, as the axes may have
% changed)
hFig = gcf; hAx = gca;
% Axes invisible and equal
set(hFig, 'Units', 'pixels');
set(hAx, 'Visible', 'off', 'DataAspectRatio', [1 1 1], 'DrawMode', 'fast');
% Set data for a colorbar
if ~isempty(limits) && limits(1) ~= limits(2)
colBar = (0:255) * ((limits(2) - limits(1)) / 255) + limits(1);
colBar = squeeze(sc(colBar, map, limits));
if reverseMap
colBar = colBar(end:-1:1,:);
end
set(hFig, 'Colormap', colBar);
set(hAx, 'CLim', limits);
set(hIm, 'CDataMapping', 'scaled');
end
% Only resize image if it is alone in the figure
if numel(findobj(get(hFig, 'Children'), 'Type', 'axes')) > 1
return
end
% Could still be the first subplot - do another check
axesPos = get(hAx, 'Position');
if isequal(axesPos, get(hFig, 'DefaultAxesPosition'))
% Default position => not a subplot
% Fill the window
set(hAx, 'Units', 'normalized', 'Position', [0 0 1 1]);
axesPos = [0 0 1 1];
end
if ~isequal(axesPos, [0 0 1 1]) || strcmp(get(hFig, 'WindowStyle'), 'docked')
% Figure not alone, or docked. Either way, don't resize.
return
end
% Get the size of the monitor we're on
figPosCur = get(hFig, 'Position');
MonSz = get(0, 'MonitorPositions');
MonOn = size(MonSz, 1);
if MonOn > 1
figCenter = figPosCur(1:2) + figPosCur(3:4) / 2;
figCenter = MonSz - repmat(figCenter, [MonOn 2]);
MonOn = all(sign(figCenter) == repmat([-1 -1 1 1], [MonOn 1]), 2);
MonOn(1) = MonOn(1) | ~any(MonOn);
MonSz = MonSz(MonOn,:);
end
MonSz(3:4) = MonSz(3:4) - MonSz(1:2) + 1;
% Check if the window is maximized
% This is a hack which may only work on Windows! No matter, though.
if isequal(MonSz([1 3]), figPosCur([1 3]))
% Leave maximized
return
end
% Compute the size to set the window
MaxSz = MonSz(3:4) - [20 120];
ImSz = [size(I, 2) size(I, 1)];
RescaleFactor = min(MaxSz ./ ImSz);
if RescaleFactor > 1
% Integer scale for enlarging, but don't make too big
MaxSz = min(MaxSz, [1000 680]);
RescaleFactor = max(floor(min(MaxSz ./ ImSz)), 1);
end
figPosNew = ceil(ImSz * RescaleFactor);
% Don't move the figure if the size isn't changing
if isequal(figPosCur(3:4), figPosNew)
return
end
% Keep the centre of the figure stationary
figPosNew = [max(1, floor(figPosCur(1:2)+(figPosCur(3:4)-figPosNew)/2)) figPosNew];
% Ensure the figure bar is in bounds
figPosNew(1:2) = min(figPosNew(1:2), MonSz(1:2)+MonSz(3:4)-[6 101]-figPosNew(3:4));
set(hFig, 'Position', figPosNew);
return
%% Parse input variables
function [map limits mask] = parse_inputs(I, inputs, y, x)
% Check the first two arguments for the colormap and limits
ninputs = numel(inputs);
map = 'none';
limits = [];
mask = 1;
for a = 1:min(2, ninputs)
if ischar(inputs{a}) && numel(inputs{a}) > 1
% Name of colormap
map = inputs{a};
elseif isnumeric(inputs{a})
[p q r] = size(inputs{a});
if (p * q * r) == 2
% Limits
limits = double(inputs{a});
elseif p > 1 && (q == 3 || q == 4) && r == 1
% Table-based colormap
map = inputs{a};
else
break;
end
else
break;
end
mask = mask + 1;
end
% Check for following inputs
if mask > ninputs
mask = cell(2, 0);
return
end
% Following inputs must either be colour/mask pairs, or a colour for NaNs
if ninputs - mask == 0
mask = cell(2, 1);
mask{1} = inputs{end};
mask{2} = ~all(isfinite(I), 3);
elseif mod(ninputs-mask, 2) == 1
mask = reshape(inputs(mask:end), 2, []);
else
error('Error parsing inputs');
end
% Go through pairs and generate
for a = 1:size(mask, 2)
% Generate any masks from functions
if isa(mask{2,a}, 'function_handle')
mask{2,a} = mask{2,a}(I);
end
if ~islogical(mask{2,a})
error('Mask is not a logical array');
end
if ~isequal(size(mask{2,a}), [y x])
error('Mask does not match image size');
end
if ischar(mask{1,a})
if numel(mask{1,a}) == 1
% Generate colours from MATLAB colour strings
mask{1,a} = double(dec2bin(strfind('kbgcrmyw', mask{1,a})-1, 3)) - double('0');
else
% Assume it's a colormap name
mask{1,a} = sc(I, mask{1,a});
end
end
mask{1,a} = reshape(mask{1,a}, [], 3);
if size(mask{1,a}, 1) ~= y*x && size(mask{1,a}, 1) ~= 1
error('Replacement color/image of unexpected dimensions');
end
if size(mask{1,a}, 1) ~= 1
mask{1,a} = mask{1,a}(mask{2,a},:);
end
end
return
%% Grey
function [I limits] = grey(I, limits, reverseMap)
% Greyscale
[I limits] = intensity(I, limits, reverseMap);
I = I(:,[1 1 1]);
return
%% RGB2grey
function [I limits] = rgb2grey(I, limits, reverseMap)
% Compress RGB to greyscale
if size(I, 2) == 3
I = I * [0.299; 0.587; 0.114];
end
[I limits] = grey(I, limits, reverseMap);
return
%% RGB2YUV
function [I limits] = rgb2yuv(I)
% Convert RGB to YUV - not for displaying or saving to disk!
if size(I, 2) ~= 3
error('rgb2yuv requires a 3 channel image');
end
I = I * [0.299, -0.14713, 0.615; 0.587, -0.28886, -0.51498; 0.114, 0.436, -0.10001];
limits = []; % This colourmap doesn't have a valid colourbar
return
%% Phase helper
function I = phase_helper(I, limits, n)
I(:,1) = mod(I(:,1)/(2*pi), 1);
I(:,2) = I(:,2) - limits(1);
I(:,2) = I(:,2) * (n / (limits(2) - limits(1)));
I(:,3) = n - I(:,2);
I(:,[2 3]) = min(max(I(:,[2 3]), 0), 1);
I = hsv2rgb(reshape(I, [], 1, 3));
return
%% Jet helper
function [I limits] = jet_helper(I, limits, reverseMap)
% Dark blue to dark red, through green
[I limits] = intensity(I, limits, reverseMap);
I = I * 4;
I = [I-3, I-2, I-1];
I = 1.5 - abs(I);
I = reshape(min(max(I(:), 0), 1), size(I));
return
%% HSV helper
function I = hsv_helper(I)
I = I * 6;
I = abs([I-3, I-2, I-4]);
I(:,1) = I(:,1) - 1;
I(:,2:3) = 2 - I(:,2:3);
I = reshape(min(max(I(:), 0), 1), size(I));
return
%% Bled
function [I limits] = bled(I, limits, reverseMap)
% Black to red through blue
[I limits] = intensity(I, limits, reverseMap);
J = reshape(hsv_helper(I), [], 3);
if exist('bsxfun', 'builtin')
I = bsxfun(@times, I, J);
else
I = J .* I(:,[1 1 1]);
end
return
%% Normalize
function [I limits] = normalize(I, limits)
if isempty(limits)
limits = isfinite(I);
if ~any(reshape(limits, numel(limits), 1))
% All NaNs, Infs or -Infs
I = double(I > 0);
limits = [0 1];
return
end
limits = [min(I(limits)) max(I(limits))];
I = I - limits(1);
if limits(2) ~= limits(1)
I = I * (1 / (limits(2) - limits(1)));
end
else
I = I - limits(1);
if limits(2) ~= limits(1)
I = I * (1 / (limits(2) - limits(1)));
end
I = reshape(min(max(reshape(I, numel(I), 1), 0), 1), size(I));
end
return
%% Intensity maps
function [I limits] = intensity(I, limits, reverseMap)
% Squash to 1d using L2 norm
if size(I, 2) > 1
I = sqrt(sum(I .^ 2, 2));
end
% Determine and scale to limits
[I limits] = normalize(I, limits);
if reverseMap
% Invert after everything
I = 1 - I;
end
return
%% Interpolate table-based map
function [I limits] = interp_map(I, limits, reverseMap, map)
% Convert to intensity
[I limits] = intensity(I, limits, reverseMap);
% Compute indices and offsets
if size(map, 2) == 4
bins = map(1:end-1,4);
cbins = cumsum(bins);
bins = bins ./ cbins(end);
cbins = cbins(1:end-1) ./ cbins(end);
if exist('bsxfun', 'builtin')
ind = bsxfun(@gt, I(:)', cbins(:));
else
ind = repmat(I(:)', [numel(cbins) 1]) > repmat(cbins(:), [1 numel(I)]);
end
ind = min(sum(ind), size(map, 1) - 2) + 1;
bins = 1 ./ bins;
cbins = [0; cbins];
I = (I - cbins(ind)) .* bins(ind);
else
n = size(map, 1) - 1;
I = I(:) * n;
ind = min(floor(I), n-1);
I = I - ind;
ind = ind + 1;
end
if exist('bsxfun', 'builtin')
I = bsxfun(@times, map(ind,1:3), 1-I) + bsxfun(@times, map(ind+1,1:3), I);
else
I = map(ind,1:3) .* repmat(1-I, [1 3]) + map(ind+1,1:3) .* repmat(I, [1 3]);
end
return
%% Index images
function [J limits num_vals] = index_im(I)
% Returns an index image
if size(I, 2) ~= 1
error('Index maps only work on single channel images');
end
J = round(I);
rescaled = any(abs(I - J) > 0.01);
if rescaled
% Appears not to be an index image. Rescale over 256 indices
m = min(I);
m = m * (1 - sign(m) * eps);
I = I - m;
I = I * (256 / max(I(:)));
J = ceil(I);
num_vals = 256;
elseif nargout > 2
% Output the number of values
J = J - (min(J) - 1);
num_vals = max(J);
end
% These colourmaps don't have valid colourbars
limits = [];
return
%% Calculate principle components
function I = calc_prin_comps(I, numComps)
if nargin < 2
numComps = size(I, 2);
end
% Do SVD
[I S] = svd(I, 0);
% Calculate projection of data onto components
S = diag(S(1:numComps,1:numComps))';
if exist('bsxfun', 'builtin')
I = bsxfun(@times, I(:,1:numComps), S);
else
I = I(:,1:numComps) .* S(ones(size(I, 1), 1, 'uint8'),:);
end
return
%% Demo function to show capabilities of sc
function demo
%% Demo gray & lack of border
figure; fig = gcf; Z = peaks(256); sc(Z);
display_text([...
' Lets take a standard, MATLAB, real-valued function:\n\n peaks(256)\n\n'...
' Calling:\n\n figure\n Z = peaks(256);\n sc(Z)\n\n'...
' gives (see figure). SC automatically scales intensity to fill the\n'...
' truecolor range of [0 1].\n\n'...
' If your figure isn''t docked, then the image will have no border, and\n'...
' will be magnified by an integer factor (in this case, 2) so that the\n'...
' image is a reasonable size.']);
%% Demo colour image display
figure(fig); clf;
load mandrill; mandrill = ind2rgb(X, map); sc(mandrill);
display_text([...
' That wasn''t so interesting. The default colormap is ''none'', which\n'...
' produces RGB images given a 3-channel input image, otherwise it produces\n'...
' a grayscale image. So calling:\n\n load mandrill\n'...
' mandrill = ind2rgb(X, map);\n sc(mandrill)\n\n gives (see figure).']);
%% Demo discretization
figure(fig); clf;
subplot(121); sc(Z, 'jet'); label(Z, 'sc(Z, ''jet'')');
subplot(122); imagesc(Z); axis image off; colormap(jet(64)); % Fix the fact we change the default depth
label(Z, 'imagesc(Z); axis image off; colormap(''jet'');');
display_text([...
' However, if we want to display intensity images in color we can use any\n'...
' of the MATLAB colormaps implemented (most of them) to give truecolor\n'...
' images. For example, to use ''jet'' simply call:\n\n'...
' sc(Z, ''jet'')\n\n'...
' The MATLAB alternative, shown on the right, is:\n\n'...
' imagesc(Z)\n axis equal off\n colormap(jet)\n\n'...
' which generates noticeable discretization artifacts.']);
%% Demo intensity colourmaps
figure(fig); clf;
subplot(221); sc(Z, 'hsv'); label(Z, 'sc(Z, ''hsv'')');
subplot(222); sc(Z, 'colorcube'); label(Z, 'sc(Z, ''colorcube'')');
subplot(223); sc(Z, 'contrast'); label(Z, 'sc(Z, ''contrast'')');
subplot(224); sc(Z-round(Z), 'diff'); label(Z, 'sc(Z-round(Z), ''diff'')');
display_text([...
' There are several other intensity colormaps to choose from. Calling:\n\n'...
' help sc\n\n'...
' will give you a list of them. Here are several others demonstrated.']);
%% Demo saturation limits & colourmap reversal
figure(fig); clf;
subplot(121); sc(Z, [0 max(Z(:))], '-hot'); label(Z, 'sc(Z, [0 max(Z(:))], ''-hot'')');
subplot(122); sc(mandrill, [-0.5 0.5]); label(mandrill, 'sc(mandrill, [-0.5 0.5])');
display_text([...
' SC can also rescale intensity, given an upper and lower bound provided\n'...
' by the user, and invert most colormaps simply by prefixing a ''-'' to the\n'...
' colormap name. For example:\n\n'...
' sc(Z, [0 max(Z(:))], ''-hot'');\n'...
' sc(mandrill, [-0.5 0.5]);\n\n'...
' Note that the order of the colormap and limit arguments are\n'...
' interchangable.']);
%% Demo prob
load gatlin;
gatlin = X;
figure(fig); clf; im = cat(3, abs(Z)', gatlin(1:256,end-255:end)); sc(im, 'prob');
label(im, 'sc(cat(3, prob, gatlin), ''prob'')');
display_text([...
' SC outputs the recolored data as a truecolor RGB image. This makes it\n'...
' easy to combine colormaps, either arithmetically, or by masking regions.\n'...
' For example, we could combine an image and a probability map\n'...
' arithmetically as follows:\n\n'...
' load gatlin\n'...
' gatlin = X(1:256,end-255:end);\n'...
' prob = abs(Z)'';\n'...
' im = sc(prob, ''hsv'') .* sc(prob, ''gray'') + sc(gatlin, ''rgb2gray'');\n'...
' sc(im, [-0.1 1.3]);\n\n'...
' In fact, that particular colormap has already been implemented in SC.\n'...
' Simply call:\n\n'...
' sc(cat(3, prob, gatlin), ''prob'');']);
%% Demo colorbar
colorbar;
display_text([...
' SC also makes possible the generation of a colorbar in the normal way, \n'...
' with all the colours and data values correct. Simply call:\n\n'...
' colorbar\n\n'...
' The colorbar doesn''t work with all colormaps, but when it does,\n'...
' inverting the colormap (using ''-map'') maintains the integrity of the\n'...
' colorbar (i.e. it works correctly) - unlike if you invert the input data.']);
%% Demo combine by masking
figure(fig); clf;
sc(Z, [0 max(Z(:))], '-hot', sc(Z-round(Z), 'diff'), Z < 0);
display_text([...
' It''s just as easy to combine generated images by masking too. Here''s an\n'...
' example:\n\n'...
' im = cat(4, sc(Z, [0 max(Z(:))], ''-hot''), sc(Z-round(Z), ''diff''));\n'...
' mask = repmat(Z < 0, [1 1 3]);\n'...
' mask = cat(4, mask, ~mask);\n'...
' im = sum(im .* mask, 4);\n'...
' sc(im)\n\n'...
' In fact, SC can also do this for you, by adding image/colormap and mask\n'...
' pairs to the end of the argument list, as follows:\n\n'...
' sc(Z, [0 max(Z(:))], ''-hot'', sc(Z-round(Z), ''diff''), Z < 0);\n\n'...
' A benefit of the latter approach is that you can still display a\n'...
' colorbar for the first colormap.']);
%% Demo texture map
figure(fig); clf;
surf(Z, sc(Z, 'contrast'), 'edgecolor', 'none');
display_text([...
' Other benefits of SC outputting the image as an array are that the image\n'...
' can be saved straight to disk using imwrite() (if you have the image\n'...
' processing toolbox), or can be used to texture map a surface, thus:\n\n'...
' tex = sc(Z, ''contrast'');\n'...
' surf(Z, tex, ''edgecolor'', ''none'');']);
%% Demo compress
load mri;
mri = D;
close(fig); % Only way to get round loss of focus (bug?)
figure(fig); clf;
sc(squeeze(mri(:,:,:,1:6)), 'compress');
display_text([...
' For images with more than 3 channels, SC can compress these images to RGB\n'...
' while maintaining the maximum amount of variance in the data. For\n'...
' example, this 6 channel image:\n\n'...
' load mri\n mri = D;\n sc(squeeze(mri(:,:,:,1:6), ''compress'')']);
%% Demo multiple images
figure(fig); clf; im = sc(mri, 'bone');
for a = 1:12
subplot(3, 4, a);
sc(im(:,:,:,a));
end
display_text([...
' SC can process multiple images for export when passed in as a 4d array.\n'...
' For example:\n\n'...
' im = sc(mri, ''bone'')\n'...
' for a = 1:12\n'...
' subplot(3, 4, a);\n'...
' sc(im(:,:,:,a));\n'...
' end']);
%% Demo user defined colormap
figure(fig); clf; sc(abs(Z), rand(10, 3)); colorbar;
display_text([...
' Finally, SC can use user defined colormaps to display indexed images.\n'...
' These can be defined as a linear colormap. For example:\n\n'...
' sc(abs(Z), rand(10, 3))\n colorbar;\n\n'...
' Note that the colormap is automatically linearly interpolated.']);
%% Demo non-linear user defined colormap
figure(fig); clf; sc(abs(Z), [rand(10, 3) exp((1:10)/2)']); colorbar;
display_text([...
' Non-linear colormaps can also be defined by the user, by including the\n'...
' relative distance between the given colormap points on the colormap\n'...
' scale in the fourth column of the colormap matrix. For example:\n\n'...
' sc(abs(Z), [rand(10, 3) exp((1:10)/2)''])\n colorbar;\n\n'...
' Note that the colormap is still linearly interpolated between points.']);
clc; fprintf('End of demo.\n');
return
%% Some helper functions for the demo
function display_text(str)
clc;
fprintf([str '\n\n']);
fprintf('Press a key to go on.\n');
figure(gcf);
waitforbuttonpress;
return
function label(im, str)
text(size(im, 2)/2, size(im, 1)+12, str,...
'Interpreter', 'none', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
return
|
github
|
thejihuijin/VideoDilation-master
|
compute_OF.m
|
.m
|
VideoDilation-master/opticalFlow/compute_OF.m
| 739 |
utf_8
|
94ea800e5b3a4b7ef848c0cf94fe2ad2
|
% COMPUTE_OF returns the optical flow magnitudes for a given video
% Currently uses Horn Schunck
% Assumes input video is in grey scale
% Dimensions = (rows, cols, frames)
%
% vid : 3D video matrix
%
% flow_mags : 3D Optical Flow magnitudes
function [flow_mags] = compute_OF(vid)
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
[rows,cols,n_frames] = size(vid);
OF = opticalFlowHS();
flow_mags = zeros(rows,cols,n_frames);
for i = 1:n_frames
% Store magnitude frames
flow = estimateFlow(OF, vid(:,:,i));
flow_mags(:,:,i) = flow.Magnitude;
end
end
|
github
|
thejihuijin/VideoDilation-master
|
vidToMat.m
|
.m
|
VideoDilation-master/videoDilation/vidToMat.m
| 854 |
utf_8
|
8f4d19cf089e628cb93ed6b3f7b25844
|
% VIDTOMAT Convert a RGB video file to a 4D matrix of image frames
%
% INPUT
% filename : String filename of video
%
% OUTPUT
% vidMatrix : 4D matrix of rgb frames
% frame_rate : Framerate at which the video file was encoded
function [vidMatrix, frame_rate] = vidToMat( filename )
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
v = VideoReader(filename);
rows = v.Height;
cols = v.Width;
frame_rate = v.FrameRate;
num_frames = floor(v.duration * frame_rate);
% Read each frame sequentially
vidMatrix = zeros(rows, cols, 3, num_frames);
for i = 1:num_frames
frame = readFrame(v);
vidMatrix(:,:,:,i) = im2double(frame);
end
end
|
github
|
thejihuijin/VideoDilation-master
|
playDilatedFrames.m
|
.m
|
VideoDilation-master/videoDilation/playDilatedFrames.m
| 1,958 |
utf_8
|
a2c1f2cad1274451be6b2d79a8233abf
|
% PLAYDILATEDFRAMES Plays the frames as designated by the vector of
% indices, frameIndices, at a constant framerate.
%
% INPUTS
% vidMat : 3D or 4D video matrix
% frameIndices : Vector of indices into vidMat to be played sequentially
% fr : Constant framerate at which to play frames
% dilated_fr : Variable framerate at which each frame from vidMat is played
%
% OUTPUTS
% None - plays video in last opened figure
function [] = playDilatedFrames( vidMat, frameIndices, fr, dilated_fr )
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Grab number of frames
if length(size(vidMat)) == 4
[~, ~, ~, frames] = size(vidMat);
else
[~, ~, frames] = size(vidMat);
end
% Catch off-by-one error and correct
if frames < frameIndices(end)
disp(['Frame index (' num2str(frameIndices(end)) ') greater than '...
' total number of frames (' num2str(frames) ')' ])
frameIndices(end) = frames;
disp(['Changed last frame index to ' num2str(frames)])
end
% Play video frames sequentially by repeating calls to imagesc
currTime = 0;
if length(size(vidMat)) == 4
for i = 1:length(frameIndices)
imagesc(vidMat(:,:,:,frameIndices(i)))
axis off
title(['Dilated @ ' sprintf('%.1f',dilated_fr(frameIndices(i))) ...
' fps - ' sprintf('%.2f',currTime) ' seconds elapsed'])
pause( 1/fr );
currTime = currTime + 1/fr;
end
else
for i = 1:length(frameIndices)
colormap gray
imagesc(vidMat(:,:,frameIndices(i)))
title(['Dilated @ ' sprintf('%.1f',dilated_fr(frameIndices(i))) ...
' fps - ' sprintf('%.2f',currTime) ' seconds elapsed'])
pause( 1/fr );
currTime = currTime + 1/fr;
end
end
end
|
github
|
thejihuijin/VideoDilation-master
|
compute_energy.m
|
.m
|
VideoDilation-master/videoDilation/compute_energy.m
| 2,922 |
utf_8
|
35abf09cb0299c8c80c0dfce81728436
|
% COMPUTE_ENERGY Converts heat maps to energy of frame.
% Frames with higher energy will be slowed down and frames with lower
% energy will be sped up.
% Heat Maps are assumed to be 3D matrices with the same number of "frames".
% Size of individual frames may differ between different heat maps
%
% OF_mags : Optical Flow Magnitudes, assumed to be same size as original
% video
% saliencyMaps : Saliency of each frame
% tsaliencyMaps : Time-Weighted saliency map of each frame
% method : string determining which heat map to use. Options:
% - 'OF' - Optical Flow Magnitudes
% - 'TSAL' - Time-Weighted Saliency Maps
% - 'MOF' - Saliency Masked Optical Flow
% pool : String determining which pooling function to use. Options:
% - 'MINK' - Minkowski Pooling, p = 2
% - 'WP' - Weighted Pooling, p = 1/2
% - 'FNS' - Five Number Summary
%
% normalized_energy : Energy calculated from heat maps normalized from 0 to
% 1. Of dimension (1, n_frames)
function [normalized_energy] = compute_energy(OF_mags, saliencyMaps, tsaliencyMaps, method, pool)
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Check Parameters
if ~exist('method','var')
method = 'OF';
end
if ~exist('pool','var')
pool = 'WP';
end
% Extract Dimensions
[rows, cols, n_frames] = size(OF_mags);
% Compute Energy Maps depending on method
if strcmp(method,'OF')
% Use Optical Flow Magnitudes
energy_map = OF_mags;
elseif strcmp(method,'TSAL')
% Use time weighted saliency maps
energy_map = tsaliencyMaps;
elseif strcmp(method,'MOF')
% Use Saliency Masked Optical Flow
masked_flow_mags = zeros(rows,cols,n_frames);
for i = 1:n_frames
% Compute Saliency Mask
sal_mask = imresize(saliencyMaps(:,:,i),[rows, cols],'bilinear');
sal_mask = imbinarize(sal_mask);
masked_flow_mags(:,:,i) = OF_mags(:,:,i).*sal_mask;
end
energy_map = masked_flow_mags;
else
fprintf('Invalid method given.\n')
fprintf('Options:\n\t- OF - Optical Flow \n');
fprintf('\t- TSAL - Time Weighted Saliency\n');
fprintf('\t- MOF - Saliency Masked Optical Flow\n');
return;
end
% Compute Energy Function depending on pool
if strcmp(pool,'MINK')
% Minkowski, default p=2
normalized_energy = minkowski(energy_map);
elseif strcmp(pool,'WP')
% Weighted Pooling, default p=1/2
normalized_energy = weight_pool(energy_map);
elseif strcmp(pool,'FNS')
% Five Num Sum
normalized_energy = five_num_sum(energy_map);
else
fprintf('Invalid pooling function given.\n');
fprintf('Options:\n\t- MINK - Minkowski, p=2\n');
fprintf('\t- WP - Weighted Pooling, p=1/2\n');
fprintf('\t- FNS - Five Num Sum\n');
return;
end
end
|
github
|
thejihuijin/VideoDilation-master
|
playVidMat.m
|
.m
|
VideoDilation-master/videoDilation/playVidMat.m
| 1,804 |
utf_8
|
5cfd657016548630c075c86521cac133
|
% PLAYVIDMAT Plays a sequence of RGB or Grayscale frames with framerate
% determined by input framerate vector or scalar.
%
% INPUTS
% vidMat : 3D or 4D video matrix
% frameRates : Vector of variable framerates at which to play each frame of
% vidMat, or a constant at which to play the entire video.
%
% OUTPUTS
% None - plays video in last opened figure
function [] = playVidMat(vidMat, frameRates)
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Grab number of frames
if length(size(vidMat)) == 4
[~, ~, ~, frames] = size(vidMat);
else
[~, ~, frames] = size(vidMat);
end
% If input framerate is a constant, convert to a vector with that values
if length(frameRates) == 1
frameRates = frameRates * ones(1,frames);
end
% Catch framerate vector length error and play until last available frame
if frames ~= length(frameRates)
disp('Framerate vector and video matrix not equal length.')
if length(frameRates) < frames
frames = length(frameRates);
end
end
% Play video frames sequentially by repeating calls to imagesc
currTime = 0;
if length(size(vidMat)) == 4
for i = 1:frames
imagesc(vidMat(:,:,:,i))
axis off
title([sprintf('%.2f',currTime) ' seconds elapsed'])
pause( 1/frameRates(i) );
currTime = currTime + 1/frameRates(i);
end
else
for i = 1:frames
colormap gray
imagesc(vidMat(:,:,i))
title([sprintf('%.2f',currTime) ' seconds elapsed'])
pause( 1/frameRates(i) );
currTime = currTime + 1/frameRates(i);
end
end
end
|
github
|
thejihuijin/VideoDilation-master
|
resize_vid.m
|
.m
|
VideoDilation-master/videoDilation/resize_vid.m
| 967 |
utf_8
|
15405abf35c91807c072c1e51842aaa5
|
% RESIZE_VID Saves a video with new dimensions [newrows newcols]
% Input videos can be RGB or Greyscale
%
% inputName : Path to input video file
% outputName : Path and name for output video file
% newrows : Vertical size of resized video
% newcols : Horizontal size of resized video
function resize_vid(inputName,outputName,newrows,newcols)
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Read in Video
inputReader = VideoReader(inputName);
% Prepare output video
outputWriter = VideoWriter(outputName,'MPEG-4');
open(outputWriter);
while hasFrame(inputReader)
% Read in Frame
frame = readFrame(inputReader);
% Resize frame and write
outputFrame = imresize(frame, [newrows, newcols]);
writeVideo(outputWriter, outputFrame);
end
close(outputWriter);
fprintf('done\n');
end
|
github
|
thejihuijin/VideoDilation-master
|
adjustFR.m
|
.m
|
VideoDilation-master/videoDilation/adjustFR.m
| 1,452 |
utf_8
|
cbe748a493be302e2de00094db2b4c6c
|
% ADJUSTFR Extends the slowmo sections of a framerate vector to
% preemptively slow before 'exciting' segements and smoothly speed back up
% afterward.
%
% INPUTS
% frVect : vector w/ time-varying framerate
% timeShift : Time to shift slow/speedups by, in seconds
% fr : Framerate video was taken at
%
% OUTPUT
% frAdjusted : vector w/ time-varying framerate & time-padded slow/speedup
function frAdjusted = adjustFR( frVect, timeShift, fr )
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Compute derivative of FR
slope = conv(frVect, [1 -1], 'valid');
% Shift slowmo changes earlier, and shift speedup changes later
shift = round(timeShift*fr);
slope_adj = slope;
for i = 1+shift : length(slope)-shift
% Shift slowmo earlier
if slope(i) < 0
slope_adj(i-shift) = slope_adj(i-shift) + slope(i);
% Shift speedup later
elseif slope(i) > 0
slope_adj(i+shift) = slope_adj(i+shift) + slope(i);
end
% Remove original slow/speedup
slope_adj(i) = slope_adj(i) - slope(i);
end
% Recover framerate from derivative and reset range to min-max of frVect
frAdjusted = cumsum([0 slope_adj]) + frVect(1);
frAdjusted = min(frAdjusted, max(frVect));
frAdjusted = max(frAdjusted, min(frVect));
end
|
github
|
thejihuijin/VideoDilation-master
|
rgbToGrayVid.m
|
.m
|
VideoDilation-master/videoDilation/rgbToGrayVid.m
| 696 |
utf_8
|
531aa72f922bf66a47ac0528f47a2a43
|
% RGBTOGRAYVID Convert a 4D RGB matrix to a 3D grayscale matrix
%
% INPUT
% rgbVidMatrix : matrix (rows x cols x 3 x frames)
%
% OUTPUT
% 3D matrix of a grayscale video
function grayVidMatrix = rgbToGrayVid( rgbVidMatrix )
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
% Sequentially convert each RGB frame to grayscale
[rows, cols, ~, frames] = size(rgbVidMatrix);
grayVidMatrix = zeros(rows,cols,frames);
for i = 1:frames
grayVidMatrix(:,:,i) = rgb2gray(rgbVidMatrix(:,:,:,i));
end
end
|
github
|
thejihuijin/VideoDilation-master
|
energy2fr.m
|
.m
|
VideoDilation-master/videoDilation/energy2fr.m
| 1,311 |
utf_8
|
e00baa8902e1f4f6046cdf77ced22078
|
% ENERGY2FR Converts energy to time padded frame rate
% Inverts an energy function, then scales it between -scale to scale and
% passes it through an exponential to determine speed up factor.
% Frame rate is then padded to begin slow down prior to "interesting"
% events
%
% energy : 1D energy function. High values will be slowed down
% fr : Original frame rate
% time_pad : Time to shift slows/speedups by, in seconds
% scale : Speed up/slow down factor, 2^scale
%
% fr_adj_smooth : new frame rate for each frame in original video
function [fr_adj_smooth] = energy2fr(energy,fr,time_pad,scale)
% ECE6258: Digital image processing
% School of Electrical and Computer Engineering
% Georgia Instiute of Technology
% Date Modified : 11/28/17
% By Erik Jorgensen ([email protected]), Jihui Jin ([email protected])
if ~exist('time_pad','var')
time_pad=.2;
end
if ~exist('scale','var')
scale=1;
end
energy_normal = 1-energy;
% Scale framerate to speed up
% Adjust framerate to exponential
fr_scaled = fr.*2.^(scale*(2*(energy_normal-mean(energy_normal))));
% time pad frame rate
fr_adj = adjustFR( fr_scaled, time_pad, fr );
% Smooth the adjusted framerate
mov_avg_window = 5;
fr_adj_smooth = movmean( fr_adj, mov_avg_window );
fr_adj_smooth = movmean( fr_adj_smooth, mov_avg_window );
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.