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
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/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
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/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
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/machine-learning-ex6/ex6/submit.m
1,318
utf_8
bfa0b4ffb8a7854d8e84276e91818107
function submit() addpath('./lib'); conf.assignmentSlug = 'support-vector-machines'; conf.itemName = 'Support Vector Machines'; conf.partArrays = { ... { ... '1', ... { 'gaussianKernel.m' }, ... 'Gaussian Kernel', ... }, ... { ... '2', ... { 'dataset3Params.m' }, ... 'Parameters (C, sigma) for Dataset 3', ... }, ... { ... '3', ... { 'processEmail.m' }, ... 'Email Preprocessing', ... }, ... { ... '4', ... { 'emailFeatures.m' }, ... 'Email Feature Extraction', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases x1 = sin(1:10)'; x2 = cos(1:10)'; ec = 'the quick brown fox jumped over the lazy dog'; wi = 1 + abs(round(x1 * 1863)); wi = [wi ; wi]; if partId == '1' sim = gaussianKernel(x1, x2, 2); out = sprintf('%0.5f ', sim); elseif partId == '2' load('ex6data3.mat'); [C, sigma] = dataset3Params(X, y, Xval, yval); out = sprintf('%0.5f ', C); out = [out sprintf('%0.5f ', sigma)]; elseif partId == '3' word_indices = processEmail(ec); out = sprintf('%d ', word_indices); elseif partId == '4' x = emailFeatures(wi); out = sprintf('%d ', x); end end
github
shawnngtq/machine-learning-master
porterStemmer.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/machine-learning-ex6/ex6/porterStemmer.m
9,902
utf_8
7ed5acd925808fde342fc72bd62ebc4d
function stem = porterStemmer(inString) % Applies the Porter Stemming algorithm as presented in the following % paper: % Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, % no. 3, pp 130-137 % Original code modeled after the C version provided at: % http://www.tartarus.org/~martin/PorterStemmer/c.txt % The main part of the stemming algorithm starts here. b is an array of % characters, holding the word to be stemmed. The letters are in b[k0], % b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since % matlab begins indexing by 1 instead of 0). k is readjusted downwards as % the stemming progresses. Zero termination is not in fact used in the % algorithm. % To call this function, use the string to be stemmed as the input % argument. This function returns the stemmed word as a string. % Lower-case string inString = lower(inString); global j; b = inString; k = length(b); k0 = 1; j = k; % With this if statement, strings of length 1 or 2 don't go through the % stemming process. Remove this conditional to match the published % algorithm. stem = b; if k > 2 % Output displays per step are commented out. %disp(sprintf('Word to stem: %s', b)); x = step1ab(b, k, k0); %disp(sprintf('Steps 1A and B yield: %s', x{1})); x = step1c(x{1}, x{2}, k0); %disp(sprintf('Step 1C yields: %s', x{1})); x = step2(x{1}, x{2}, k0); %disp(sprintf('Step 2 yields: %s', x{1})); x = step3(x{1}, x{2}, k0); %disp(sprintf('Step 3 yields: %s', x{1})); x = step4(x{1}, x{2}, k0); %disp(sprintf('Step 4 yields: %s', x{1})); x = step5(x{1}, x{2}, k0); %disp(sprintf('Step 5 yields: %s', x{1})); stem = x{1}; end % cons(j) is TRUE <=> b[j] is a consonant. function c = cons(i, b, k0) c = true; switch(b(i)) case {'a', 'e', 'i', 'o', 'u'} c = false; case 'y' if i == k0 c = true; else c = ~cons(i - 1, b, k0); end end % mseq() measures the number of consonant sequences between k0 and j. If % c is a consonant sequence and v a vowel sequence, and <..> indicates % arbitrary presence, % <c><v> gives 0 % <c>vc<v> gives 1 % <c>vcvc<v> gives 2 % <c>vcvcvc<v> gives 3 % .... function n = measure(b, k0) global j; n = 0; i = k0; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; while true while true if i > j return end if cons(i, b, k0) break; end i = i + 1; end i = i + 1; n = n + 1; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; end % vowelinstem() is TRUE <=> k0,...j contains a vowel function vis = vowelinstem(b, k0) global j; for i = k0:j, if ~cons(i, b, k0) vis = true; return end end vis = false; %doublec(i) is TRUE <=> i,(i-1) contain a double consonant. function dc = doublec(i, b, k0) if i < k0+1 dc = false; return end if b(i) ~= b(i-1) dc = false; return end dc = cons(i, b, k0); % cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant % and also if the second c is not w,x or y. this is used when trying to % restore an e at the end of a short word. e.g. % % cav(e), lov(e), hop(e), crim(e), but % snow, box, tray. function c1 = cvc(i, b, k0) if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0)) c1 = false; else if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y') c1 = false; return end c1 = true; end % ends(s) is TRUE <=> k0,...k ends with the string s. function s = ends(str, b, k) global j; if (str(length(str)) ~= b(k)) s = false; return end % tiny speed-up if (length(str) > k) s = false; return end if strcmp(b(k-length(str)+1:k), str) s = true; j = k - length(str); return else s = false; end % setto(s) sets (j+1),...k to the characters in the string s, readjusting % k accordingly. function so = setto(s, b, k) global j; for i = j+1:(j+length(s)) b(i) = s(i-j); end if k > j+length(s) b((j+length(s)+1):k) = ''; end k = length(b); so = {b, k}; % rs(s) is used further down. % [Note: possible null/value for r if rs is called] function r = rs(str, b, k, k0) r = {b, k}; if measure(b, k0) > 0 r = setto(str, b, k); end % step1ab() gets rid of plurals and -ed or -ing. e.g. % caresses -> caress % ponies -> poni % ties -> ti % caress -> caress % cats -> cat % feed -> feed % agreed -> agree % disabled -> disable % matting -> mat % mating -> mate % meeting -> meet % milling -> mill % messing -> mess % meetings -> meet function s1ab = step1ab(b, k, k0) global j; if b(k) == 's' if ends('sses', b, k) k = k-2; elseif ends('ies', b, k) retVal = setto('i', b, k); b = retVal{1}; k = retVal{2}; elseif (b(k-1) ~= 's') k = k-1; end end if ends('eed', b, k) if measure(b, k0) > 0; k = k-1; end elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0) k = j; retVal = {b, k}; if ends('at', b, k) retVal = setto('ate', b(k0:k), k); elseif ends('bl', b, k) retVal = setto('ble', b(k0:k), k); elseif ends('iz', b, k) retVal = setto('ize', b(k0:k), k); elseif doublec(k, b, k0) retVal = {b, k-1}; if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ... b(retVal{2}) == 'z' retVal = {retVal{1}, retVal{2}+1}; end elseif measure(b, k0) == 1 && cvc(k, b, k0) retVal = setto('e', b(k0:k), k); end k = retVal{2}; b = retVal{1}(k0:k); end j = k; s1ab = {b(k0:k), k}; % step1c() turns terminal y to i when there is another vowel in the stem. function s1c = step1c(b, k, k0) global j; if ends('y', b, k) && vowelinstem(b, k0) b(k) = 'i'; end j = k; s1c = {b, k}; % step2() maps double suffices to single ones. so -ization ( = -ize plus % -ation) maps to -ize etc. note that the string before the suffix must give % m() > 0. function s2 = step2(b, k, k0) global j; s2 = {b, k}; switch b(k-1) case {'a'} if ends('ational', b, k) s2 = rs('ate', b, k, k0); elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end; case {'c'} if ends('enci', b, k) s2 = rs('ence', b, k, k0); elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end; case {'e'} if ends('izer', b, k) s2 = rs('ize', b, k, k0); end; case {'l'} if ends('bli', b, k) s2 = rs('ble', b, k, k0); elseif ends('alli', b, k) s2 = rs('al', b, k, k0); elseif ends('entli', b, k) s2 = rs('ent', b, k, k0); elseif ends('eli', b, k) s2 = rs('e', b, k, k0); elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end; case {'o'} if ends('ization', b, k) s2 = rs('ize', b, k, k0); elseif ends('ation', b, k) s2 = rs('ate', b, k, k0); elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end; case {'s'} if ends('alism', b, k) s2 = rs('al', b, k, k0); elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0); elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0); elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end; case {'t'} if ends('aliti', b, k) s2 = rs('al', b, k, k0); elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0); elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end; case {'g'} if ends('logi', b, k) s2 = rs('log', b, k, k0); end; end j = s2{2}; % step3() deals with -ic-, -full, -ness etc. similar strategy to step2. function s3 = step3(b, k, k0) global j; s3 = {b, k}; switch b(k) case {'e'} if ends('icate', b, k) s3 = rs('ic', b, k, k0); elseif ends('ative', b, k) s3 = rs('', b, k, k0); elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end; case {'i'} if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end; case {'l'} if ends('ical', b, k) s3 = rs('ic', b, k, k0); elseif ends('ful', b, k) s3 = rs('', b, k, k0); end; case {'s'} if ends('ness', b, k) s3 = rs('', b, k, k0); end; end j = s3{2}; % step4() takes off -ant, -ence etc., in context <c>vcvc<v>. function s4 = step4(b, k, k0) global j; switch b(k-1) case {'a'} if ends('al', b, k) end; case {'c'} if ends('ance', b, k) elseif ends('ence', b, k) end; case {'e'} if ends('er', b, k) end; case {'i'} if ends('ic', b, k) end; case {'l'} if ends('able', b, k) elseif ends('ible', b, k) end; case {'n'} if ends('ant', b, k) elseif ends('ement', b, k) elseif ends('ment', b, k) elseif ends('ent', b, k) end; case {'o'} if ends('ion', b, k) if j == 0 elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t')) j = k; end elseif ends('ou', b, k) end; case {'s'} if ends('ism', b, k) end; case {'t'} if ends('ate', b, k) elseif ends('iti', b, k) end; case {'u'} if ends('ous', b, k) end; case {'v'} if ends('ive', b, k) end; case {'z'} if ends('ize', b, k) end; end if measure(b, k0) > 1 s4 = {b(k0:j), j}; else s4 = {b(k0:k), k}; end % step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. function s5 = step5(b, k, k0) global j; j = k; if b(k) == 'e' a = measure(b, k0); if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0)) k = k-1; end end if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1) k = k-1; end s5 = {b(k0:k), k};
github
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/machine-learning-ex6/ex6/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/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
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/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
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week07/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/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
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/machine-learning-ex7/ex7/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/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
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/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
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week08/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/machine-learning-ex8/ex8/submit.m
2,064
utf_8
7c4fcf60df3a7e09d05a74f7772fed3b
function submit() addpath('./lib'); conf.assignmentSlug = 'anomaly-detection-and-recommender-systems'; conf.itemName = 'Anomaly Detection and Recommender Systems'; conf.partArrays = { ... { ... '1', ... { 'estimateGaussian.m' }, ... 'Estimate Gaussian Parameters', ... }, ... { ... '2', ... { 'selectThreshold.m' }, ... 'Select Threshold', ... }, ... { ... '3', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Cost', ... }, ... { ... '4', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Gradient', ... }, ... { ... '5', ... { 'cofiCostFunc.m' }, ... 'Regularized Cost', ... }, ... { ... '6', ... { 'cofiCostFunc.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases n_u = 3; n_m = 4; n = 5; X = reshape(sin(1:n_m*n), n_m, n); Theta = reshape(cos(1:n_u*n), n_u, n); Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u); R = Y > 0.5; pval = [abs(Y(:)) ; 0.001; 1]; yval = [R(:) ; 1; 0]; params = [X(:); Theta(:)]; if partId == '1' [mu sigma2] = estimateGaussian(X); out = sprintf('%0.5f ', [mu(:); sigma2(:)]); elseif partId == '2' [bestEpsilon bestF1] = selectThreshold(yval, pval); out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]); elseif partId == '3' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', J(:)); elseif partId == '4' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', grad(:)); elseif partId == '5' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', J(:)); elseif partId == '6' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', grad(:)); end end
github
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/machine-learning-ex8/ex8/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/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
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/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
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week09/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/submit.m
1,605
utf_8
9b63d386e9bd7bcca66b1a3d2fa37579
function submit() addpath('./lib'); conf.assignmentSlug = 'logistic-regression'; conf.itemName = 'Logistic Regression'; conf.partArrays = { ... { ... '1', ... { 'sigmoid.m' }, ... 'Sigmoid Function', ... }, ... { ... '2', ... { 'costFunction.m' }, ... 'Logistic Regression Cost', ... }, ... { ... '3', ... { 'costFunction.m' }, ... 'Logistic Regression Gradient', ... }, ... { ... '4', ... { 'predict.m' }, ... 'Predict', ... }, ... { ... '5', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Cost', ... }, ... { ... '6', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))']; y = sin(X(:,1) + X(:,2)) > 0; if partId == '1' out = sprintf('%0.5f ', sigmoid(X)); elseif partId == '2' out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y)); elseif partId == '3' [cost, grad] = costFunction([0.25 0.5 -0.5]', X, y); out = sprintf('%0.5f ', grad); elseif partId == '4' out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X)); elseif partId == '5' out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1)); elseif partId == '6' [cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1); out = sprintf('%0.5f ', grad); end end
github
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week03/Programming Assignment/machine-learning-ex2/ex2/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
congzlwag/UnsupGenModbyMPS-master
tensor_product.m
.m
UnsupGenModbyMPS-master/matlab_code/tensor_product.m
1,985
utf_8
0aab341bb32bc59072d6bf91566b6350
function [C cindex] = tensor_product(varargin) % Author: Jing Chen [email protected] % varargin is cindex %C(cindex)=A(aindex)*B(bindex) % the same string in index will be summed up % A,B,C is muti dimention array %get all the permute order if nargin == 4 A = varargin{1}; aindex = varargin{2}; B = varargin{3}; bindex = varargin{4}; elseif nargin == 5 cindex = varargin{1}; A = varargin{2}; aindex = varargin{3}; B = varargin{4}; bindex = varargin{5}; end a_length = length ( aindex ); b_length = length ( bindex ); size_a = size(A); size_a(end+1:a_length) = 1; size_b = size(B); size_b(end+1:b_length) = 1; [com_in_a, com_in_b ] = find_common ( aindex, bindex ); if ~all(size_a(com_in_a)==size_b(com_in_b)) error('The dimention doesnot match!'); end diff_in_a = 1:a_length; diff_in_a ( com_in_a ) = []; diff_in_b = 1:b_length; diff_in_b ( com_in_b ) = []; temp_idx = [ aindex(diff_in_a) , bindex(diff_in_b) ]; if nargin ==5 [ ix1 ix2 ] = find_common ( temp_idx , cindex ); ix_temp (ix2) = ix1 ; else cindex = temp_idx; end c_length = length(cindex); % mutiply if any([ com_in_a diff_in_a ] ~= 1:a_length) A = permute( A, [ com_in_a diff_in_a ] ); end if any([ com_in_b diff_in_b ] ~= 1:b_length) B = permute( B, [ com_in_b diff_in_b ] ); end sda = prod(size_a(diff_in_a)); sc = prod(size_a(com_in_a)); sdb = prod(size_b(diff_in_b)); A = reshape(A,[sc,sda,1]); B = reshape(B,[sc,sdb,1]); C = A.' * B ; C = reshape(C,[size_a(diff_in_a),size_b(diff_in_b),1,1]); if c_length > 1 && nargin == 5 && any(ix_temp ~= 1:c_length) C = permute(C,ix_temp); end function [com_a, com_b] = find_common ( a, b) % find the common elements a = a.'; a_len = length( a ); b_len = length( b ); a = a(:,ones (1,b_len) ); b = b( ones(a_len ,1),:); %[b a] = meshgrid(b,a); [ com_a ,com_b ] = find ( a == b ); com_a = com_a.'; com_b = com_b.';
github
Moein-Khajehnejad/Automated-Classification-of-Right-Hand-and-Foot-Movement-EEG-Signals-master
mutation.m
.m
Automated-Classification-of-Right-Hand-and-Foot-Movement-EEG-Signals-master/Feature Selection by Genetic Algorithm/mutation.m
383
utf_8
693a8986fc3cce36ba68e225b78affbc
% function y = mutation(x,VarRange) %Gaussian mutation % nVar=numel(x); % j=randi([1 nVar]); % Varmin=min(VarRange); % Varmax=max(VarRange); % sigma= (Varmax-Varmin)/10; % y=x; % y(j)=x(j)+sigma * randn; % y=min(max(y, Varmin), Varmax)); % end function y = mutation(x) nVar=length(x); j1=randi([1 nVar-1]); j2=randi([j1+1 nVar]); nj1=x(j1); nj2=x(j2); x(j1)=nj2; x(j2)=nj1; y=x; end
github
kul-optec/nmpc-codegen-master
compare_libs_table.m
.m
nmpc-codegen-master/old_code/demos/Matlab/compare_libs_table.m
4,686
utf_8
51be9c2e097d0c560e6afb8ad713299f
% Compare the nmpc-codegen library with alternatives for different % obstacles. Print out a table with the timing results. clear all; addpath(genpath('../../src_matlab')); % noise_amplitude=[0;0;0]; noise_amplitude=[0.1;0.1;0.05]; shift_horizon=true; %% names={"controller_compare_libs","demo2","demo3"}; result_mean = zeros(length(names),7); result_min = zeros(length(names),7); result_max = zeros(length(names),7); for i=1:length(names) name=names{i}; % change this to demo1,demo2,demo3 or demo4 disp([ 'Simulating with ' name ':']); [ trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = demo_set_obstacles( name,shift_horizon ); % simulate with different methods [min_convergence_time,mean_convergence_time,max_convergence_time]= ... simulate_example(trailer_controller,initial_state,reference_state,... reference_input,obstacle_weights,shift_horizon,noise_amplitude); result_mean(i,:) = mean_convergence_time; result_min(i,:) = min_convergence_time; result_max(i,:) = max_convergence_time; end %% % Convert table to latex for i=1:length(names) columnLabels{i} = char(names{i}); end rowLabels = {'nmpc-codegen','panoc Matab','panoc draft','fmincon:interior-point','fmincon:sqp','fmincon:active-set','OPTI:ipopt'}; %% generate_latex_table = @(table_matrix,file_name) matrix2latex(table_matrix, file_name, 'rowLabels', rowLabels, 'columnLabels', columnLabels, 'alignment', 'c', 'format', '%-6.2e', 'size', 'tiny'); generate_latex_table(result_mean','tables/mean.tex'); generate_latex_table(result_max','tables/max.tex'); generate_latex_table(result_min','tables/min.tex'); result_mean_rel=result_mean; for i=length(rowLabels):-1:1 result_mean_rel(:,i) = result_mean(:,i)./result_mean(:,1); end generate_latex_rel_table = @(table_matrix,file_name) matrix2latex(table_matrix*100, file_name, 'rowLabels', rowLabels, 'columnLabels', columnLabels, 'alignment', 'c', 'format', '%-8.0f', 'size', 'tiny'); generate_latex_rel_table(result_mean_rel','tables/mean_rel.tex'); %% function [min_convergence_time,mean_convergence_time,max_convergence_time]= ... simulate_example(trailer_controller,initial_state,reference_state,... reference_input,obstacle_weights,shift_horizon,noise_amplitude) disp('Simulating using nmpc-codegen'); [~,time_history,~,simulator] = simulate_demo_trailer(trailer_controller,initial_state,reference_state,reference_input,obstacle_weights,noise_amplitude); disp('Simulating using ForBeS'); [~,time_history_forbes,~] = simulate_demo_trailer_panoc_matlab(trailer_controller,simulator,initial_state,reference_state,reference_input,shift_horizon,noise_amplitude); disp('Simulating using panoc draft'); [~,time_history_panoc_draft,~] = simulate_demo_trailer_panoc_draft(trailer_controller,simulator,initial_state,reference_state,reference_input,shift_horizon,noise_amplitude); disp('Simulating using fmincon ip'); [~,time_history_fmincon_interior_point] = simulate_demo_trailer_fmincon('interior-point',trailer_controller,simulator,initial_state,reference_state,reference_input,shift_horizon,noise_amplitude); disp('Simulating using fmincon sqp'); [~,time_history_fmincon_sqp] = simulate_demo_trailer_fmincon('sqp',trailer_controller,simulator,initial_state,reference_state,reference_input,shift_horizon,noise_amplitude); disp('Simulating using fmincon active set'); [~,time_history_fmincon_active_set] = simulate_demo_trailer_fmincon('active-set',trailer_controller,simulator,initial_state,reference_state,reference_input,shift_horizon,noise_amplitude); disp('Simulating using ipopt'); [ ~,time_history_ipopt ] = simulate_demo_trailer_OPTI_ipopt( trailer_controller,simulator, ... initial_state,reference_state,reference_input,obstacle_weights,shift_horizon,noise_amplitude ); clear simulator; min_convergence_time = [min(time_history) min(time_history_forbes) min(time_history_panoc_draft) min(time_history_fmincon_interior_point)... min(time_history_fmincon_sqp) min(time_history_fmincon_active_set) min(time_history_ipopt)]; max_convergence_time = [max(time_history) max(time_history_forbes) max(time_history_panoc_draft) max(time_history_fmincon_interior_point)... max(time_history_fmincon_sqp) max(time_history_fmincon_active_set) max(time_history_ipopt)]; mean_convergence_time = [mean(time_history) mean(time_history_forbes) mean(time_history_panoc_draft) mean(time_history_fmincon_interior_point)... mean(time_history_fmincon_sqp) mean(time_history_fmincon_active_set) mean(time_history_ipopt)]; end
github
kul-optec/nmpc-codegen-master
demo_set_obstacles.m
.m
nmpc-codegen-master/old_code/demos/Matlab/demo_set_obstacles.m
11,179
utf_8
bcfbf687601a2b72b0cc66b60fefac99
function [ trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = demo_set_obstacles( name,shift_horizon ) %DEMO_SET_OBSTACLES if(strcmp(name,"controller_compare_libs")) [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_controller_compare_libs(shift_horizon); elseif(strcmp(name,"demo1")) [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo1(shift_horizon); elseif(strcmp(name,"demo2")) [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo2(shift_horizon); elseif(strcmp(name,"demo3")) [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo3(shift_horizon); elseif(strcmp(name,"demo4")) [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo4(shift_horizon); else error("error name not found"); end end function [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_controller_compare_libs(shift_horizon) step_size=0.05; % Q and R matrixes determined by the control engineer. Q = diag([1. 1. 1.])*0.2; R = diag([1. 1.]) * 0.01; Q_terminal = diag([1. 1. 1])*10; R_terminal = diag([1. 1.]) * 0.01; controller_folder_name = 'demo_controller_matlab'; trailer_controller = prepare_demo_trailer(controller_folder_name,step_size,Q,R,Q_terminal,R_terminal); trailer_controller.horizon = 40; % NMPC parameter trailer_controller.integrator_casadi = true; % optional feature that can generate the integrating used in the cost function trailer_controller.panoc_max_steps = 2000; % the maximum amount of iterations the PANOC algorithm is allowed to do. trailer_controller.min_residual=-3; trailer_controller.lbgfs_buffer_size=50; % trailer_controller.pure_prox_gradient=true; trailer_controller.shift_input=shift_horizon; % is true by default % construct left circle circle1 = nmpccodegen.controller.obstacles.Circular([1.5; 0.], 1.,trailer_controller.model); circle2 = nmpccodegen.controller.obstacles.Circular([3.5; 2.], 0.6,trailer_controller.model); circle3 = nmpccodegen.controller.obstacles.Circular([2.; 2.5], 0.8,trailer_controller.model); circle4 = nmpccodegen.controller.obstacles.Circular([5.; 4.], 1.05,trailer_controller.model); % add obstacles to controller trailer_controller = trailer_controller.add_constraint(circle1); trailer_controller = trailer_controller.add_constraint(circle2); trailer_controller = trailer_controller.add_constraint(circle3); trailer_controller = trailer_controller.add_constraint(circle4); % generate the dynamic code trailer_controller = trailer_controller.generate_code(); % simulate everything initial_state = [0.; -0.5 ; pi/2]; reference_state = [7.; 5.; 0.8]; reference_input = [0; 0]; obstacle_weights = [700.;700.;700.;700.]; figure; hold on; circle1.plot(); circle2.plot(); circle3.plot(); circle4.plot(); end function [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo1(shift_horizon) step_size=0.03; % Q and R matrixes determined by the control engineer. Q = diag([1. 1. 0.01])*0.2; R = diag([1. 1.]) * 0.01; Q_terminal = Q; R_terminal = R; controller_folder_name = 'demo_controller_matlab'; trailer_controller = prepare_demo_trailer(controller_folder_name,step_size,Q,R,Q_terminal,R_terminal); %% trailer_controller.horizon = 30; % NMPC parameter trailer_controller.integrator_casadi = true; % optional feature that can generate the integrating used in the cost function trailer_controller.panoc_max_steps = 500; % the maximum amount of iterations the PANOC algorithm is allowed to do. trailer_controller.min_residual=-3; trailer_controller.shift_input=shift_horizon; % is true by default rectangular_center_coordinates = [0.45;-0.1]; rectangular_width = 0.4; rectangular_height = 0.1; rectangular = nmpccodegen.controller.obstacles.Rectangular(rectangular_center_coordinates,... rectangular_width,rectangular_height,trailer_controller.model); % construct left circle left_circle = nmpccodegen.controller.obstacles.Circular([0.2; 0.2],0.2,trailer_controller.model); % construct right circle right_circle = nmpccodegen.controller.obstacles.Circular([0.7; 0.2], 0.2,trailer_controller.model); % add obstacles to controller trailer_controller = trailer_controller.add_constraint(rectangular); trailer_controller = trailer_controller.add_constraint(left_circle); trailer_controller = trailer_controller.add_constraint(right_circle); % generate the dynamic code trailer_controller.generate_code(); %% % simulate everything initial_state = [0.45; 0.1; -pi/2]; reference_state = [0.8; -0.1; 0]; reference_input = [0; 0]; obstacle_weights = [10000.;8000.;50.]; figure; hold all; rectangular.plot(); left_circle.plot(); right_circle.plot(); end function [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo2(shift_horizon) step_size=0.03; % Q and R matrixes determined by the control engineer. Q = diag([1. 1. 0.01])*0.2; R = diag([1. 1.]) * 0.01; Q_terminal = Q; R_terminal = R; controller_folder_name = 'demo_controller_matlab'; trailer_controller = prepare_demo_trailer(controller_folder_name,step_size,Q,R,Q_terminal,R_terminal); %% trailer_controller.horizon = 50; % NMPC parameter trailer_controller.integrator_casadi = true; % optional feature that can generate the integrating used in the cost function trailer_controller.panoc_max_steps = 500; % the maximum amount of iterations the PANOC algorithm is allowed to do. trailer_controller.min_residual=-3; trailer_controller.lbgfs_buffer_size = 50; trailer_controller.shift_input=shift_horizon; % is true by default % construct upper rectangular rectangular_up = nmpccodegen.controller.obstacles.Rectangular([1;0.5],0.4,0.5,trailer_controller.model); % construct lower rectangular rectangular_down = nmpccodegen.controller.obstacles.Rectangular([1; -0.2], 0.4, 0.5,trailer_controller.model); % construct circle circle = nmpccodegen.controller.obstacles.Circular([0.2;0.2],0.2,trailer_controller.model); % add obstacles to controller trailer_controller = trailer_controller.add_constraint(rectangular_up); trailer_controller = trailer_controller.add_constraint(rectangular_down); trailer_controller = trailer_controller.add_constraint(circle); % generate the dynamic code trailer_controller.generate_code(); %% % simulate everything initial_state = [-0.1; -0.1; pi]; reference_state = [1.5; 0.4; 0]; reference_input = [0; 0]; obstacle_weights = [10.;10.;2000.]; figure; hold all; rectangular_up.plot(); rectangular_down.plot(); circle.plot(); end function [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo3(shift_horizon) step_size=0.03; % Q and R matrixes determined by the control engineer. Q = diag([1. 1. 0.01])*0.2; R = diag([1. 1.]) * 0.01; Q_terminal = Q; R_terminal = R; controller_folder_name = 'demo_controller_matlab'; trailer_controller = prepare_demo_trailer(controller_folder_name,step_size,Q,R,Q_terminal,R_terminal); %% trailer_controller.horizon = 50; % NMPC parameter trailer_controller.integrator_casadi = true; % optional feature that can generate the integrating used in the cost function trailer_controller.panoc_max_steps = 500; % the maximum amount of iterations the PANOC algorithm is allowed to do. trailer_controller.min_residual=-3; trailer_controller.lbgfs_buffer_size = 50; trailer_controller.shift_input=shift_horizon; % is true by default % construct upper rectangular costum_obstacle = nmpccodegen.controller.obstacles.Nonconvex_constraints(trailer_controller.model); h_0 = @(x) x(2)-x(1)^2; h_1 = @(x) 1 + (x(1)^2)/2 - x(2); costum_obstacle = costum_obstacle.add_constraint(h_0); costum_obstacle = costum_obstacle.add_constraint(h_1); % add obstacles to controller trailer_controller = trailer_controller.add_constraint(costum_obstacle); % trailer_controller = trailer_controller.add_general_constraint(costum_obstacle); % generate the dynamic code trailer_controller.generate_code(); %% % simulate everything initial_state = [-1.0; 0.0; pi/2]; reference_state = [-1.0; 2.; pi/3]; reference_input = [0; 0]; obstacle_weights = 1e3; figure; hold all; h_0_border = @(x) x.^2; h_1_border = @(x) 1 + (x.^2)/2; draw_obstacle_border(h_0_border,[-1.5;1.5],100); draw_obstacle_border(h_1_border, [-1.5;1.5], 100); end function [trailer_controller,initial_state,reference_state,reference_input,obstacle_weights ] = generate_demo4(shift_horizon) step_size=0.015; % Q and R matrixes determined by the control engineer. Q = diag([1. 1. 0.01])*0.2; R = diag([1. 1.]) * 0.1; Q_terminal = diag([1., 1., 0.1])*1; R_terminal = diag([1., 1.]) * 0.01; controller_folder_name = 'demo_controller_matlab'; trailer_controller = prepare_demo_trailer(controller_folder_name,step_size,Q,R,Q_terminal,R_terminal); %% trailer_controller.horizon = 50; % NMPC parameter trailer_controller.integrator_casadi = true; % optional feature that can generate the integrating used in the cost function trailer_controller.panoc_max_steps = 10000; % the maximum amount of iterations the PANOC algorithm is allowed to do. trailer_controller.min_residual=-3; trailer_controller.lbgfs_buffer_size = 50; trailer_controller.shift_input=shift_horizon; % is true by default % construct upper rectangular costum_obstacle = nmpccodegen.controller.obstacles.Nonconvex_constraints(trailer_controller.model); h_0 = @(x) x(2) - 2.*math.sin(-x(1)/2.); h_1 = @(x) 3.*sin(x(1)/2 -1) - x(2); h_2 = @(x) x(1) - 1; h_3 = @(x) 8 - x(1); costum_obstacle.add_constraint(h_0); costum_obstacle.add_constraint(h_1); costum_obstacle.add_constraint(h_2); costum_obstacle.add_constraint(h_3); % add obstacles to controller trailer_controller = trailer_controller.add_constraint(costum_obstacle); % generate the dynamic code trailer_controller.generate_code(); %% % simulate everything initial_state = [7; -1; -pi]; reference_state = [1.5; -2.; -pi]; reference_input = [0; 0]; obstacle_weights = 1e1; figure; hold all; h_0_border = @(x) 2.*sin(-x/2.); h_1_border = @(x) 3.*sin(x/2. -1.); draw_obstacle_border(h_0_border,[1;8],100) draw_obstacle_border(h_1_border, [1;8], 100) end
github
kul-optec/nmpc-codegen-master
simulate_demo_trailer_OPTI_ipopt.m
.m
nmpc-codegen-master/old_code/demos/Matlab/simulate_demo_trailer_OPTI_ipopt.m
2,641
utf_8
de13fac5910022b2d4c227a294a7112f
function [ state_history,time_history,iteration_history ] = simulate_demo_trailer_OPTI_ipopt( controller, simulator, ... initial_state,reference_state,reference_input,obstacle_weights,shift_horizon,noise_amplitude) %SIMULATE_DEMO_TRAILER_PANOC_MATLAB Summary of this function goes here % Detailed explanation goes here % -- simulate controller -- simulation_time = 3; number_of_steps = ceil(simulation_time / controller.model.step_size); % setup a simulator to test inputs = repmat(zeros(controller.model.number_of_inputs, 1), ... controller.horizon, 1); %% state = initial_state; state_history = zeros(controller.model.number_of_states, number_of_steps); time_history = zeros(number_of_steps,1); iteration_history = zeros(number_of_steps,1); for i=1:number_of_steps cost_f = @(x) simulator.evaluate_cost(... state,reference_state,reference_input,x); gradient_f = @(x) gradient_f_multiarg(... simulator,state,reference_state,reference_input,x); % Bounds lb = ones(controller.horizon*controller.model.number_of_inputs,1).*-4; ub = ones(controller.horizon*controller.model.number_of_inputs,1).*4; opts = optiset('solver','ipopt','tolrfun',1e-3,'tolafun',1e-3); % Opt = opti('fun',cost_f,'grad',gradient_f,'bounds', lb, ub,'options' ,opts); Opt = opti('fun',cost_f,'grad',gradient_f ,'bounds', lb, ub,'options' ,opts); to=tic; [x,fval,exitflag,info] = solve(Opt,inputs); time_history(i)=toc(to)*1000;% get time in ms inputs = x; iteration_history(i)=0; optimal_input=inputs(1:controller.model.number_of_inputs); if(shift_horizon) inputs(1:end-controller.model.number_of_inputs) = ... inputs(controller.model.number_of_inputs+1:end); end disp(['The optimal input is[' num2str(optimal_input(1)) ' ; ' num2str(optimal_input(2)) ']']); state = controller.model.get_next_state_double(state, optimal_input)+((rand - 0.5)*2)*noise_amplitude; state_history(:, i) = state; end disp("Final state:") disp(state) clear('sim'); % remove the simulator so it unloads the shared lib end %initial_state,state_reference,input_reference,location function [gradient] = gradient_f_multiarg(simulator,state,reference_state,reference_input,inputs_horizon) [cost,gradient] = simulator.evaluate_cost_gradient(... state,reference_state,reference_input,inputs_horizon); end
github
kul-optec/nmpc-codegen-master
simulate_OPTI_ipopt.m
.m
nmpc-codegen-master/old_code/demos/Matlab/quadcopter/simulate_OPTI_ipopt.m
2,684
utf_8
71726baf867043dd6698a0133bf8aee5
function [ state_history,time_history,iteration_history ] = simulate_OPTI_ipopt( controller, simulator, ... initial_state,reference_state,reference_input,obstacle_weights,shift_horizon,noise_amplitude) %SIMULATE_DEMO_TRAILER_PANOC_MATLAB Summary of this function goes here % Detailed explanation goes here % -- simulate controller -- simulation_time = 3; number_of_steps = ceil(simulation_time / controller.model.step_size); % setup a simulator to test inputs = repmat(zeros(controller.model.number_of_inputs, 1), ... controller.horizon, 1); %% state = initial_state; state_history = zeros(controller.model.number_of_states, number_of_steps); time_history = zeros(number_of_steps,1); iteration_history = zeros(number_of_steps,1); for i=1:number_of_steps cost_f = @(x) simulator.evaluate_cost(... state,reference_state,reference_input,x); gradient_f = @(x) gradient_f_multiarg(... simulator,state,reference_state,reference_input,x); % Bounds lb = ones(controller.horizon*controller.model.number_of_inputs,1).*0; ub = ones(controller.horizon*controller.model.number_of_inputs,1).*100; opts = optiset('solver','ipopt','tolrfun',1e-3,'tolafun',1e-3); % Opt = opti('fun',cost_f,'grad',gradient_f,'bounds', lb, ub,'options' ,opts); Opt = opti('fun',cost_f,'grad',gradient_f ,'bounds', lb, ub,'options' ,opts); to=tic; [x,fval,exitflag,info] = solve(Opt,inputs); time_history(i)=toc(to)*1000;% get time in ms inputs = x; iteration_history(i)=0; optimal_input=inputs(1:controller.model.number_of_inputs); if(shift_horizon) inputs(1:end-controller.model.number_of_inputs) = ... inputs(controller.model.number_of_inputs+1:end); end disp([ 'ipopt [' num2str(i) '/' num2str(number_of_steps) ']' 'The optimal input is[' num2str(optimal_input(1)) ' ; ' num2str(optimal_input(2)) ']']); state = controller.model.get_next_state_double(state, optimal_input)+((rand - 0.5)*2)*noise_amplitude; state_history(:, i) = state; end disp("Final state:") disp(state) clear('sim'); % remove the simulator so it unloads the shared lib end %initial_state,state_reference,input_reference,location function [gradient] = gradient_f_multiarg(simulator,state,reference_state,reference_input,inputs_horizon) [cost,gradient] = simulator.evaluate_cost_gradient(... state,reference_state,reference_input,inputs_horizon); end
github
kul-optec/nmpc-codegen-master
integrate.m
.m
nmpc-codegen-master/old_code/src_matlab/+nmpccodegen/+models/integrate.m
3,294
utf_8
cff2851dfdb4d749cddbd4c8206cd4fb
function [ next_state ] = integrate( state,step_size,function_system,key_name) %INTEGRATE Summary of this function goes here % Detailed explanation goes here next_state = integrate_lib(state,step_size,function_system,key_name); % if(key_name=='RK44') % for now only 1 integrator available % k1 = function_system(state); % k2 = function_system(state + step_size*k1/2); % k3 = function_system(state + step_size*k2/2); % k4 = function_system(state + step_size*k3); % next_state = state + (step_size/6)*(k1 + 2*k2 + 2*k3 + k4); % else % disp('ERROR invalid integrator'); % end end function [ x_new ] =integrate_lib(x,step_size,function_system,key_name) %INTEGRATE Integrate using an explicit integration tableau from ./integrator_tableaus % x : current state % step_size : discretizator step size % function_system : continious differential equation of the system % behavior % key_name : name of the integrator % BS5 Bogacki-Shampine RK5(4)8 % BuRK65 Butcher's RK65 % CMR6 Calvo 6(5) % DP5 Dormand-Prince RK5(4)7 % FE Forward Euler % Fehlberg45 Fehlberg RK5(4)6 % Heun33 Heun RK 33 % Lambert65 Lambert % MTE22 Minimal Truncation Error 22 % Merson43 Merson RK4(3) % Mid22 Midpoint Runge-Kutta % NSSP32 non-SSPRK 32 % NSSP33 non-SSPRK 33 % PD8 Prince-Dormand 8(7) % RK44 Classical RK4 % SSP104 SSPRK(10,4) % SSP22 SSPRK 22 % SSP22star SSPRK22star % SSP33 SSPRK 33 % SSP53 SSP 53 % SSP54 SSP 54 % SSP63 SSP 63 % SSP75 SSP 75 % SSP85 SSP 85 % SSP95 SSP 95 models_folder = fileparts(which('nmpccodegen.models.integrate')); integrator_folder = strcat(models_folder,'/integrator_tableaus/'); load(strcat(integrator_folder,key_name,'.mat')); number_of_states = length(x); [number_of_samples,~]=size(A); % phase 1: calculate the k's % k1 = f(x_n) % k2 = f(x_n + h(a_21 k_1)) % k3 = f(x_n + h(a_31 k_1 + a32 k2)) % ... k=casadi.SX.sym('k',number_of_states,number_of_samples); k(:,1) = function_system(x); for i=2:number_of_samples x_step=zeros(number_of_states,1); for j=1:i-1 x_step = x_step + A(i,j)*k(:,j); end x_step_scaled = x_step*step_size; x_local = x + x_step_scaled ; k(:,i) = function_system(x_local); end % phase 2: use k's to calculate next state % x_{n+1} = x_n + h \sum_{i=1}^s b_i \cdot k_i x_new=zeros(number_of_states,1); for i=1:number_of_samples x_new = x_new + k(:,i)*b(i); end x_new = x_new*step_size; x_new = x_new + x; end
github
kul-optec/nmpc-codegen-master
lbfgs.m
.m
nmpc-codegen-master/Matlab/lbfgs/lbfgs.m
1,665
utf_8
9b9248e31868782d232d95c5edd5f02f
% f=function % df=gradient of function % g_i=df(x(i)) % The buffer of length m contains 2 variables % s_i = x_{i+1} - x_{i} % y_i = g_{i+1} - g_{i} function [ s,y,new_x] = lbfgs(iteration_index,buffer_size,x,df,s,y) % if this is the first time, use the gradient descent if(iteration_index==1) direction=df(x); new_x = x-direction; % start to fill in the s(:,1) = new_x-x; y(:,1) = df(new_x) - df(x); else % if we dont have enough past values lower the max buffer size if(iteration_index<=buffer_size+1) buffer_size_max=iteration_index-1; else buffer_size_max=buffer_size; % maximum buffer size end q=df(x); rho=zeros(1,buffer_size_max); alpha=zeros(1,buffer_size_max); beta=zeros(1,buffer_size_max); % loop over most recent to oldest for i=1:buffer_size_max rho(i)=1/(y(:,i)'*s(:,i)); alpha(i) = rho(i)*s(:,i)'*q; q = q - alpha(i)*y(:,i); end z=(y(:,buffer_size_max)*s(:,buffer_size_max)'*q)... /(y(:,buffer_size_max)'*y(:,buffer_size_max)); for i=buffer_size_max:-1:1 % oldest first beta(i)=rho(i)*y(:,i)'*z; z=z+s(:,i)*(alpha(i) - beta(i)); end new_x = x - z; % z is upward direction % After the new values have been found, % fix the buffers for the next iteration. s(:,2:end)=s(:,1:end-1); y(:,2:end)=y(:,1:end-1); s(:,1) = new_x-x; y(:,1) = df(new_x) - df(x); end end
github
kul-optec/nmpc-codegen-master
myfun_poly.m
.m
nmpc-codegen-master/Matlab/lbfgs/lib/fminlbfgs_version2c/myfun_poly.m
227
utf_8
594dc9467dd6877b46a36211ac1475aa
% where myfun is a MATLAB function such as: % function [f,g] = myfun(x) % f = sum(sin(x) + 3); % if ( nargout > 1 ), g = cos(x); end function [f,g] = myfun_poly(x) f =x(1)^10 + x(2)^10; g = [10*x(1)^9; 10*x(2)^9 ]; end
github
kul-optec/nmpc-codegen-master
myfun.m
.m
nmpc-codegen-master/Matlab/lbfgs/lib/fminlbfgs_version2c/myfun.m
274
utf_8
01f35caf22b243254ec4046505457734
% where myfun is a MATLAB function such as: % function [f,g] = myfun(x) % f = sum(sin(x) + 3); % if ( nargout > 1 ), g = cos(x); end function [f,g] = myfun(x) a=1; b=100; f =(a-x(1))^2 + b*(x(2)-x(1))^2; g = [-2*(a-(b+1)*x(1)+b*x(2)); 2*b*(x(2)-x(1)) ]; end
github
andersonreisoares/DivideAndSegment-master
divSeg.m
.m
DivideAndSegment-master/divSeg.m
4,538
ibm852
c9126c6d7b43c01b35d43d612463aacf
% % The divide and segment method appears in % % Divide And Segment - An Alternative For Parallel Segmentation. TS Korting, % % EF Castejon, LMG Fonseca - GeoInfo, 97-104 % % Improvements of the divide and segment method for parallel image segmentation % % AR Soares, TS Körting, LMG Fonseca - Revista Brasileira de Cartografia 68 (6) % % % % Anderson Soares, Thales Korting and Emiliano Castejon - 23/10/17 % % % % ---INPUT--- % % img - input image % % filterOption - 1 for standard magnitude approach, 2 for Canny and 3 for directional % % approach (recommended) % % line_number - Nummber of lines to split the image (4 - divide in 16 tiles) % % vchunk - Vertical chunk size % % hchunk - horizontal chuck size % % max_displacement - maximum displacement to the crop line % % epsg - EPSG of image % % weight - You can add a weight to a specific band to highlight some important feature. function divSeg(img,line_number,filterOption,vchunk,hchunk,max_displacement,epsg,weight) if nargin < 6 disp('error: You must provide at least 6 parameters') return; end if nargin == 6 epsg = 32723; disp('warning: epsg defined as 32723') end if nargin == 8 disp('Adding weights to bands') end tic disp('Loading input image'); %Check if is a valid geotiff info = imfinfo(img); tag = isfield(info,'GeoKeyDirectoryTag'); [~, name ,~] = fileparts(info.Filename); if tag == 1 geoinfo = info.GeoKeyDirectoryTag; [img, R] = geotiffread(img); depth = info.BitsPerSample(1); else [img,~] = imread(img); end img = double(img); [~,~,d]= size(img); if ~exist('weight','var'), weight = ones(1,d); end [image_h, image_v] = filter_op(img, filterOption, weight); [line_cut_xcolumns_h, line_cut_yrows_h,line_cut_xcolumns_v,line_cut_yrows_v] = line_cut(image_h, image_v,line_number,vchunk,hchunk,max_displacement); %Show results figure(1); clf; if d>3 redChannel = imadjust(mat2gray(img(:, :, 3))); greenChannel = imadjust(mat2gray(img(:, :, 2))); blueChannel = imadjust(mat2gray(img(:, :, 1))); rgbImage = cat(3, redChannel, greenChannel, blueChannel); imshow(rgbImage); else imshow(img); end hold on; for i=1:line_number plot(line_cut_xcolumns_h{i}, line_cut_yrows_h{i},'linewidth', 2, 'Color', 'y'); plot(line_cut_yrows_v{i+1}, line_cut_xcolumns_v{i+1},'linewidth', 2, 'Color', 'y'); end hold off; % figure(2) % imshow(mat2gray(uint8(image_h))) % hold on; % for i=1:line_number % plot(line_cut_xcolumns_h{i}, line_cut_yrows_h{i},'linewidth', 2, 'Color', 'y'); % plot(line_cut_yrows_v{i+1}, line_cut_xcolumns_v{i+1},'linewidth', 2, 'Color', 'y'); % end % hold off; t1=toc; %Cropping i = 1; for h=1:line_number linha_hx = cell2mat(line_cut_xcolumns_h(h+1)); linha_hy = cell2mat(line_cut_yrows_h(h+1)); lim_hy = cell2mat(line_cut_yrows_h(h)); if h==1 [temp, temp2] = divide(img, linha_hy, linha_hx); else [temp, temp2] = divide(temph, linha_hy, linha_hx); end for v=1:line_number disp(['Creating tile: ',int2str(i)]); %Get line cut linha_vx = cell2mat(line_cut_xcolumns_v(v+1)); linha_vy = cell2mat(line_cut_yrows_v(v+1)); lim_vy = cell2mat(line_cut_yrows_v(v)); temp = permute(temp, [2 1 3]); [cut1, temp3] = divide(temp, linha_vy, linha_vx); cut1 = permute(cut1,[2 1 3]); temp3 = permute(temp3,[2 1 3]); %Subset image firstrow = min(lim_hy); lastrow = max(linha_hy); firstcol = min(lim_vy); lastcol = max(linha_vy); subImage = cut1(firstrow:lastrow, firstcol:lastcol, :); xi = [firstcol - .5, lastcol + .5]; yi = [firstrow - .5, lastrow + .5]; [xlimits, ylimits] = intrinsicToWorld(R, xi, yi); subR = R; subR.RasterSize = size(subImage); subR.XLimWorld = sort(xlimits); subR.YLimWorld = sort(ylimits); %Write image if tag==1 geotiffwrite([name, '_cut',int2str(i),'.tif'],subImage,subR,'CoordRefSysCode',epsg); i=i+1; else imwrite(cut1, [name, '_cut',int2str(i),'.tif'],'WriteMode', 'append'); i=i+1; end temp = temp3; clear cut1; end temph=temp2; end fprintf('Algorithm find the line cut after %.2f s \n',t1); %end
github
andersonreisoares/DivideAndSegment-master
dijkstra.m
.m
DivideAndSegment-master/dijkstra.m
1,422
utf_8
bcd87e1fec09ed7eecb50ee9e017bc41
%--------------------------------------------------- % Dijkstra Algorithm % author : Dimas Aryo % email : [email protected] % %--------------------------------------------------- % example % G = [0 3 9 10 10 10 10; % 0 1 10 7 1 10 10; % 0 2 10 7 10 10 10; % 0 0 0 0 0 2 8; % 0 0 4 5 0 9 0; % 0 0 0 0 0 0 4; % 0 0 0 0 0 0 0; % ]; %[e L] = dijkstra(G,1,7) %A = G; %s = 2; %d =3; function [e linecut] = dijkstra(A,s,d) if s==d e=0; L=[s]; else A = setupgraph(A,inf,1); end if d==1 d=s; end A=exchangenode(A,1,s); lengthA=size(A,1); W=zeros(lengthA); for i=2 : lengthA W(1,i)=i; W(2,i)=A(1,i); end for i=1 : lengthA D(i,1)=A(1,i); D(i,2)=i; end D2=D(2:length(D),:); L=2; while L<=(size(W,1)-1) L=L+1; D2=sortrows(D2,1); k=D2(1,2); W(L,1)=k; D2(1,:)=[]; for i=1 : size(D2,1) if D(D2(i,2),1)>(D(k,1)+A(k,D2(i,2))); D(D2(i,2),1) = D(k,1)+A(k,D2(i,2)); D2(i,1) = D(D2(i,2),1); end end for i=2 : length(A) W(L,i)=D(i,1); end end if d==s L=[1]; else L=[d]; end e = W(size(W,1),d); L = listdijkstra(L,W,s,d); linecut = []; for i = 1:length(L) linecut = [L(i), linecut]; end end % usage % [cost rute] = dijkstra(Graph, source, destination) %
github
xjsxujingsong/UberNet-master
classification_demo.m
.m
UberNet-master/caffe-fast-rcnn/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
xjsxujingsong/UberNet-master
voc_eval.m
.m
UberNet-master/lib/datasets/VOCdevkit-matlab-wrapper/voc_eval.m
1,332
utf_8
3ee1d5373b091ae4ab79d26ab657c962
function res = voc_eval(path, comp_id, test_set, output_dir) VOCopts = get_voc_opts(path); VOCopts.testset = test_set; for i = 1:length(VOCopts.classes) cls = VOCopts.classes{i}; res(i) = voc_eval_cls(cls, VOCopts, comp_id, output_dir); end fprintf('\n~~~~~~~~~~~~~~~~~~~~\n'); fprintf('Results:\n'); aps = [res(:).ap]'; fprintf('%.1f\n', aps * 100); fprintf('%.1f\n', mean(aps) * 100); fprintf('~~~~~~~~~~~~~~~~~~~~\n'); function res = voc_eval_cls(cls, VOCopts, comp_id, output_dir) test_set = VOCopts.testset; year = VOCopts.dataset(4:end); addpath(fullfile(VOCopts.datadir, 'VOCcode')); res_fn = sprintf(VOCopts.detrespath, comp_id, cls); recall = []; prec = []; ap = 0; ap_auc = 0; do_eval = (str2num(year) <= 2007) | ~strcmp(test_set, 'test'); if do_eval % Bug in VOCevaldet requires that tic has been called first tic; [recall, prec, ap] = VOCevaldet(VOCopts, comp_id, cls, true); ap_auc = xVOCap(recall, prec); % force plot limits ylim([0 1]); xlim([0 1]); print(gcf, '-djpeg', '-r0', ... [output_dir '/' cls '_pr.jpg']); end fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc); res.recall = recall; res.prec = prec; res.ap = ap; res.ap_auc = ap_auc; save([output_dir '/' cls '_pr.mat'], ... 'res', 'recall', 'prec', 'ap', 'ap_auc'); rmpath(fullfile(VOCopts.datadir, 'VOCcode'));
github
anmolnijhawan/Piecewise-linear-model-fitting-of-DCE-MRI-data-master
PLMmain.m
.m
Piecewise-linear-model-fitting-of-DCE-MRI-data-master/PLMmain.m
477
utf_8
fe7202a2b43457fa562c7ae46e20e671
%% function to be used in Perfusio Tool Main for PL model calculation function [ Ct ] = PLMmain( par_PL,time ) for t = 1: length(time) if (time(t)<=par_PL(1)) Ct(t) = par_PL(3); elseif (time(t)<=par_PL(2)) Ct(t) = par_PL(3) + par_PL(4)*(time(t)-par_PL(1)); else Ct(t) = par_PL(3) + par_PL(4)*(par_PL(2)-par_PL(1))+par_PL(5)*(time(t)-par_PL(2)); end end end
github
s0920832252/Number-Optimization-Class--master
hessian_f.m
.m
Number-Optimization-Class--master/Hw2/hessian_f.m
425
utf_8
6ab24e44ad54c197c6f3a1cb813af792
%function h = hessian_f(X) function hes = hessian_f( X ) % g is a function which can return gradient vector. %idea : (g(x+h ; y)-g(x;y))/h -> g() for( delat_x ) %and (g(x ; y+h)-g(x;y))/h -> g() for( delat_y ) h=0.0001; g=gradient_f(X)'; hes=[]; for i=1:length(X) newX=X; newX(i)=X(i)+h; new_g=gradient_f(newX)'; hes=[hes (new_g-g)/h]; end end
github
s0920832252/Number-Optimization-Class--master
別人的InteriorPointMethod.m
.m
Number-Optimization-Class--master/Hw4/別人的InteriorPointMethod.m
3,691
utf_8
7b22636821f0d713a1ce16cd20241b43
%{ GNU Octave version = 3.8.2 http://octave-online.net/ GNU Octave version = 4.0.0 Windows XP %} function [outputX, outputCase] = InteriorPointMethod(c, A, b, x0, lambda0, s0); %{ min c^T * x s.t. A*x >= b %} %{ min c^T * x s.t. A*x - s = b s >= 0 %} error = 1e-5; maxIteration = 1000; % Define: (0) solved, (1) unbounded, (2) infeasible. caseSolved = int8(0); caseUnbounded = int8(1); caseInfeasible = int8(2); caseMaxIteration = int8(3); % Check the number of dimensions. if( 2 ~= ndims(c) || 2 ~= ndims(A) || 2 ~= ndims(b) || 2 ~= ndims(x0) ) fprintf(2, 'Error: The number of dimensions in the input arguments must be TWO.\n'); outputX = x0; outputCase = caseInfeasible; return; end % Check the sizes of the input arguments. [m, n] = size(A); if( any( [n, 1] ~= size(c) ) || any( [m, 1] ~= size(b) ) || any( [n, 1] ~= size(x0) ) ) fprintf(2, 'Error: The sizes of the input arguments are wrong.\n'); outputX = x0; outputCase = caseInfeasible; return; end % Check x0 is satisfied all constraints. %{ if( ~ all(A*x0 >= b) ) fprintf(2, 'Error: x0 must be satisfied A*x0 >= b.\n'); outputX = x0; outputCase = caseInfeasible; return; end %} % Step (1) x_k = x0; lambda_k = lambda0; s_k = s0; for k = 1 : maxIteration % Step (3) sigma_k = 0.5; mu_k = dot(lambda_k, s_k)/m; temp_A = zeros( n + 2*m, n + 2*m); temp_A( 1:n, n+ 1 : n+ m) = -A'; temp_A( n+ 1 : n+ m, 1:n) = A; temp_A( n+ 1 : n+ m, n+m+ 1 : n+m+ m) = eye(m); temp_A( n+m + 1 : n+m + m, n + 1 : n + m ) = diag(s_k); temp_A( n+m+ 1 : n+m + m, n+m + 1 : n+m + m) = diag(lambda_k); temp_b = zeros( n+2*m, 1); temp_b(1:n,1) = A'*lambda_k - c; temp_b(n+1:n+m,1) = A*x_k - s_k - b; temp_b(n+m+1:n+m+m,1) = sigma_k * mu_k * ones(m,1) - lambda_k .* s_k; temp_x = mldivide(temp_A,temp_b); delta_x_k = temp_x(1:n,1); delta_lambda_k = temp_x(n+1:n+m,1); delta_s_k = temp_x(n+m+1:n+m+m,1); % Step (4) alpha = 1; gamma = 1e-3; for l = 1 : maxIteration x_kp1 = x_k + alpha * delta_x_k; lambda_kp1 = lambda_k + alpha * delta_lambda_k; s_kp1 = s_k + alpha * delta_s_k; mu_kp1 = dot(lambda_kp1, s_kp1)/m; if( all( lambda_kp1 .* s_kp1 >= gamma*mu_kp1) && A'*lambda_kp1 == c && A*x_kp1 == s_kp1 + b ) break; else alpha = alpha/2; end end if(norm(x_k-x_kp1) <= error) outputX = x_kp1; outputCase = caseSolved; return; end x_k = x_kp1; lambda_k = lambda_kp1; s_k = s_kp1; end outputX = x_kp1; outputCase = caseMaxIteration; return; end function text_IPM %{ min c^T * x s.t. A*x >= b %} c = [-8; -5]; A = [-2 -1; -3 -4; -1 -1; -1 1; 1 0; 0 1]; b = [-1000; -2400; -700; -350; 0; 0]; [m, n] = size(A); x0 = zeros(n, 1); s0 = [1000; 2400; 700; 350; 0; 0]; lambda0 = ones(6,1); [x, myCase] = InteriorPointMethod(c, A, b, x0, lambda0, s0); printf('x = [%.1f; %.1f];\ncase = %d\n', x(1), x(2), myCase); end
github
s0920832252/Number-Optimization-Class--master
main.m
.m
Number-Optimization-Class--master/Hw4/世承的作業/main.m
412
utf_8
4d7cd5aabe4a933a8f88d8a8252cd567
% EXAMPLE % max z=8*x1+5*x2 % s.t. 2*x1+x2<=1000 % 3*x1+4*x2<=2400 % x1+x2<=700 % x1-x2<=350 function main A=[-2,-1;-3,-4;-1,-2;-1,1;1,0;0,1]; b=[-1000;-2400;-700;-350;0;0]; c=[-8;-5]; lambda0=[1;1;1;1;1;1]; x0=[0;0]; s0=[1000;2400;700;350;0;0]; [Z X]=interior_point_method(A, b, c, x0, lambda0, s0); hold on; scatter(X(1,:),X(2,:)); plot(X(1,:),X(2,:),'-'); end
github
s0920832252/Number-Optimization-Class--master
draw_trace.m
.m
Number-Optimization-Class--master/Hw1/draw_trace.m
1,312
utf_8
3e4bf037967e1f3757b10abe04cc2f1f
function draw_trace() step = 0.1; X = 0:step:9; Y = -1:step:1; n = size(X,2); m = size(Y,2); Z = zeros(m,n); for j = 1:m for i = 1:n Z(j,i) = f(X(i),Y(j)); end end contour(X,Y,Z,50); hold on; % this is important!! This will overlap your plots. % plot the trace % You can record the trace of your results and use the following % code to plot the trace. %xk = [9 8 8 7 7 6 6 5 5 4 4 3 3 2 2]; %yk = [.5 .5 -.5 -.5 .5 .5 -.5 -.5 .5 .5 -.5 -.5 .5 .5 -.5]; Xs=[9;1]; g=[1;9]; H=[1,0;0,9]; pathS=step_descent(Xs); pathN=Newton(Xs); plot(pathN(1,:),pathN(2,:)); plot(pathS(1,:),pathS(2,:)); axis equal ; title('my homework');xlabel('x-label');ylabel('y-label'); h_leg =legend('contour','Newton','step_descent'); set(h_leg,'position',[0.2 0.2 0.2 0.1]); %plot(xk,yk,'-','LineWidth',3); hold off; % function definition function z = f(x,y) z = (x*x+9*y*y)/2; end function N = Newton(Xs) N = Xs; G=[1;1]; while( ~isequal(round(G,5),[0;0]) ) G=[g(1)*Xs(1);g(2)*Xs(2)]; Xs = Xs-(H\G); N = [N Xs]; end end function S = step_descent(Xs) S = Xs; G=[1;1]; while( ~isequal(round(G,5),[0;0]) ) G=[g(1)*Xs(1);g(2)*Xs(2)]; Xs = Xs-(((G)'*H*(G))^(-1)*((G)'*(G)))*(G); S = [S Xs]; end end end
github
shaform/facenet-master
detect_face_v1.m
.m
facenet-master/tmp/detect_face_v1.m
7,954
utf_8
678c2105b8d536f8bbe08d3363b69642
% MIT License % % Copyright (c) 2016 Kaipeng Zhang % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [total_boxes, points] = detect_face_v1(img,minsize,PNet,RNet,ONet,threshold,fastresize,factor) %im: input image %minsize: minimum of faces' size %pnet, rnet, onet: caffemodel %threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold %fastresize: resize img from last scale (using in high-resolution images) if fastresize==true factor_count=0; total_boxes=[]; points=[]; h=size(img,1); w=size(img,2); minl=min([w h]); img=single(img); if fastresize im_data=(single(img)-127.5)*0.0078125; end m=12/minsize; minl=minl*m; %creat scale pyramid scales=[]; while (minl>=12) scales=[scales m*factor^(factor_count)]; minl=minl*factor; factor_count=factor_count+1; end %first stage for j = 1:size(scales,2) scale=scales(j); hs=ceil(h*scale); ws=ceil(w*scale); if fastresize im_data=imResample(im_data,[hs ws],'bilinear'); else im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125; end PNet.blobs('data').reshape([hs ws 3 1]); out=PNet.forward({im_data}); boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1)); %inter-scale nms pick=nms(boxes,0.5,'Union'); boxes=boxes(pick,:); if ~isempty(boxes) total_boxes=[total_boxes;boxes]; end end numbox=size(total_boxes,1); if ~isempty(total_boxes) pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); regw=total_boxes(:,3)-total_boxes(:,1); regh=total_boxes(:,4)-total_boxes(:,2); total_boxes=[total_boxes(:,1)+total_boxes(:,6).*regw total_boxes(:,2)+total_boxes(:,7).*regh total_boxes(:,3)+total_boxes(:,8).*regw total_boxes(:,4)+total_boxes(:,9).*regh total_boxes(:,5)]; total_boxes=rerec(total_boxes); total_boxes(:,1:4)=fix(total_boxes(:,1:4)); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); end numbox=size(total_boxes,1); if numbox>0 %second stage tempimg=zeros(24,24,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0 tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear'); else total_boxes = []; return; end; end tempimg=(tempimg-127.5)*0.0078125; RNet.blobs('data').reshape([24 24 3 numbox]); out=RNet.forward({tempimg}); score=squeeze(out{2}(2,:)); pass=find(score>threshold(2)); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); if size(total_boxes,1)>0 pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); total_boxes=bbreg(total_boxes,mv(:,pick)'); total_boxes=rerec(total_boxes); end numbox=size(total_boxes,1); if numbox>0 %third stage total_boxes=fix(total_boxes); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); tempimg=zeros(48,48,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); if size(tmp,1)>0 && size(tmp,2)>0 || size(tmp,1)==0 && size(tmp,2)==0 tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear'); else total_boxes = []; return; end; end tempimg=(tempimg-127.5)*0.0078125; ONet.blobs('data').reshape([48 48 3 numbox]); out=ONet.forward({tempimg}); score=squeeze(out{3}(2,:)); points=out{2}; pass=find(score>threshold(3)); points=points(:,pass); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); w=total_boxes(:,3)-total_boxes(:,1)+1; h=total_boxes(:,4)-total_boxes(:,2)+1; points(1:5,:)=repmat(w',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1; points(6:10,:)=repmat(h',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1; if size(total_boxes,1)>0 total_boxes=bbreg(total_boxes,mv(:,:)'); pick=nms(total_boxes,0.7,'Min'); total_boxes=total_boxes(pick,:); points=points(:,pick); end end end end function [boundingbox] = bbreg(boundingbox,reg) %calibrate bouding boxes if size(reg,2)==1 reg=reshape(reg,[size(reg,3) size(reg,4)])'; end w=[boundingbox(:,3)-boundingbox(:,1)]+1; h=[boundingbox(:,4)-boundingbox(:,2)]+1; boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h]; end function [boundingbox reg] = generateBoundingBox(map,reg,scale,t) %use heatmap to generate bounding boxes stride=2; cellsize=12; boundingbox=[]; map=map'; dx1=reg(:,:,1)'; dy1=reg(:,:,2)'; dx2=reg(:,:,3)'; dy2=reg(:,:,4)'; [y x]=find(map>=t); a=find(map>=t); if size(y,1)==1 y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2'; else score=map(a); end reg=[dx1(a) dy1(a) dx2(a) dy2(a)]; if isempty(reg) reg=reshape([],[0 3]); end boundingbox=[y x]; boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg]; end function pick = nms(boxes,threshold,type) %NMS if isempty(boxes) pick = []; return; end x1 = boxes(:,1); y1 = boxes(:,2); x2 = boxes(:,3); y2 = boxes(:,4); s = boxes(:,5); area = (x2-x1+1) .* (y2-y1+1); [vals, I] = sort(s); pick = s*0; counter = 1; while ~isempty(I) last = length(I); i = I(last); pick(counter) = i; counter = counter + 1; xx1 = max(x1(i), x1(I(1:last-1))); yy1 = max(y1(i), y1(I(1:last-1))); xx2 = min(x2(i), x2(I(1:last-1))); yy2 = min(y2(i), y2(I(1:last-1))); w = max(0.0, xx2-xx1+1); h = max(0.0, yy2-yy1+1); inter = w.*h; if strcmp(type,'Min') o = inter ./ min(area(i),area(I(1:last-1))); else o = inter ./ (area(i) + area(I(1:last-1)) - inter); end I = I(find(o<=threshold)); end pick = pick(1:(counter-1)); end function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h) %compute the padding coordinates (pad the bounding boxes to square) tmpw=total_boxes(:,3)-total_boxes(:,1)+1; tmph=total_boxes(:,4)-total_boxes(:,2)+1; numbox=size(total_boxes,1); dx=ones(numbox,1);dy=ones(numbox,1); edx=tmpw;edy=tmph; x=total_boxes(:,1);y=total_boxes(:,2); ex=total_boxes(:,3);ey=total_boxes(:,4); tmp=find(ex>w); edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w; tmp=find(ey>h); edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h; tmp=find(x<1); dx(tmp)=2-x(tmp);x(tmp)=1; tmp=find(y<1); dy(tmp)=2-y(tmp);y(tmp)=1; end function [bboxA] = rerec(bboxA) %convert bboxA to square bboxB=bboxA(:,1:4); h=bboxA(:,4)-bboxA(:,2); w=bboxA(:,3)-bboxA(:,1); l=max([w h]')'; bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5; bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5; bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]); end
github
shaform/facenet-master
detect_face_v2.m
.m
facenet-master/tmp/detect_face_v2.m
9,016
utf_8
0c963a91d4e52c98604dd6ca7a99d837
% MIT License % % Copyright (c) 2016 Kaipeng Zhang % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [total_boxes, points] = detect_face_v2(img,minsize,PNet,RNet,ONet,LNet,threshold,fastresize,factor) %im: input image %minsize: minimum of faces' size %pnet, rnet, onet: caffemodel %threshold: threshold=[th1 th2 th3], th1-3 are three steps's threshold %fastresize: resize img from last scale (using in high-resolution images) if fastresize==true factor_count=0; total_boxes=[]; points=[]; h=size(img,1); w=size(img,2); minl=min([w h]); img=single(img); if fastresize im_data=(single(img)-127.5)*0.0078125; end m=12/minsize; minl=minl*m; %creat scale pyramid scales=[]; while (minl>=12) scales=[scales m*factor^(factor_count)]; minl=minl*factor; factor_count=factor_count+1; end %first stage for j = 1:size(scales,2) scale=scales(j); hs=ceil(h*scale); ws=ceil(w*scale); if fastresize im_data=imResample(im_data,[hs ws],'bilinear'); else im_data=(imResample(img,[hs ws],'bilinear')-127.5)*0.0078125; end PNet.blobs('data').reshape([hs ws 3 1]); out=PNet.forward({im_data}); boxes=generateBoundingBox(out{2}(:,:,2),out{1},scale,threshold(1)); %inter-scale nms pick=nms(boxes,0.5,'Union'); boxes=boxes(pick,:); if ~isempty(boxes) total_boxes=[total_boxes;boxes]; end end numbox=size(total_boxes,1); if ~isempty(total_boxes) pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); bbw=total_boxes(:,3)-total_boxes(:,1); bbh=total_boxes(:,4)-total_boxes(:,2); total_boxes=[total_boxes(:,1)+total_boxes(:,6).*bbw total_boxes(:,2)+total_boxes(:,7).*bbh total_boxes(:,3)+total_boxes(:,8).*bbw total_boxes(:,4)+total_boxes(:,9).*bbh total_boxes(:,5)]; total_boxes=rerec(total_boxes); total_boxes(:,1:4)=fix(total_boxes(:,1:4)); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); end numbox=size(total_boxes,1); if numbox>0 %second stage tempimg=zeros(24,24,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); tempimg(:,:,:,k)=imResample(tmp,[24 24],'bilinear'); end tempimg=(tempimg-127.5)*0.0078125; RNet.blobs('data').reshape([24 24 3 numbox]); out=RNet.forward({tempimg}); score=squeeze(out{2}(2,:)); pass=find(score>threshold(2)); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); if size(total_boxes,1)>0 pick=nms(total_boxes,0.7,'Union'); total_boxes=total_boxes(pick,:); total_boxes=bbreg(total_boxes,mv(:,pick)'); total_boxes=rerec(total_boxes); end numbox=size(total_boxes,1); if numbox>0 %third stage total_boxes=fix(total_boxes); [dy edy dx edx y ey x ex tmpw tmph]=pad(total_boxes,w,h); tempimg=zeros(48,48,3,numbox); for k=1:numbox tmp=zeros(tmph(k),tmpw(k),3); tmp(dy(k):edy(k),dx(k):edx(k),:)=img(y(k):ey(k),x(k):ex(k),:); tempimg(:,:,:,k)=imResample(tmp,[48 48],'bilinear'); end tempimg=(tempimg-127.5)*0.0078125; ONet.blobs('data').reshape([48 48 3 numbox]); out=ONet.forward({tempimg}); score=squeeze(out{3}(2,:)); points=out{2}; pass=find(score>threshold(3)); points=points(:,pass); total_boxes=[total_boxes(pass,1:4) score(pass)']; mv=out{1}(:,pass); bbw=total_boxes(:,3)-total_boxes(:,1)+1; bbh=total_boxes(:,4)-total_boxes(:,2)+1; points(1:5,:)=repmat(bbw',[5 1]).*points(1:5,:)+repmat(total_boxes(:,1)',[5 1])-1; points(6:10,:)=repmat(bbh',[5 1]).*points(6:10,:)+repmat(total_boxes(:,2)',[5 1])-1; if size(total_boxes,1)>0 total_boxes=bbreg(total_boxes,mv(:,:)'); pick=nms(total_boxes,0.7,'Min'); total_boxes=total_boxes(pick,:); points=points(:,pick); end end numbox=size(total_boxes,1); %extended stage if numbox>0 tempimg=zeros(24,24,15,numbox); patchw=max([total_boxes(:,3)-total_boxes(:,1)+1 total_boxes(:,4)-total_boxes(:,2)+1]'); patchw=fix(0.25*patchw); tmp=find(mod(patchw,2)==1); patchw(tmp)=patchw(tmp)+1; pointx=ones(numbox,5); pointy=ones(numbox,5); for k=1:5 tmp=[points(k,:);points(k+5,:)]; x=fix(tmp(1,:)-0.5*patchw); y=fix(tmp(2,:)-0.5*patchw); [dy edy dx edx y ey x ex tmpw tmph]=pad([x' y' x'+patchw' y'+patchw'],w,h); for j=1:numbox tmpim=zeros(tmpw(j),tmpw(j),3); tmpim(dy(j):edy(j),dx(j):edx(j),:)=img(y(j):ey(j),x(j):ex(j),:); tempimg(:,:,(k-1)*3+1:(k-1)*3+3,j)=imResample(tmpim,[24 24],'bilinear'); end end LNet.blobs('data').reshape([24 24 15 numbox]); tempimg=(tempimg-127.5)*0.0078125; out=LNet.forward({tempimg}); score=squeeze(out{3}(2,:)); for k=1:5 tmp=[points(k,:);points(k+5,:)]; %do not make a large movement temp=find(abs(out{k}(1,:)-0.5)>0.35); if ~isempty(temp) l=length(temp); out{k}(:,temp)=ones(2,l)*0.5; end temp=find(abs(out{k}(2,:)-0.5)>0.35); if ~isempty(temp) l=length(temp); out{k}(:,temp)=ones(2,l)*0.5; end pointx(:,k)=(tmp(1,:)-0.5*patchw+out{k}(1,:).*patchw)'; pointy(:,k)=(tmp(2,:)-0.5*patchw+out{k}(2,:).*patchw)'; end for j=1:numbox points(:,j)=[pointx(j,:)';pointy(j,:)']; end end end end function [boundingbox] = bbreg(boundingbox,reg) %calibrate bouding boxes if size(reg,2)==1 reg=reshape(reg,[size(reg,3) size(reg,4)])'; end w=[boundingbox(:,3)-boundingbox(:,1)]+1; h=[boundingbox(:,4)-boundingbox(:,2)]+1; boundingbox(:,1:4)=[boundingbox(:,1)+reg(:,1).*w boundingbox(:,2)+reg(:,2).*h boundingbox(:,3)+reg(:,3).*w boundingbox(:,4)+reg(:,4).*h]; end function [boundingbox reg] = generateBoundingBox(map,reg,scale,t) %use heatmap to generate bounding boxes stride=2; cellsize=12; boundingbox=[]; map=map'; dx1=reg(:,:,1)'; dy1=reg(:,:,2)'; dx2=reg(:,:,3)'; dy2=reg(:,:,4)'; [y x]=find(map>=t); a=find(map>=t); if size(y,1)==1 y=y';x=x';score=map(a)';dx1=dx1';dy1=dy1';dx2=dx2';dy2=dy2'; else score=map(a); end reg=[dx1(a) dy1(a) dx2(a) dy2(a)]; if isempty(reg) reg=reshape([],[0 3]); end boundingbox=[y x]; boundingbox=[fix((stride*(boundingbox-1)+1)/scale) fix((stride*(boundingbox-1)+cellsize-1+1)/scale) score reg]; end function pick = nms(boxes,threshold,type) %NMS if isempty(boxes) pick = []; return; end x1 = boxes(:,1); y1 = boxes(:,2); x2 = boxes(:,3); y2 = boxes(:,4); s = boxes(:,5); area = (x2-x1+1) .* (y2-y1+1); [vals, I] = sort(s); pick = s*0; counter = 1; while ~isempty(I) last = length(I); i = I(last); pick(counter) = i; counter = counter + 1; xx1 = max(x1(i), x1(I(1:last-1))); yy1 = max(y1(i), y1(I(1:last-1))); xx2 = min(x2(i), x2(I(1:last-1))); yy2 = min(y2(i), y2(I(1:last-1))); w = max(0.0, xx2-xx1+1); h = max(0.0, yy2-yy1+1); inter = w.*h; if strcmp(type,'Min') o = inter ./ min(area(i),area(I(1:last-1))); else o = inter ./ (area(i) + area(I(1:last-1)) - inter); end I = I(find(o<=threshold)); end pick = pick(1:(counter-1)); end function [dy edy dx edx y ey x ex tmpw tmph] = pad(total_boxes,w,h) %compute the padding coordinates (pad the bounding boxes to square) tmpw=total_boxes(:,3)-total_boxes(:,1)+1; tmph=total_boxes(:,4)-total_boxes(:,2)+1; numbox=size(total_boxes,1); dx=ones(numbox,1);dy=ones(numbox,1); edx=tmpw;edy=tmph; x=total_boxes(:,1);y=total_boxes(:,2); ex=total_boxes(:,3);ey=total_boxes(:,4); tmp=find(ex>w); edx(tmp)=-ex(tmp)+w+tmpw(tmp);ex(tmp)=w; tmp=find(ey>h); edy(tmp)=-ey(tmp)+h+tmph(tmp);ey(tmp)=h; tmp=find(x<1); dx(tmp)=2-x(tmp);x(tmp)=1; tmp=find(y<1); dy(tmp)=2-y(tmp);y(tmp)=1; end function [bboxA] = rerec(bboxA) %convert bboxA to square bboxB=bboxA(:,1:4); h=bboxA(:,4)-bboxA(:,2); w=bboxA(:,3)-bboxA(:,1); l=max([w h]')'; bboxA(:,1)=bboxA(:,1)+w.*0.5-l.*0.5; bboxA(:,2)=bboxA(:,2)+h.*0.5-l.*0.5; bboxA(:,3:4)=bboxA(:,1:2)+repmat(l,[1 2]); end
github
kevinliu001/Android-SpeexDenoise-master
echo_diagnostic.m
.m
Android-SpeexDenoise-master/app/src/main/jni/libspeexdsp/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
Minyu-Shen/Simulation-for-bus-stops-near-signalized-intersection-master
Simulation_far_side.m
.m
Simulation-for-bus-stops-near-signalized-intersection-master/Simulation_far_side.m
23,064
utf_8
4b73d726815eec5a3e86be60926b91a6
clear;clc; % rng(2); global serving_rate; global cs_number; global berth_number; global buffer_number; global jam_spacing; global free_speed; global back_speed; global moveup_speed; global cycle_length_number; global green_ratio; global sim_size; global il; % cs_number = [0.15,0.3,0.45,0.6,0.75]; global cs; cs = 0.6; pl = 1; % plot handler if cs==1 sim_size = 300; else if pl sim_size = 20; else sim_size = 50000; end end berth_number = 2; buffer_number = 3:1:3; if pl cycle_length_number = 140:1:140; else cycle_length_number = 80:1:240; end green_ratio = 0.7; jam_spacing = 12; free_speed = 20 / 3.6; back_speed = 25 / 3.6; moveup_speed = 20 / 3.6; serving_rate = 1/25; il = 3; mh = jam_spacing / moveup_speed; bh = jam_spacing / back_speed; ih = il*jam_spacing/moveup_speed; % mh=0; % bh=0; % fh=0; %% simulation procedures cs_size = sum(cs_number~=-1); c_size = sum(berth_number~=-1); d_size = sum(buffer_number~=-1); cl_size = sum(cycle_length_number~=-1); for l=1:cl_size cycle_length = cycle_length_number(l); green_time = cycle_length * green_ratio; if cs==0 serv_time(1 : sim_size) = unifrnd(1/serving_rate, 1/serving_rate); else serv_time(1 : sim_size) = gamrnd(1/cs^2, cs^2/serving_rate, 1, sim_size); end for k=1:c_size c = berth_number(k); for j=1:d_size u = zeros(sim_size, 1); d = buffer_number(j); d0 = mod(d,c); n = floor(d/c); dq_m = zeros(sim_size, 1); bff_pos = zeros(sim_size, 1); bth_pos = zeros(sim_size, 1); bff_times = zeros(sim_size, 1); arr_bff_m = zeros(sim_size, n+1); lv_bff_m = zeros(sim_size, n+1); end_serv_m = zeros(sim_size, 1); wait_bth = zeros(sim_size, 1); lv_bth_m = zeros(sim_size, 1); for i=1:sim_size if i == 1 % starting from green period dq_m(i) = 0; bff_pos(i) = 0; bth_pos(i) = 1; bff_times(i) = 0; end_serv_m(i) = dq_m(i) + (c+d)*mh + ih + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); else % i > 1 starts %% buffer_pos(i-1) == 0 starts if bff_pos(i-1) == 0 temp_dq_m = dq_m(i-1) + mh +bh; if bth_pos(i-1) == c if d==0 bth_pos(i) = 1; bff_pos(i) = 0; bff_times(i) = 0; if mod(lv_bth_m(i-1) + bh, cycle_length) <= green_time dq_m(i) = lv_bth_m(i-1) + bh; else dq_m(i) = cycle_length - mod(lv_bth_m(i-1), cycle_length) + lv_bth_m(i-1) + bh; end end_serv_m(i) = dq_m(i) + (c+d)*mh + ih + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); else % last berth is c and d~=0 if mod(temp_dq_m, cycle_length) <= green_time dq_m(i) = temp_dq_m; bff_pos(i) = 1; bth_pos(i) = det_bth(1, c); bff_times(i) = 1; lv_bff_m(i, 1) = lv_bth_m(i-1)+bh; end_serv_m(i) = lv_bff_m(i, 1) + c*mh + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); else % meet the red period, wait until the greee period nxt_g = cycle_length - mod(dq_m(i-1), cycle_length) + dq_m(i-1) + bh; if nxt_g < lv_bth_m(i-1) + bh dq_m(i) = lv_bth_m(i-1) + bh; bff_pos(i) = 1; bth_pos(i) = det_bth(1, c); bff_times(i) = 1; lv_bff_m(i, 1) = lv_bth_m(i-1)+bh; end_serv_m(i) = lv_bff_m(i, 1) + c*mh + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); else dq_m(i) = nxt_g; bff_pos(i) = 0; bth_pos(i) = 1; bff_times(i) = 0; end_serv_m(i) = dq_m(i) + (c+d)*mh + ih + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); end end end else % last bus's berth < c bff_pos(i) = 0; bff_times(i) = 0; if mod(temp_dq_m, cycle_length) <= green_time dq_m(i) = temp_dq_m; bth_pos(i) = bth_pos(i-1) + 1; end_serv_m(i) = dq_m(i) + (c+d-bth_pos(i)+1)*mh + ih + serv_time(i); wait_bth(i) = max(0, lv_bth_m(i-1) + bh - end_serv_m(i)); lv_bth_m(i) = end_serv_m(i) + wait_bth(i); else nxt_g = cycle_length - mod(temp_dq_m, cycle_length) + temp_dq_m + bh; dq_m(i) = nxt_g; if nxt_g < lv_bth_m(i-1) + bh dq_m(i) = lv_bth_m(i-1) + bh; bth_pos(i) = bth_pos(i-1)+1; end_serv_m(i) = dq_m(i) + (d+c-bth_pos(i)+1+il)*mh + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); else dq_m(i) = nxt_g; bth_pos(i) = 1; bff_times(i) = 0; end_serv_m(i) = dq_m(i) + (c+d)*mh + ih + serv_time(i); wait_bth(i) = 0; lv_bth_m(i) = end_serv_m(i); end end end %% buffer_pos(i-1) == 0 ends elseif bff_pos(i-1) < d %% 0< buffer_pos(i-1) < d temp_dq_m = dq_m(i-1) + mh + bh; % determine berth and buffer if mod(temp_dq_m, cycle_length) <= green_time dq_m(i) = temp_dq_m; bff_pos(i) = bff_pos(i-1) + 1; bth_pos(i) = det_bth(bff_pos(i), c); else dq_m(i) = dq_m(i-1) + cycle_length - mod(dq_m(i-1), cycle_length) + bh; flag = 0; for p=1:1:bff_times(i-1) evr_bff_pos = bff_pos(i-1) - (p-1)*c; tp = dq_m(i) + (d-evr_bff_pos+1)*mh + ih; if tp < lv_bff_m(i-1, p) + bh bff_pos(i) = evr_bff_pos + 1; bth_pos(i) = det_bth(bff_pos(i), c); flag = 1; break; end end if flag == 0 % judge berth point tp = dq_m(i) + ih + (d+c-bth_pos(i-1))*mh; if tp < lv_bth_m(i-1) + bh if bth_pos(i-1) == c bff_pos(i) = 1; bth_pos(i) = 1; else bff_pos(i) = 0; bth_pos(i) = bth_pos(i-1) + 1; end else bff_pos(i) = 0; bth_pos(i) = 1; end end end % determine lv_bff_m bff_times(i) = ceil(bff_pos(i)/c); if bff_times(i) == 0 % lv_bff is not important !!! end_serv_m(i) = dq_m(i) + (c+d-bth_pos(i)+1+il)*mh + serv_time(i); wait_bth(i) = max(0, lv_bth_m(i-1) + bh - end_serv_m(i)); lv_bth_m(i) = end_serv_m(i) + wait_bth(i); else % wait at buffer before service if bff_times(i) == bff_times(i-1) % same convoy if (mod(bff_pos(i), c) == 1 && c~=1) || (mod(bff_pos(i), c) == 0 && c==1) % the first bus for p=1:1:bff_times(i)-1 lv_bff_m(i, p) = lv_bff_m(i-1, p+1) + bh; end lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; else for p=1:1:bff_times(i) lv_bff_m(i, p) = lv_bff_m(i-1, p) + bh; end end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); elseif bff_times(i) > bff_times(i-1) for p=1:1:bff_times(i-1) lv_bff_m(i, p) = lv_bff_m(i-1, p)+bh; end lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); else % bff_times(i) < bff_times(i-1) if (mod(bff_pos(i), c) == 1 && c~=1) || (mod(bff_pos(i), c) == 0 && c==1) lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; for p=bff_times(i)-1:-1:1 lv_bff_m(i, p) = lv_bff_m(i-1, bff_times(i-1)-bff_times(i)+p) + bh; end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); else for p=bff_times(i):-1:1 lv_bff_m(i, p) = lv_bff_m(i-1, bff_times(i-1)-bff_times(i)+p) + bh; end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); end end wait_bth(i) = max(0, lv_bth_m(i-1) + bh - end_serv_m(i)); lv_bth_m(i) = end_serv_m(i) + wait_bth(i); end %% 0 < buffer_pos(i-1) < d ends else %% buffer_pos(i-1) == d starts temp_dq_m = lv_bff_m(i-1, 1) + bh; % determine berth and buffer if mod(temp_dq_m, cycle_length) <= green_time dq_m(i) = temp_dq_m; flag=0; for p=1:1:bff_times(i-1) evr_bff_pos = d - (p-1)*c; tp = dq_m(i) + (d-evr_bff_pos+1)*mh + ih; if tp < lv_bff_m(i-1, p) + bh if p==1 bff_pos(i) = d-c+1; else bff_pos(i) = evr_bff_pos + 1; end bth_pos(i) = det_bth(bff_pos(i), c); flag = 1; break; end end if flag == 0 % judge berth point tp = dq_m(i) + ih + (d+c-bth_pos(i-1))*mh; if tp < lv_bth_m(i-1) + bh if bth_pos(i-1) == c bff_pos(i) = 1; bth_pos(i) = 1; else bff_pos(i) = 0; bth_pos(i) = bth_pos(i-1) + 1; end else bff_pos(i) = 0; bth_pos(i) = 1; end end % bff_pos(i) = d-c+1; % bth_pos(i) = det_bth(bff_pos(i), c); else dq_m(i) = temp_dq_m + cycle_length - mod(temp_dq_m, cycle_length) + bh; flag = 0; for p=1:1:bff_times(i-1) evr_bff_pos = d - (p-1)*c; tp = dq_m(i) + (d-evr_bff_pos+1)*mh + ih; if tp < lv_bff_m(i-1, p) + bh if p==1 bff_pos(i) = d-c+1; else bff_pos(i) = evr_bff_pos + 1; end bth_pos(i) = det_bth(bff_pos(i), c); flag = 1; break; end end if flag == 0 % judge berth point tp = dq_m(i) + ih + (d+c-bth_pos(i-1))*mh; if tp < lv_bth_m(i-1) + bh if bth_pos(i-1) == c bff_pos(i) = 1; bth_pos(i) = 1; else bff_pos(i) = 0; bth_pos(i) = bth_pos(i-1) + 1; end else bff_pos(i) = 0; bth_pos(i) = 1; end end end % determine lv_bff_m bff_times(i) = ceil(bff_pos(i)/c); if bff_times(i) == 0 % lv_bff is not important !!! end_serv_m(i) = dq_m(i) + (c+d-bth_pos(i)+1+il)*mh + serv_time(i); wait_bth(i) = max(0, lv_bth_m(i-1) + bh - end_serv_m(i)); lv_bth_m(i) = end_serv_m(i) + wait_bth(i); else % wait at buffer before service if bff_times(i) == bff_times(i-1) % same convoy if (mod(bff_pos(i), c) == 1 && c~=1) || (c==1) % the first bus for p=1:1:bff_times(i)-1 lv_bff_m(i, p) = lv_bff_m(i-1, p+1); end lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; else for p=1:1:bff_times(i) lv_bff_m(i, p) = lv_bff_m(i-1, p) + bh; end end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); elseif bff_times(i) > bff_times(i-1) for p=1:1:bff_times(i-1) lv_bff_m(i, p) = lv_bff_m(i-1, p)+bh; end lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); else % bff_times(i) < bff_times(i-1) if (mod(bff_pos(i), c) == 1 && c~=1) || (c==1) lv_bff_m(i, bff_times(i)) = lv_bth_m(i-1) + bh; for p=bff_times(i)-1:-1:1 lv_bff_m(i, p) = lv_bff_m(i-1, bff_times(i-1)-bff_times(i)+p+1) + bh; end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); else for p=bff_times(i):-1:1 lv_bff_m(i, p) = lv_bff_m(i-1, bff_times(i-1)-bff_times(i)+p) + bh; end end_serv_m(i) = lv_bff_m(i, bff_times(i)) + c*mh + serv_time(i); end end wait_bth(i) = max(0, lv_bth_m(i-1) + bh - end_serv_m(i)); lv_bth_m(i) = end_serv_m(i) + wait_bth(i); end end %% buffer_pos(i-1) == d ends end end end_time = lv_bth_m(sim_size); capacity(l,j) = 3600 * sim_size / end_time; end end end if ~pl plot(cycle_length_number,capacity,'linewidth',2,'linestyle','-','color',[111/255, 122/255, 117/255]); hold on; end if pl plot_number = sim_size; % plot stop line t = [0, lv_bth_m(plot_number)]; y = [0, 0]; plot(t, y, '-', 'Color', 'k', 'LineWidth', 3); hold on; %plot signal for i=1:ceil(lv_bth_m(plot_number)/cycle_length) signal_y = [il*jam_spacing, il*jam_spacing]; signal_red_x = [(i-1)*cycle_length,(i-1)*cycle_length+green_time]; signal_green_x = [(i-1)*cycle_length+green_time,i*cycle_length]; line(signal_red_x,signal_y,'Color','g','LineWidth',4,'LineStyle','-'); line(signal_green_x,signal_y,'Color','r','LineWidth',4,'LineStyle','-'); end for i=1:c+d %plot berth and buffer x = [0,lv_bth_m(plot_number)]; y = [(il+i)*jam_spacing, (il+i)*jam_spacing]; plot(x,y,'--'); hold on; end for i=1:plot_number %1 dq_x = []; dq_y=[]; if bff_pos(i)==0 dq_x = [dq_m(i), dq_m(i)+(d+c-bth_pos(i)+1+il)*mh]; dq_y = [0,(d+c-bth_pos(i)+1+il)*jam_spacing]; else dq_x = [dq_m(i), dq_m(i)+(d-bff_pos(i)+1+il)*mh]; dq_y = [0, (d-bff_pos(i)+1+il)*jam_spacing]; end line(dq_x, dq_y, 'linewidth',2); % 2 plot waiting at buffer for p=1:1:bff_times(i) temp_bff_pos = bff_pos(i) - (p-1)*c; if p==1 bff_x = [dq_x(2), lv_bff_m(i, p)]; bff_y = [dq_y(2), (d-temp_bff_pos+1+il)*jam_spacing]; line(bff_x,bff_y,'linewidth',3); else bff_x = [lv_bff_m(i, p-1)+c*mh, lv_bff_m(i, p)]; bff_y = [(d-temp_bff_pos+1+il)*jam_spacing, (d-temp_bff_pos+1+il)*jam_spacing]; line(bff_x, bff_y,'linewidth',3); end end % 3 plot moving behavior in the buffers for p=2:1:bff_times(i) mv_bff_x = [lv_bff_m(i, p-1), lv_bff_m(i, p-1)+c*mh]; mv_bff_y = [(d-(bff_pos(i) - (p-2)*c)+1+il)*jam_spacing, (d-(bff_pos(i) - (p-1)*c)+1+il)*jam_spacing]; line(mv_bff_x, mv_bff_y, 'linewidth', 1.5); end % 4 plot moving behavior to berths if bff_times(i) ~= 0 mv_bth_x = [lv_bff_m(i, bff_times(i)), lv_bff_m(i, bff_times(i))+c*mh]; mv_bth_y = [(d-(bff_pos(i) - (bff_times(i)-1)*c)+1+il)*jam_spacing, (d+c-bth_pos(i)+1+il)*jam_spacing]; line(mv_bth_x, mv_bth_y, 'linewidth', 1.5); end % 5 plot service time if bff_times(i)==0 arr_bth_t = dq_m(i)+(d+c-bth_pos(i)+1+il)*mh; else arr_bth_t = lv_bff_m(i, bff_times(i))+c*mh; end serv_x = [arr_bth_t, arr_bth_t+serv_time(i)]; serv_y = [(d+c-bth_pos(i)+1+il)*jam_spacing, (d+c-bth_pos(i)+1+il)*jam_spacing]; line(serv_x, serv_y, 'linewidth', 3, 'color', 'k'); % 6 plot waiting in berth and departing fake=5; if wait_bth(i) == 0 dpt_x = [arr_bth_t+serv_time(i), arr_bth_t+serv_time(i)+fake]; dpt_y = [(d+c-bth_pos(i)+1+il)*jam_spacing, (d+c-bth_pos(i)+1+il)*jam_spacing+fake*5]; line(dpt_x, dpt_y, 'linewidth', 2.5); else wb_x = [arr_bth_t+serv_time(i), arr_bth_t+serv_time(i)+wait_bth(i)]; wb_y = [(d+c-bth_pos(i)+1+il)*jam_spacing, (d+c-bth_pos(i)+1+il)*jam_spacing]; line(wb_x, wb_y, 'linewidth', 1.5); dpt_x = [arr_bth_t+serv_time(i)+wait_bth(i), arr_bth_t+serv_time(i)+wait_bth(i)+fake]; dpt_y = [(d+c-bth_pos(i)+1+il)*jam_spacing, (d+c-bth_pos(i)+1+il)*jam_spacing+fake*5]; line(dpt_x, dpt_y, 'linewidth', 2.5); end end end function result = det_bth(bff_pos, c) if mod(bff_pos, c) == 0 result = c; else result = mod(bff_pos, c); end end
github
erwinwu211/TS-LSTM-based-HAR-master
create_flow_images_LRCN.m
.m
TS-LSTM-based-HAR-master/Action_Recognition/create_flow_images_LRCN.m
1,867
utf_8
2c6c52d02e2a85fc153ac4e7d2711107
function create_flow_images_LRCN(base, save_base) %create_flow_images will compute flow images from RGB images using [1]. %input: % base: folder in which RGB frames from videos are stored % save_base: folder in which flow images should be saved % %[1] Brox, Thomas, et al. "High accuracy optical flow estimation based on a theory for warping." Computer Vision-ECCV 2004. Springer Berlin Heidelberg, 2004. 25-36. base='frames'; save_base='flow' list = clean_dir(base); if ~isdir(save_base) mkdir(save_base) end for i = 1:length(list) if mod(i,100) == 0 fprintf('On item %d of %d\n', i, length(list)) end video = list{i}; frames = clean_dir(sprintf('%s/%s',base,video)); if length(frames) >= 1 if ~isdir(sprintf('%s/%s',save_base, video)) mkdir(sprintf('%s/%s',save_base, video)) end im1 = imread(sprintf('%s/%s/%s',base,video,frames{1})); for k = 2:length(frames) im2 = imread(sprintf('%s/%s/%s',base,video,frames{k})); flow = mex_OF(double(im1),double(im2)); scale = 16; mag = sqrt(flow(:,:,1).^2+flow(:,:,2).^2)*scale+128; mag = min(mag, 255); flow = flow*scale+128; flow = min(flow,255); flow = max(flow,0); [x,y,z] = size(flow); flow_image = zeros(x,y,3); flow_image(:,:,1:2) = flow; flow_image(:,:,3) = mag; imwrite(flow_image./255,sprintf('%s/%s/flow_image_%s',save_base,video,frames{k})) im1 = im2; end end end function files = clean_dir(base) %clean_dir just runs dir and eliminates files in a foldr files = dir(base); files_tmp = {}; for i = 1:length(files) if strncmpi(files(i).name, '.',1) == 0 files_tmp{length(files_tmp)+1} = files(i).name; end end files = files_tmp;
github
jlperla/continuous_time_methods-master
ValueMatch.m
.m
continuous_time_methods-master/matlab/tests/ValueMatch.m
1,127
utf_8
8638ee3b217786493d64e98e26b97168
% this is a function take input of Delta_p and Delta_m,v and create % v1-omega*v function residual = ValueMatch(v,z,Delta_p,Delta_m,h_p,h_m) I = length(Delta_p); N = length(v)/I; % v is N*I alpha = 2.1; F_p = @(z) alpha*exp(-alpha*z); eta = 1; %Trapezoidal weights, adjusted for non-uniform trapezoidal weighting omega_bar = (Delta_p + Delta_m)/2; %(52) though the corners are wrong omega_bar(1) = Delta_p(1)/2; %(51) omega_bar(end) = Delta_m(end)/2; %(51) omega = omega_bar .* F_p(z); %(19) Adjusted for the PDF to make (20) easy. %Stacking for the Omega %This is the eta = 0 case %omega_tilde = ([1;zeros(I-1,1)] - omega)'; %Omega = kron(speye(N),omega_tilde); %omega_tsilde as block diagonal %Alternative Omega with the alpha weighting Omega = sparse(N, N*I); %prealloate for n=1:N-1 Omega(n, (n-1)*I+1:(n+1)*I) = [([1;zeros(I-1,1)] - (1-eta) * omega)' -eta * omega']; end Omega(N, end - I + 1:end) = ([1;zeros(I-1,1)] - omega)'; %Adds in corner without the eta weighting. residual = Omega * v; return
github
jlperla/continuous_time_methods-master
Julia_comparison_stationary_test.m
.m
continuous_time_methods-master/matlab/tests/Julia_comparison_stationary_test.m
6,411
utf_8
3428cc8accd57af623a963ac72d17209
% This is test function that try to replicate Julia problem with same set % up %Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = Julia_comparison_stationary_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.lower_test_tol = 1e-8; %For huge matrices, the inf norm can get a little different. testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function uniform_more_grid_test(testCase) tolerances = testCase.TestData.tolerances; r = 0.05; zeta = 14.5; gamma = 0.005; g = 0.020758; mu_x = @(x) gamma-g; sigma_bar = 0.02; sigma_2_x = @(x) (sigma_bar).^2+0.0*x; u_x = @(x) exp(0.5*x); rho = r-g; x_min = 0.0; x_max = 5.0; I = 500; x = linspace(x_min,x_max,I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); %dlmwrite(strcat(mfilename, '_1_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %v_check = dlmread(strcat(mfilename, '_1_v_output.csv')); %verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); %verifyTrue(testCase, success==true, 'unsuccesful'); %Solve with a uniform grid and check if similar after interpolation x_2 = linspace(x_min, x_max, 701)'; %Twice as many points to be sure. A_2 = discretize_univariate_diffusion(x_2, mu_x(x_2), sigma_2_x(x_2)); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_2, success] = simple_HJBE_discretized_univariate(A_2, x_2, u_x(x_2), rho); figure() v_2int=interp1(x_2, v_2, x); dif=v-v_2int; plot(x,dif,'LineWidth',2);hold on title('difference of v and v_2 along z_grid, z_bar=5') %Make sure within range. This seems too large. verifyTrue(testCase, norm(interp1(x_2, v_2, x) - v,Inf) < 0.02, 'Not within range of interpolation'); end function uniform_more_grid_test2(testCase) tolerances = testCase.TestData.tolerances; r = 0.05; zeta = 14.5; gamma = 0.005; g = 0.020758; mu_x = @(x) gamma-g; sigma_bar = 0.02; sigma_2_x = @(x) (sigma_bar).^2+0.0*x; u_x = @(x) exp(x); rho = r-g; x_min = 0.0; x_max = 2.0; % lower xbar I = 301; x = linspace(x_min,x_max,I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); %dlmwrite(strcat(mfilename, '_1_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %v_check = dlmread(strcat(mfilename, '_1_v_output.csv')); %verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); %verifyTrue(testCase, success==true, 'unsuccesful'); %Solve with a uniform grid and check if similar after interpolation x_2 = linspace(x_min, x_max, 701)'; %Twice as many points to be sure. A_2 = discretize_univariate_diffusion(x_2, mu_x(x_2), sigma_2_x(x_2)); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_2, success] = simple_HJBE_discretized_univariate(A_2, x_2, u_x(x_2), rho); figure() v_2int=interp1(x_2, v_2, x); dif=v-v_2int; plot(x,dif,'LineWidth',2);hold on title('difference of v and v_2 along z_grid,z_bar=2') %Make sure within range. This seems too large. verifyTrue(testCase, norm(interp1(x_2, v_2, x) - v,Inf) < 0.02, 'Not within range of interpolation'); end function uniform_plot_test(testCase) tolerances = testCase.TestData.tolerances; r = 0.05; zeta = 14.5; gamma = 0.005; g = 0.020758; mu_x = @(x) gamma-g; sigma_bar = 0.02; sigma_2_x = @(x) (sigma_bar).^2+0.0*x; u_x = @(x) exp(x); rho = r-g; x_min = 0.0; x_max = 5.0; % lower xbar %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. I_c=[101 201 301 401 501]; for i=1:5 I = I_c(i); x = linspace(x_min,x_max,I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); [v_{i}, success] = simple_HJBE_discretized_univariate(A, x, u, rho); x_{i}=x; end figure() for i=1:5 plot(x_{i}(end-5:end),v_{i}(end-5:end)); hold on end legend('101','201','301','401','500') title('value function at last 5 grid point') end function uniform_to_nonuniform_test(testCase) tolerances = testCase.TestData.tolerances; r = 0.05; zeta = 14.5; gamma = 0.005; g = 0.020758; mu_x = @(x) gamma-g; sigma_bar = 0.02; sigma_2_x = @(x) (sigma_bar).^2+0.0*x; u_x = @(x) exp(x); rho = r-g; x_min = 0.0; x_max = 2.0; % lower xbar %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. I = 301; x = linspace(x_min,x_max,I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); I2=floor(I*1/3); % propotional adding grid points x_2 = unique([linspace(x_min, x_max, I)'; linspace(1.7,x_max,I2)']); %Twice as many points to be sure. A_2 = discretize_univariate_diffusion(x_2, mu_x(x_2), sigma_2_x(x_2)); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_2, success] = simple_HJBE_discretized_univariate(A_2, x_2, u_x(x_2), rho); v_2int=interp1(x_2, v_2, x); %Make sure within range. This seems too large. verifyTrue(testCase, norm(interp1(x_2, v_2, x) - v,Inf) < 0.02, 'Not within range of interpolation'); end
github
jlperla/continuous_time_methods-master
discretize_univariate_diffusion_test.m
.m
continuous_time_methods-master/matlab/tests/discretize_univariate_diffusion_test.m
14,330
utf_8
6053e25e9b61e0b069dea7d221595fe8
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = discretize_univariate_diffusion_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function zero_drift_uniform_grid_test(testCase)%Simple and small with zero drift with uniform grid tolerances = testCase.TestData.tolerances; mu_x = @(x) zeros(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %%dlmwrite(strcat(mfilename, '_1_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_1_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end function large_zero_drift_uniform_grid_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) zeros(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1000000; %million X million matrix, but sparse. x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %The following are worth testing for almost every matrix in the test suite. verifyTrue(testCase, (nnz(A) == 2999998), 'Number of non-zero values is wrong'); %Should have about 3million non-zeros. Tridiagonal. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function negative_drift_uniform_grid_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) ones(numel(x),1) * (-1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1001; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %%dlmwrite(strcat(mfilename, '_3_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_3_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function x_min_is_less_than_zero_test(testCase) % x_min < 0 tolerances = testCase.TestData.tolerances; mu_x = @(x) zeros(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = -0.49; x_max = 0.5; I = 5; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %%dlmwrite(strcat(mfilename, '_4_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_4_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end %Don't remember what this was for, but doesn't apply now that we have Delta back in denominator. % function rescale_x_min_and_x_max_test(testCase) % Change in the scale of x_min and x_max for given I % tolerances = testCase.TestData.tolerances; % % mu_x = @(x) zeros(numel(x),1); % sigma_bar = 0.1; % sigma_2_x = @(x) (sigma_bar*x).^2; % x_min = 0.01; % x_max = 1; % I = 1001; % scaler = 6; % Just pick 6 as a random scaler to rescale x. % x = linspace(x_min, x_max, I)'; % x_rescale = scaler * x; % A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); % A_rescale = discretize_univariate_diffusion(x_rescale, mu_x(x_rescale), sigma_2_x(x_rescale)) / scaler; % % verifyTrue(testCase, norm(A - A_rescale, Inf) < tolerances.test_tol, 'A value no longer matches'); % % %The following are worth testing for almost every matrix in the test suit. % verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); % verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); % verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); % end function construction_test(testCase) %Use variations of construction with mu<0 tolerances = testCase.TestData.tolerances; mu_x = @(x) ones(numel(x),1) * (-2); % A random mu, which is less than 0 sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1001; x = linspace(x_min, x_max, I)'; Delta = x(2) - x(1); Delta_2 = Delta^2; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); mu = mu_x(x); sigma_2 = sigma_2_x(x); % Variation 1: construct the A assuming that mu < 0 (i.e., the direction of the finite differences is known a-priori) X_var1 = - mu/Delta + sigma_2/(2*Delta_2); Y_var1 = mu/Delta - sigma_2/Delta_2; Z_var1 = sigma_2/(2*Delta_2); A_var1 = spdiags(Y_var1, 0, I, I) + spdiags(X_var1(2:I), -1, I, I) + spdiags([0;Z_var1(1:I-1)], 1, I, I); A_var1(1, 1) = Y_var1(1) + X_var1(1); A_var1(I,I)= Y_var1(I) + sigma_2(I)/(2*Delta_2); % Variation 2: construct the A with a for loop, essentially adding in each row as an equation. Map to exact formulas in a latex document. S = zeros(I, I+2); for i = 1: I x_i = -mu(i)/Delta + sigma_2(i)/(2*Delta_2); y_i = mu(i)/Delta - sigma_2(i)/Delta_2; z_i = sigma_2(i)/(2*Delta_2); S(i, i) = x_i; S(i, i+1) = y_i; S(i, i+2) = z_i; end S(1, 2) = S(1, 2) + S(1, 1); S(I, I+1) = mu(I)/Delta - sigma_2(I)/(2*Delta_2); A_var2 = sparse(S(:, 2: I+1)); verifyTrue(testCase, norm(A - A_var1, Inf) < tolerances.test_tol, 'A is different from A_var1'); verifyTrue(testCase, norm(A - A_var2, Inf) < tolerances.test_tol, 'A is different from A_var2'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function monotonically_increasing_mu_test(testCase) % mu is monotonically increasing in x with mu(x_min)<0 and mu(x_max)>0 tolerances = testCase.TestData.tolerances; mu_x = @(x) (x - 0.5); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %dlmwrite(strcat(mfilename, '_7_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_7_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end function monotonically_decreasing_mu_test(testCase) % mu is monotonically decreasing in x with mu(x_min)>0 and mu(x_max)<0 tolerances = testCase.TestData.tolerances; mu_x = @(x) (x - 0.5) * (-1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %dlmwrite(strcat(mfilename, '_8_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_8_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end function concave_mu_test(testCase) % mu is concave in x with mu(x_min)<0, mu(x_max)<0 and mu(x)>0 for some x tolerances = testCase.TestData.tolerances; mu_x = @(x) (-(x - 0.5).^2 + 0.1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %dlmwrite(strcat(mfilename, '_9_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_9_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end %Removed. Should be checking that this throws errors, but not sure how to do it with matlab tests. % function zero_sigma_everywhere_test(testCase) % I = 5; % %mu_x = @(x) zeros(numel(x),1); % mu_x = @(x) -.01 * ones(numel(x),1); % sigma_2_x = @(x) zeros(numel(x),1); % x_min = 0.01; % x_max = 1; % x = linspace(x_min, x_max, I)'; % %A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); % %testCase.assertFail(@() discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x))); ???? Not working, % end function zero_sigma_somewhere_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) (x - 0.5) * (-1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = linspace(x_min, x_max, I)'; sigma_2 = sigma_2_x(x); sigma_2(1, 1) = 0; sigma_2(3, 1) = 0; sigma_2(5, 1) = 0; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2); %dlmwrite(strcat(mfilename, '_11_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_11_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end %These are utility functions for testing returned matrices. function result = is_stochastic_matrix(testCase, A) result = (max(abs(full(sum(A,2)))) < testCase.TestData.tolerances.test_tol); end function result = is_negative_diagonal(testCase, A) result = (max(full(diag(A))) < 0); end function result = is_negative_definite(testCase, A) result =all(eig(full(A)) < testCase.TestData.tolerances.test_tol); end
github
jlperla/continuous_time_methods-master
time_varying_optimal_stopping_diffusion_test.m
.m
continuous_time_methods-master/matlab/tests/time_varying_optimal_stopping_diffusion_test.m
5,932
utf_8
07eb198d7ad8da763c93e6ae5bf93526
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = time_varying_optimal_stopping_diffusion_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.test_tol_less = 1e-5; testCase.TestData.tolerances.test_tol_much_less = 1e-3; testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than test_tol end function baseline_one_period_test(testCase) tolerances = testCase.TestData.tolerances; parameters.rho = 0.05; %Discount rate parameters.x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma parameters.rho = 0.05; %Discount ra te parameters.u = @(t,x) x.^gamma + 0*t; %u(x) = x^gamma in this example parameters.S = @(t,x) S_bar + 0*x + 0*t; %S(x) = S_bar in this example parameters.mu = @(t,x) mu_bar + 0*x + 0*t; %i.e. mu(x) = mu_bar parameters.sigma_2 = @(t,x) (sigma_bar*x).^2 + 0*t; %i.e. sigma(x) = sigma_bar x %Grids x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value I = 100; parameters.t = 0; %One time period! parameters.x = linspace(x_min, x_max, I)'; %Create uniform grid and determine step sizes. settings.method = 'yuval'; tic; disp('yuval method'); results = optimal_stopping_diffusion(parameters, settings); plot(parameters.x, results.v, parameters.x, results.S) end function baseline_repeated_period_test(testCase) tolerances = testCase.TestData.tolerances; parameters.rho = 0.05; %Discount rate parameters.x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma parameters.rho = 0.05; %Discount ra te parameters.u = @(t,x) x.^gamma + 0*t; %u(x) = x^gamma in this example parameters.S = @(t,x) S_bar + 0*x + 0*t; %S(x) = S_bar in this example parameters.mu = @(t,x) mu_bar + 0*x + 0*t; %i.e. mu(x) = mu_bar parameters.sigma_2 = @(t,x) (sigma_bar*x).^2 + 0*t; %i.e. sigma(x) = sigma_bar x %Grids x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value I = 100; N = 3; parameters.t = linspace(0, 1, N)'; %One time period! parameters.x = linspace(x_min, x_max, I)'; %Create uniform grid and determine step sizes. settings.method = 'yuval'; tic; disp('yuval method'); results = optimal_stopping_diffusion(parameters, settings); v = reshape(results.v, [I N]); %in three dimensions now S = reshape(results.S, [I N]); %in three dimensions now %Useful to display the value funciton and the stopping value % surf(parameters.t, parameters.x, v); hold on; % surf(parameters.t, parameters.x, S,'FaceAlpha',0.5, 'EdgeColor', 'none'); %SHows the S a litle different. %%TODO: Make sure that the v is nearly identical for of the time periods, and that it is the same as the optimal_stopping_diffusion we previously calculated. end function changing_S_test(testCase) tolerances = testCase.TestData.tolerances; parameters.rho = 0.05; %Discount rate parameters.x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma parameters.rho = 0.05; %Discount rate parameters.u = @(t,x) x.^gamma + 0*t; parameters.S = @(t,x) S_bar + 0*x + .1 * t; %NOTE: value increasing over time! Should have less stopping parameters.mu = @(t,x) mu_bar + 0*x + 0*t; parameters.sigma_2 = @(t,x) (sigma_bar*x).^2 + 0*t; %Grids x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value I = 100; N = 10; parameters.t = linspace(0, 1, N)'; %One time period! parameters.x = linspace(x_min, x_max, I)'; %Create uniform grid and determine step sizes. settings.method = 'yuval'; tic; results = optimal_stopping_diffusion(parameters, settings); v = reshape(results.v, [I N]); %in three dimensions now S = reshape(results.S, [I N]); %in three dimensions now % surf(parameters.t, parameters.x, v); hold on; % surf(parameters.t, parameters.x, S,'FaceAlpha',0.5, 'EdgeColor', 'none'); %SHows the S a litle different. %%TODO: Make sure that this makes sense, that the v has less stopping than the one with an identical stopping value, etc. end
github
jlperla/continuous_time_methods-master
discretize_nonuniform_univariate_diffusion_test.m
.m
continuous_time_methods-master/matlab/tests/discretize_nonuniform_univariate_diffusion_test.m
9,936
utf_8
730b1686969f65e6c50d1eef6d7be0f1
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = discretize_nonuniform_univariate_diffusion_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function zero_drift_test(testCase)%Simple and small with zero drift with uniform grid tolerances = testCase.TestData.tolerances; mu_x = @(x) zeros(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = logspace(log10(x_min),log10(x_max),I)'; [A, Delta_p, Delta_m] = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %dlmwrite(strcat(mfilename, '_1_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_1_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end function zero_drift_for_large_sample_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) zeros(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1000; % It gets very slow when sample size is getting bigger. x = logspace(log10(x_min),log10(x_max),I)'; [A, Delta_p, Delta_m] = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); verifyTrue(testCase, (nnz(A) == 2998), 'Number of non-zero values is wrong') %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); verifyTrue(testCase,is_negative_definite(testCase, A), 'Intensity Matrix is not positive definite'); end function negative_drift_uniform_grid_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) ones(numel(x),1) * (-1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1001; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %dlmwrite(strcat(mfilename, '_4_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_4_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function positive_drift_uniform_grid_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) ones(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 1001; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %dlmwrite(strcat(mfilename, '_5_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_5_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function monotonically_increasing_mu_test(testCase) % mu is monotonically increasing in x with mu(x_min)<0 and mu(x_max)>0 tolerances = testCase.TestData.tolerances; mu_x = @(x) (x - 0.5); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %dlmwrite(strcat(mfilename, '_6_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_6_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function monotonically_decreasing_mu_test(testCase) % mu is monotonically increasing in x with mu(x_min)<0 and mu(x_max)>0 tolerances = testCase.TestData.tolerances; mu_x = @(x) (x - 0.5) * (-1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %dlmwrite(strcat(mfilename, '_7_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_7_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end function concave_mu_test(testCase) % mu is concave in x with mu(x_min)<0, mu(x_max)<0 and mu(x)>0 for some x tolerances = testCase.TestData.tolerances; mu_x = @(x) (-(x - 0.5).^2 + 0.1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 0.01; x_max = 1; I = 5; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %To save the file again, can uncomment this. %[indices_i, indices_j, values_ij] = find(A); %Uncomment to save again %dlmwrite(strcat(mfilename, '_8_A_output.csv'), [indices_i indices_j values_ij], 'precision', tolerances.default_csv_precision); %Uncomment to save again %Load and check against the sparse matrix file. A_check = spconvert(dlmread(strcat(mfilename, '_8_A_output.csv'))); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); %The following are worth testing for almost every matrix in the test suit. verifyTrue(testCase,is_stochastic_matrix(testCase, A), 'Intensity matrix rows do not sum to 0'); verifyTrue(testCase,is_negative_diagonal(testCase, A), 'Intensity Matrix diagonal has positive elements'); verifyTrue(testCase,isbanded(A,1,1), 'Intensity Matrix is not tridiagonal'); end %These are utility functions for testing returned matrices. function result = is_stochastic_matrix(testCase, A) result = (max(abs(full(sum(A,2)))) < testCase.TestData.tolerances.test_tol); end function result = is_negative_diagonal(testCase, A) result = (max(full(diag(A))) < 0); end function result = is_negative_definite(testCase, A) result =all(eig(full(A)) < testCase.TestData.tolerances.test_tol); end
github
jlperla/continuous_time_methods-master
KFE_discretized_univariate_test.m
.m
continuous_time_methods-master/matlab/tests/KFE_discretized_univariate_test.m
6,773
utf_8
de2022549d28f4046aae8918d000139e
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = KFE_discretized_univariate_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.lower_test_tol = 1e-6; %Too high precision for some tests with big matrices testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function [A, x] = baseline_negative_drift_discretization(I, testCase) %Used by other test cases as a baseline. mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; x_min = 1; x_max = 2; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); end function small_LLS_vs_eigenvalue_test(testCase) %Simple baseline check. tolerances = testCase.TestData.tolerances; I = 20; %Small matrix. [A, x] = baseline_negative_drift_discretization(I, testCase); f = stationary_distribution_discretized_univariate(A, x); % dlmwrite(strcat(mfilename, '_1_f_output.csv'), f, 'precision', tolerances.default_csv_precision); %Uncomment to save again f_check = dlmread(strcat(mfilename, '_1_f_output.csv')); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); settings.method = 'LLS'; %Now using the LLS method f_lls = stationary_distribution_discretized_univariate(A,x, settings); verifyTrue(testCase,norm(f_lls - f_check, Inf) < tolerances.lower_test_tol, 'f value no longer matches'); %With a perfect initial guess! settings.initial_guess = f_check; f_lls = stationary_distribution_discretized_univariate(A,x, settings); verifyTrue(testCase,norm(f_lls - f_check, Inf) < tolerances.lower_test_tol, 'f value no longer matches'); end function medium_LLS_vs_eigenvalue_test(testCase) %Larger system using default options, etc. tolerances = testCase.TestData.tolerances; I = 1000; %Larger grid settings.print_level = 1; settings.method = 'eigenproblem'; %Will try to only find the appropriate eigenvector, which can be faster. settings.num_basis_vectors = 100; %In general, need to tweak this to use the default eigenvector approach for large I [A, x] = baseline_negative_drift_discretization(I, testCase); tic; f = stationary_distribution_discretized_univariate(A, x, settings); toc; %dlmwrite(strcat(mfilename, '_2_f_output.csv'), f, 'precision', tolerances.default_csv_precision); %Uncomment to save again f_check = dlmread(strcat(mfilename, '_2_f_output.csv')); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); settings.method = 'LLS'; %Now using the LLS method with the default pre-conditioner tic; f_lls = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f_lls - f_check, Inf) < tolerances.lower_test_tol, 'f value no longer matches'); settings.method = 'eigenproblem_all'; %Now using the eigenvalues, but calculating all tic; f_eigen_all = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f_eigen_all - f_check, Inf) < tolerances.lower_test_tol, 'f value no longer matches'); end function medium_preconditioner_test(testCase) %tests of the various preconditioners. Some not worth much. tolerances = testCase.TestData.tolerances; I = 1000; %Larger grid settings.print_level = 1; [A, x] = baseline_negative_drift_discretization(I, testCase); %Use the eigenproblem approach as a comparison disp('Eigenvalue based solution'); tic; f = stationary_distribution_discretized_univariate(A, x, settings); toc; %dlmwrite(strcat(mfilename, '_3_f_output.csv'), f, 'precision', tolerances.default_csv_precision); %Uncomment to save again f_check = dlmread(strcat(mfilename, '_3_f_output.csv')); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); %Setup basic LLS settings.method = 'LLS'; %Now using the LLS method with the default pre-conditioner settings.max_iterations = 50000; %Only really need this many to test the no preconditioner version. settings.tolerance = 1E-8; settings.print_level = 1; %Use LLS with no preconditioners tic; disp('LLS no preconditioner'); settings.preconditioner = 'none'; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); tic; disp('LLS with incomplete LU preconditioner and perfect initial guess'); settings.preconditioner = 'incomplete_LU'; settings.initial_guess = f_check; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); tic; disp('LLS incomplete LU preconditioner'); settings.preconditioner = 'incomplete_LU'; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); tic; disp('LLS jacobi preconditioner'); settings.preconditioner = 'jacobi'; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); tic; disp('LLS incomplete_cholesky preconditioner'); settings.preconditioner = 'incomplete_cholesky'; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); tic; disp('LLS with incomplete LU preconditioner and mediocre initial guess'); settings.preconditioner = 'incomplete_LU'; settings.initial_guess = linspace(.005,0,I)'; f = stationary_distribution_discretized_univariate(A, x, settings); toc; verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); end
github
jlperla/continuous_time_methods-master
discretize_time_varying_univariate_diffusion_test.m
.m
continuous_time_methods-master/matlab/tests/discretize_time_varying_univariate_diffusion_test.m
18,948
utf_8
da7ccac5bc2c633d5a41ad01ffd7f0ee
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = discretize_time_varying_univariate_diffusion_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function nothing_uniform_test(testCase) tolerances = testCase.TestData.tolerances; mu_tx = @(t, x) -0.1 + t + .1*x;%cludge if constant since bsxfun gets confused otherwise sigma_bar = 0.1; sigma_2_tx = @(t, x) (sigma_bar*x).^2; %Want to make sure there are no identical spacing. To aid in verifying the code. x = [0.01 .1 .22 .4 .91 1]'; t = [0.0 1.1 2.4 5.1 6.9]'; [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; %should check that this does the correct permuations in order and calls the underlying function. mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); %dlmwrite(strcat(mfilename, '_11_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_11_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); end function basic_test(testCase) %This will create a time-varying setup, and should show that tolerances = testCase.TestData.tolerances; mu_tx = @(t, x) -0.1 + t + .1*x;%cludge if constant since bsxfun gets confused otherwise sigma_bar = 0.1; sigma_2_tx = @(t, x) (sigma_bar*x).^2; %Grid x_min = 0.01; x_max = 1; I = 5; t_min = 0.0; t_max = 10.0; N = 4; x = linspace(x_min, x_max, I)'; t = linspace(t_min, t_max, N)'; [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; %should check that this does the correct permuations in order and calls the underlying function. mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); %dlmwrite(strcat(mfilename, '_1_A_output.csv'), full(A), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_1_A_output.csv')); verifyTrue(testCase,norm(A - A_check, Inf) < tolerances.test_tol, 'A value no longer matches'); end function non_time_varying_test(testCase) %This will create a non-time-varying setup, and should show that tolerances = testCase.TestData.tolerances; % This test use mu(x)=mu*x;sigma(x)^2=sigma^2*x^2 and u(x)=exp(x) mu_tx = @(t,x) -0.01 * x+0*t; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; sigma_2_x = @(x) (sigma_bar*x).^2; u_tx = @(t,x) exp(x)+t*0; u_x = @(x) exp(x); rho = 0.05; x_min = 0.1; x_max = 3; t_min = 0.0; t_max = 10.0; I = 1500; N = 10; x = linspace(x_min, x_max, I)'; t = linspace(t_min,t_max, N)'; % generate permutations of x and t, tacking t first then x [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. % Solve for A_n and v_n for non time-varying method, use as check %A_n = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); %dlmwrite(strcat(mfilename, '_2_An_output.csv'), full(A_n), 'precision', tolerances.default_csv_precision); %Uncomment to save again A_check = dlmread(strcat(mfilename, '_2_An_output.csv')); u_n=u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the non-time %varying sprocess %v_n = simple_HJBE_discretized_univariate(A_n, x, u_n, rho); %dlmwrite(strcat(mfilename, '_2_vn_output.csv'), v_n, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_2_vn_output.csv')); % Solve for A and v for time-varying method [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); u = bsxfun(u_tx, state_permutations(:,1), state_permutations(:,2)); % sp(:,1) is time sp(:,2) is x [v,success] = simple_HJBE_discretized_univariate(A, state_permutations(:,1), u, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_2_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check_1 = dlmread(strcat(mfilename, '_2_v_output.csv')); % tests for 1. A is same as A_n; 2. A is same across time; 3. v is same % as v_n ; 4. v is same across time % initial test: make sure the v of time varying result didn't change. verifyTrue(testCase,norm(v - v_check_1, Inf) < 1e-9, 'v time-varying result no longer matches'); % this checks the matrix A1 in time varying case same as A in % non-time-varying case verifyTrue(testCase,norm(A(1:I,1:I) + A(1:I,I+1:2*I) - A_check, Inf) < 1e-5, 'A_1 not match with non-time-varying result'); % This checks the matrix A1 in time varying case same as A_n, n % randomly drawn luck=max(floor(rand*N),2); indx=(luck-1)*I+1; verifyTrue(testCase,norm(A(1:I,1:I) + A(1:I,I+1:2*I) - A(indx:indx+I-1,indx:indx+I-1) - A(indx:indx+I-1,indx+I:indx+2*I-1) , Inf) < 1e-9, 'A_1 not match with A_n'); %verifyTrue(testCase, success==true, 'unsuccesful'); % This checks the value function of t=0 is same as v in % non-time-varying result verifyTrue(testCase,norm(v(1:I) - v_check, Inf) < 1e-5, 'v_1 not match with non-time-varying result'); % This checks the v_1 in time varying case same as v_n luck=max(floor(rand*N),2); indx=(luck-1)*I+1; verifyTrue(testCase,norm(v(1:I) - v(indx:indx+I-1), Inf) < 1e-9, 'v_1 not match with v_n'); end function time_varying_u_test(testCase) %This will create a time-varying setup, and should show that tolerances = testCase.TestData.tolerances; % mu and sig^2 not time varying mu_tx = @(t,x) -0.01 * x+0*t; sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; %Grid rho = 0.05; x_min = 0.1; x_max = 3; I = 1000; t_min = 0.0; t_max = 1.0; N = 100; x_base = linspace(x_min, x_max, I)'; t_base = linspace(t_min, t_max, N)'; I_extra = 15; N_extra = 15; %Linspace then merge in extra points x_extra = linspace(x_min, x_max, I_extra)'; t_extra = linspace(t_min, t_max, N_extra)'; %t_extra = t_base;% only change x grid %x_extra = x_base; % only change t grid x = unique([x_base; x_extra], 'sorted'); t = unique([t_base; t_extra], 'sorted'); % u is time varying a = 0.0; % this is defining F(0)=a u_tx = @(t,x) exp(x).*((t_max-a)/t_max*t+a); % F(t)=(T-a)/T*t+a % Uncomment if want to compute v_b, saved in '_3_v_output' [t_grid_b, x_grid_b] = meshgrid(t_base,x_base); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations_b = [t_grid_b(:) x_grid_b(:)]; mu_b = bsxfun(mu_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2_b = bsxfun(sigma_2_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A_b, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t_base, x_base, mu_b, sigma_2_b); u_b = bsxfun(u_tx, state_permutations_b(:,1), state_permutations_b(:,2)); v_b = simple_HJBE_discretized_univariate(A_b, state_permutations_b(:,1), u_b, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_3_v_output.csv'), v_b, 'precision', tolerances.default_csv_precision); %Uncomment to save again [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); u = bsxfun(u_tx, state_permutations(:,1), state_permutations(:,2)); [v,success] = simple_HJBE_discretized_univariate(A, state_permutations(:,1), u, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_33_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_3_v_output.csv')); % test whether baseline result changes verifyTrue(testCase,norm(v_b - v_check, Inf) < tolerances.test_tol, 'v_baseline value no longer matches'); % test whether the add point results after interploration is close to % baseline v_intp = interp2(t_grid, x_grid, reshape(v,size(x_grid,1),size(x_grid,2)), t_grid_b, x_grid_b); % interpolate v to v_b verifyTrue(testCase,norm(reshape(v_intp,size(v_intp,1)*size(v_intp,2),1) - v_check, Inf) < 5e-3, 'v_addpoint value not matches'); % Notice here: the max diff is 0.0038, not sure whether it's acceptable % or not end function time_varying_mu_test(testCase) %This will create a time-varying setup, and should show that tolerances = testCase.TestData.tolerances; %Grid rho = 0.05; x_min = 0.1; x_max = 3; I = 1000; t_min = 0.0; t_max = 1.0; N = 100; x_base = linspace(x_min, x_max, I)'; t_base = linspace(t_min, t_max, N)'; a = 0.0; % this is defining F(0)=a % mu is time varying mu_tx = @(t,x) -0.01 * x .*((t_max-a)/t_max*t+a); sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; I_extra = 15; N_extra = 15; %Linspace then merge in extra points x_extra = linspace(x_min, x_max, I_extra)'; t_extra = linspace(t_min, t_max, N_extra)'; %t_extra = t_base;% only change x grid %x_extra = x_base; % only change t grid x = unique([x_base; x_extra], 'sorted'); t = unique([t_base; t_extra], 'sorted'); % u is not time varying u_tx = @(t,x) exp(x); % F(t)=(T-a)/T*t+a % Uncomment if want to compute v_b, saved in '_3_v_output' [t_grid_b, x_grid_b] = meshgrid(t_base,x_base); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations_b = [t_grid_b(:) x_grid_b(:)]; mu_b = bsxfun(mu_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2_b = bsxfun(sigma_2_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A_b, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t_base, x_base, mu_b, sigma_2_b); u_b = bsxfun(u_tx, state_permutations_b(:,1), state_permutations_b(:,2)); v_b = simple_HJBE_discretized_univariate(A_b, state_permutations_b(:,1), u_b, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_4_v_output.csv'), v_b, 'precision', tolerances.default_csv_precision); %Uncomment to save again [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); u = bsxfun(u_tx, state_permutations(:,1), state_permutations(:,2)); [v,success] = simple_HJBE_discretized_univariate(A, state_permutations(:,1), u, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_44_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_4_v_output.csv')); % test whether baseline result changes verifyTrue(testCase,norm(v_b - v_check, Inf) < tolerances.test_tol, 'v_baseline value no longer matches'); % test whether the add point results after interploration is close to % baseline v_intp = interp2(t_grid, x_grid, reshape(v,size(x_grid,1),size(x_grid,2)), t_grid_b, x_grid_b); % interpolate v to v_b verifyTrue(testCase,norm(reshape(v_intp,size(v_intp,1)*size(v_intp,2),1) - v_check, Inf) < 1e-3, 'v_addpoint value not matches'); % Notice here: the max diff is 0.0038, not sure whether it's acceptable % or not end function time_varying_both_shift_test(testCase) %This will create a time-varying setup, and should show that tolerances = testCase.TestData.tolerances; %Grid rho = 0.05; x_min = 0.1; x_max = 3; I = 1000; t_min = 0.0; t_max = 1.0; N = 200; x_base = linspace(x_min, x_max, I)'; t_base = linspace(t_min, t_max, N)'; a = 0.0; % this is defining F(0)=a % mu is time varying mu_tx = @(t,x) -0.01 * x .*((t_max-a)/t_max*t+a); sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; %Some shifts in x and t spaces x_shift_1 = floor(0.3 * I); x_shift_2 = floor(0.7 * I); t_shift_1 = floor(0.3 * N); t_shift_2 = floor(0.7 * N); %Linspace then merge in extra points nn = length(x_base); shifts = (rand(nn, 1) - 0.5) / (nn * 10e4); shifts(1, 1) = 0; shifts(end, 1) = 0; shifts(x_shift_1 + 1: x_shift_1 + 10, 1) = zeros(10, 1); shifts(x_shift_2 + 1: x_shift_2 + 10, 1) = zeros(10, 1); x = x_base+shifts; tt = length(t_base); shifts = (rand(tt, 1) - 0.5) / (tt * 10e2); shifts(1, 1) = 0; shifts(end, 1) = 0; shifts(t_shift_1 + 1: t_shift_1 + 10, 1) = zeros(10, 1); shifts(t_shift_2 + 1: t_shift_2 + 10, 1) = zeros(10, 1); t = t_base+shifts; % u is also time varying u_tx = @(t,x) exp(x).*((t_max-a)/t_max*t+a); % F(t)=(T-a)/T*t+a % Uncomment if want to compute v_b, saved in '_3_v_output' [t_grid_b, x_grid_b] = meshgrid(t_base,x_base); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations_b = [t_grid_b(:) x_grid_b(:)]; mu_b = bsxfun(mu_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2_b = bsxfun(sigma_2_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A_b, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t_base, x_base, mu_b, sigma_2_b); u_b = bsxfun(u_tx, state_permutations_b(:,1), state_permutations_b(:,2)); v_b = simple_HJBE_discretized_univariate(A_b, state_permutations_b(:,1), u_b, rho); % state_perm need to be in size N*I %dlmwrite(strcat(mfilename, '_5_v_output.csv'), v_b, 'precision', tolerances.default_csv_precision); %Uncomment to save again [t_grid, x_grid] = meshgrid(t,x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; mu = bsxfun(mu_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(sigma_2_tx, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); u = bsxfun(u_tx, state_permutations(:,1), state_permutations(:,2)); [v,success] = simple_HJBE_discretized_univariate(A, state_permutations(:,1), u, rho); % state_perm need to be in size N*I v_check = dlmread(strcat(mfilename, '_5_v_output.csv')); % test whether baseline result changes verifyTrue(testCase,norm(v_b - v_check, Inf) < tolerances.test_tol, 'v_baseline value no longer matches'); % test whether the add point results after interploration is close to % baseline v_intp = interp2(t_grid, x_grid, reshape(v,size(x_grid,1),size(x_grid,2)), t_grid_b, x_grid_b); % interpolate v to v_b verifyTrue(testCase,norm(reshape(v_intp,size(v_intp,1)*size(v_intp,2),1) - v_check, Inf) < 1e-6, 'v_addpoint value not matches'); % Notice here: the max diff is 1e-7, not sure whether it's acceptable % or not end
github
jlperla/continuous_time_methods-master
HJBE_discretized_univariate_test.m
.m
continuous_time_methods-master/matlab/tests/HJBE_discretized_univariate_test.m
5,791
utf_8
deb22a4d65b518586586c31aa32b43a9
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = HJBE_discretized_univariate_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.lower_test_tol = 1e-8; %For huge matrices, the inf norm can get a little different. testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function simple_value_function_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) exp(x); rho = 0.05; x_min = 1; x_max = 2; I = 20; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); %dlmwrite(strcat(mfilename, '_1_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_1_v_output.csv')); verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); end function bigger_value_function_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) log(x); rho = 0.05; x_min = .01; x_max = 10; I = 10000; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); %dlmwrite(strcat(mfilename, '_2_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_2_v_output.csv')); verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.lower_test_tol, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); end % %This will try to jointly solve for the KFE and the value function with linear least squares. function joint_value_function_KFE_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * ones(numel(x),1); sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar * ones(numel(x),1)).^2; u_x = @(x) log(x); rho = 0.05; x_min = 0.1; x_max = 2; I = 1000; x = linspace(x_min, x_max, I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. disp('Solving HJBE on its own'); tic; [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); toc; %dlmwrite(strcat(mfilename, '_3_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_3_v_output.csv')); verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); %Now find the KFE with linear least squares and the default preconditioner settings.print_level = 1; %settings.method = 'LLS'; %settings.method = 'eigenproblem_all'; disp('Solving stationary distribution on its own'); tic; f = stationary_distribution_discretized_univariate(A, x, settings); toc; %dlmwrite(strcat(mfilename, '_3_f_output.csv'), f, 'precision', tolerances.default_csv_precision); %Uncomment to save again f_check = dlmread(strcat(mfilename, '_3_f_output.csv')); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); %Now, solve as a joint problem with LLS %settings.preconditioner = 'none'; settings.sparse = 'false'; disp('Solving dense'); tic; [v, f, success] = simple_joint_HJBE_stationary_distribution_univariate(A, x, u, rho, settings); verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); toc; %Now try as a sparse system. disp('Solving sparse with no preconditioner'); settings.sparse = 'true'; tic; [v, f, success] = simple_joint_HJBE_stationary_distribution_univariate(A, x, u, rho, settings); toc; verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); %Now try as a sparse system with jacobi preconditioner disp('Solving sparse with jacobi preconditioner'); settings.sparse = 'jacobi'; tic; [v, f, success] = simple_joint_HJBE_stationary_distribution_univariate(A, x, u, rho, settings); toc; verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase,norm(f - f_check, Inf) < tolerances.test_tol, 'f value no longer matches'); end
github
jlperla/continuous_time_methods-master
simple_optimal_stopping_diffusion_test.m
.m
continuous_time_methods-master/matlab/tests/simple_optimal_stopping_diffusion_test.m
35,987
utf_8
608f184a92134e7f8d0d49679e367164
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = simple_optimal_stopping_diffusion_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.test_tol_less = 1e-5; testCase.TestData.tolerances.test_tol_much_less = 1e-3; testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than test_tol end %To add in cleanup code, add here %function teardownOnce(testCase) %end %This runs code prior to every test. Not required function setup(testCase) %Setup defaults. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma parameters.rho = 0.05; %Discount rate parameters.x_min = 0.01; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example %Baseline test is GBM parameters.mu_x = @(x) mu_bar * x; %i.e. mu(x) = mu_bar * x parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x settings.I = 300; %number of grid variables for x settings.print_level = 0; %Optional settings.error_tolerance = 1E-12; %Optional settings.max_iter = 10000; %These will be overwritten as required. testCase.TestData.baseline_parameters = parameters; testCase.TestData.baseline_settings = settings; end %This unpacks everything stored in the testCase function [settings, parameters, tolerances] = unpack_setup(testCase) settings = testCase.TestData.baseline_settings; parameters = testCase.TestData.baseline_parameters; tolerances = testCase.TestData.tolerances; end % Define an absolute tolerance for floating point comparisons %A minimally modified version of the HACT code for comparison. The main difference is generality and the boundary value at 0. See /graveyard function baseline_HACT_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %These are the defaults used in the yuval solver. They are not necessarily the best choices, but test consistency. settings.I = 1000; settings.error_tolerance = 1.0e-12; settings.lm_mu = 1e-3; settings.lm_mu_min = 1e-5; settings.lm_mu_step = 5; settings.max_iter = 20; %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount ra te parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %Check all values v_old = dlmread(strcat(mfilename,'_1_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); end function LCP_methods_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); settings.I = 500; %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount ra te parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. settings.method = 'yuval'; tic; disp('yuval method'); results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; v_old = v; %Other methods seeing if the same toc; fprintf('L2 Error = %d\n',results.LCP_L2_error); %Check all values % v_old = dlmread(strcat(mfilename,'_1_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); %Try the next method. settings.method = 'lemke'; %This is a pretty poor method when I gets large, but seems robust. tic; disp('Lemke method'); results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; toc; fprintf('L2 Error = %d\n',results.LCP_L2_error); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); %Try the next method. settings.method = 'knitro'; tic; disp('Knitro LCP method'); results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; toc; fprintf('L2 Error = %d\n',results.LCP_L2_error); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); end function convex_u_x_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 2; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^2 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_2_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_2_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function u_x_is_negative_for_small_x_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x - 0.2; %u(x) = x - 0.2 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %settings.method = 'knitro'; %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_3_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values %a comparable value is saved as 'mfilename_33_v_output.csv' v_old = dlmread(strcat(mfilename,'_3_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function negative_S_x_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = -2.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma - .5; %u(x) = x^gamma minus a constant in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %settings.method = 'knitro'; %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_4_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values %a comparable value is saved as 'mfilename_44_v_output.csv' v_old = dlmread(strcat(mfilename,'_4_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, results.converged); %plot(results.x, results.v, results.x, parameters.S_x(results.x)) verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function S_x_increases_in_x_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %settings.error_tolerance = 1e-6;%Can't hit the very high tolerance for some reason. Going much higher and it doesn't converge. %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) 5*x + 5.5; %S(x) = x in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_5_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_5_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, results.converged); plot(results.x, results.v, results.x, parameters.S_x(results.x)) verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function S_x_decreases_in_x_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); % settings.error_tolerance = 1e-6;%Can't hit the very high tolerance for some reason. Going much higher and it doesn't converge. %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar - x; %S(x) = S_bar - x in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_6_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values verifyTrue(testCase, results.converged); plot(results.x, results.v, results.x, parameters.S_x(results.x)) v_old = dlmread(strcat(mfilename,'_6_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function negative_mu_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %settings.error_tolerance = 1e-6;%Can't hit the very high tolerance for some reason. Going much higher and it doesn't converge. %Rewriting parameters mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_8_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_8_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function positive_mu_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); settings.I = 300; %Tough to get to large I, but also not really necessary. %Rewriting parameters mu_bar = 0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.02; %Variance S_bar = 13.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_9_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_9_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, results.converged); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function zero_mu_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. mu_bar = 0; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 13.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_10_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_10_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, results.converged); plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function negative_mu_min_and_positive_mu_max_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) .2 * (x - 0.5); %i.e. mu(x) = x - 0.5; parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_11_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_11_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function positive_mu_min_and_negative_mu_max_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %settings.error_tolerance = 1e-85; %unable to get a high level of accuracy. settings.max_iter = 30000; %Needs more iterations for some reason. %Rewriting parameters entirely. sigma_bar = 0.01; %Variance S_bar = 14.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) -x + 0.5; %i.e. mu(x) = -x + 0.5; parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x %Create uniform grid and determine step sizes. settings.method='lemke'; %Works much better here, for some reason. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_12_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_12_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function negative_mu_and_zero_sigma_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount rate parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^0.5 in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) sigma_bar * ones(numel(x),1); %i.e. sigma(x) = sigma_bar %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %dlmwrite(strcat(mfilename, '_13_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %Uncomment to save again %Check all values v_old = dlmread(strcat(mfilename,'_13_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches negative u(x) for small x example'); end function knitro_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); settings.I = 500; mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = 10.0; %the value of stopping gamma = 0.5; %us(x) = x^gamma parameters.rho = 0.05; %Discount ra te parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = sigma_bar x settings.method = 'knitro'; tic; results = simple_optimal_stopping_diffusion(parameters, settings); toc; v = results.v; plot(results.x, results.v, results.x, parameters.S_x(results.x)); verifyTrue(testCase,results.converged); end function no_stopping_point_test(testCase) [settings, ~, tolerances] = unpack_setup(testCase); %These are the defaults used in the yuval solver. They are not necessarily the best choices, but test consistency. settings.I = 1000; settings.error_tolerance = 1.0e-12; settings.lm_mu = 1e-3; settings.lm_mu_min = 1e-5; settings.lm_mu_step = 5; settings.max_iter = 20; %Rewriting parameters entirely. mu_bar = -0.01; %Drift. Sign changes the upwind direction. sigma_bar = 0.01; %Variance S_bar = -100.0; %the value of stopping gamma = 0.5; %u(x) = x^gamma %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion parameters.rho = 0.05; %Discount ra te parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example parameters.S_x = @(x) S_bar.*ones(numel(x),1); %S(x) = S_bar in this example parameters.mu_x = @(x) mu_bar * ones(numel(x),1); %i.e. mu(x) = mu_bar parameters.sigma_2_x = @(x) (sigma_bar*x).^2; %i.e. sigma(x) = (sigma_bar * x).^2 %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); v = results.v; %Check all values %dlmwrite(strcat(mfilename,'_14_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %To save results again v_old = dlmread(strcat(mfilename,'_14_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); end % % %I don't understand these tests, so commenting out. No reason to have only 3 or 6 points. % function one_stopping_point_test(testCase) % [settings, ~, tolerances] = unpack_setup(testCase); % %These are the defaults used in the yuval solver. They are not necessarily the best choices, but test consistency. % settings.I = 3; % settings.error_tolerance = 1.0e-12; % settings.lm_mu = 1e-3; % settings.lm_mu_min = 1e-5; % settings.lm_mu_step = 5; % settings.max_iter = 20; % % %Rewriting parameters entirely. % mu_bar = 0; %Drift. Sign changes the upwind direction. % sigma_bar = 0.1; %Variance % %S_bar =10.0; %the value of stopping % gamma = 0.5; %u(x) = x^gamma % % %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion % parameters.rho = 0.05; %Discount ra te % parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value % parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value % % parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example % parameters.mu_x = @(x) mu_bar * x; %i.e. mu(x) = mu_bar * x % parameters.sigma_2_x = @(x) (sigma_bar * x).^2; %i.e. sigma(x) = (sigma_bar*x).^2 % % % Use the same parameters as above to calculate the S that has exactly obe element different from v % x = linspace(0.01, 1, 3)'; % u = x.^0.5; % mu = zeros(3, 1); % sigma_2 = (0.1*x).^2; % A = discretize_univariate_diffusion(x, mu, sigma_2, false); % Delta = x(2)-x(1); % rho = 0.05; % B = (rho * eye(3) - A); % v = B \ u; % S = v + [0.1 0 0.1]'; % % parameters.S_x = @(x) S; % % %Create uniform grid and determine step sizes. % results = simple_optimal_stopping_diffusion(parameters, settings); % v = results.v; % S = results.S; % % %Check all values % %dlmwrite(strcat(mfilename,'_15_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %To save results again % plot(results.x, results.v, results.x, parameters.S_x(results.x)) % v_old = dlmread(strcat(mfilename,'_15_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. % verifyTrue(testCase,results.converged, 'There is no stopping point.'); % verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches example'); % verifyTrue(testCase, sum(1 * (abs(v - S) < tolerances.test_tol_less)) == 1, 'There are more than one stopping point'); % end % % function two_stopping_point_test(testCase) % [settings, ~, tolerances] = unpack_setup(testCase); % %These are the defaults used in the yuval solver. They are not necessarily the best choices, but test consistency. % settings.I = 6; % settings.error_tolerance = 1.0e-12; % settings.lm_mu = 1e-3; % settings.lm_mu_min = 1e-5; % settings.lm_mu_step = 5; % settings.max_iter = 20; % % %Rewriting parameters entirely. % mu_bar = -0.01; %Drift. Sign changes the upwind direction. % sigma_bar = 0.1; %Variance % %S_bar =10.0; %the value of stopping % gamma = 0.5; %u(x) = x^gamma % % %Relevant functions for u(x), S(x), mu(x) and sigma(x) for a general diffusion dx_t = mu(x) dt + sigma(x) dW_t, for W_t brownian motion % parameters.rho = 0.05; %Discount ra te % parameters.x_min = 0.1; %Reflecting barrier at x_min. i.e. v'(x_min) = 0 as a boundary value % parameters.x_max = 1.0; %Reflecting barrier at x_max. i.e. v'(x_max) = 0 as a boundary value % % parameters.u_x = @(x) x.^gamma; %u(x) = x^gamma in this example % parameters.mu_x = @(x) mu_bar * (x - 0.5).^2; %i.e. mu(x) = mu_bar * (x - 0.5).^2 % parameters.sigma_2_x = @(x) (sigma_bar * x).^2; %i.e. sigma(x) = (sigma_bar * x).^2 % % % Use the same parameters as above to calculate the S that has exactly two elements different from v % x = linspace(0.01, 1, 6)'; % u = x.^0.5; % mu = -0.01*(x-0.5).^2; % sigma_2 = (0.1*x).^2; % A = discretize_univariate_diffusion(x, mu, sigma_2, false); % Delta = x(2)-x(1); % rho = 0.05; % B = ( rho * eye(6) - A); % v = B \ ( u); % S = v + [0 0 0.5 0.5 0.5 0.5]'; % % parameters.S_x = @(x) S; % % %Create uniform grid and determine step sizes. % results = simple_optimal_stopping_diffusion(parameters, settings); % v = results.v; % S = results.S; % % %Check all values % %dlmwrite(strcat(mfilename,'_16_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %To save results again % plot(results.x, results.v, results.x, parameters.S_x(results.x)) % v_old = dlmread(strcat(mfilename,'_16_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. % verifyTrue(testCase,results.converged, 'There is no stopping point.'); % verifyTrue(testCase, max(abs(v - v_old)) < tolerances.test_tol_less, 'Value of solution no longer matches HACT example'); % verifyTrue(testCase, ~(sum(1 * (abs(v - S) < tolerances.test_tol_less)) == 1), 'There is one stopping point'); % verifyTrue(testCase, sum(1 * (abs(v - S) < tolerances.test_tol_less)) == 2, 'There are more than two stopping point'); % end %This test runs the test case with only the default parameters in settings. function default_parameters_test(testCase) [~, parameters, tolerances] = unpack_setup(testCase); %default parameters, but note that settings is not used. settings.I = 1000; %Only the number of points is provided. %Create uniform grid and determine step sizes. results = simple_optimal_stopping_diffusion(parameters, settings); %dlmwrite(strcat(mfilename,'_22_v_output.csv'), results.v, 'precision', tolerances.default_csv_precision); %To save results again v_old = dlmread(strcat(mfilename,'_22_v_output.csv')); %Loads old value, asserts identical. Note that the precision of floating points in the .csv matters, and can't be lower than test_tol. verifyTrue(testCase, max(abs(results.v - v_old)) < tolerances.test_tol, 'Value of solution no longer matches default value'); end
github
jlperla/continuous_time_methods-master
simple_model_test.m
.m
continuous_time_methods-master/matlab/tests/simple_model_test.m
6,062
utf_8
2bdecc69be86d7a099960399ddc228b9
function tests = simple_model_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); end function simple_v_test(testCase) %% 1. test on v behavior for time changing u and big t grid % this test checks when T is large and u is moving sufficiently with t, the % value functions are smooth % mu and sig^2 not time varying mu_tx = @(t,x) -0.01 * x+0*t; sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; %Grid x_min = 0.1; x_max = 8; I = 1000; t_min = 0.0; t_max = 10.0; N = 100; x_base = linspace(x_min, x_max, I)'; t_base = linspace(t_min, t_max, N)'; I_extra = 15; N_extra = 15; %Linspace then merge in extra points x_extra = linspace(x_min, x_max, I_extra)'; t_extra = linspace(t_min, t_max, N_extra)'; %t_extra = t_base;% only change x grid %x_extra = x_base; % only change t grid x = unique([x_base; x_extra], 'sorted'); t = unique([t_base; t_extra], 'sorted'); % u is time varying a = 0.0; % this is defining F(0)=a u_tx = @(t,x) exp(x).*((t_max-a)/t_max*t+a); % F(t)=(T-a)/T*t+a % Uncomment if want to compute v_b, saved in '_3_v_output' [t_grid_b, x_grid_b] = meshgrid(t_base,x_base); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations_b = [t_grid_b(:) x_grid_b(:)]; mu_b = bsxfun(mu_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2_b = bsxfun(sigma_2_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A_b, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t_base, x_base, mu_b, sigma_2_b); u_b = bsxfun(u_tx, state_permutations_b(:,1), state_permutations_b(:,2)); rho = 0.09; v_b = simple_HJBE_discretized_univariate(A_b, state_permutations_b(:,1), u_b, rho); % state_perm need to be in size N*I vr = ValueMatch(v_b,x_base,Delta_p,Delta_m,h_p,h_m); v = reshape(v_b,I,N); diff_s = v(:,N-2) - v(:,N-1); diff_N = v(:,N-1) - v(:,N); diff_1 = v(:,1) - v(:,2); figure() plot(x_base,v(:,1),'-o');hold on plot(x_base,v(:,50),'-x'); hold on plot(x_base,v(:,N-1),'--','Linewidth',2); hold on plot(x_base,v(:,N)); legend('1st t','50th t','99th t','100th t') title('value function plot') figure() plot(x_grid,diff_1,'-o');hold on plot(x_grid,diff_s,'--');hold on plot(x_grid,diff_N); legend('1st to 2nd','N-2 to N-1','N-1 to N') title('difference of v plot') end function change_r_test(testCase) %% 2. test for r change and pi change mu_tx = @(t,x) -0.01 * x+0*t; sigma_bar = 0.1; sigma_2_tx = @(t,x) (sigma_bar*x).^2+0*t; %Grid x_min = 0.1; x_max = 8; I = 1000; t_min = 0.0; t_max = 10.0; N = 100; x_base = linspace(x_min, x_max, I)'; t_base = linspace(t_min, t_max, N)'; % u is time varying a = 0.1; % this is defining F(0)=a a_h = 5.0; % highest time multiplier value %u_tx = @(t,x) exp(x).*((t_max-a)/t_max*t+a); % F(t)=(T-a)/T*t+a u_tx = @(t,x) exp(x).*(a_h-abs(t-t_max/2)*(a_h-a)/(t_max/2)); % F(t)=a_h - abs(t-T/2)*(a_h-a_l)/(T/2) % Uncomment if want to compute v_b, saved in '_3_v_output' [t_grid_b, x_grid_b] = meshgrid(t_base,x_base); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations_b = [t_grid_b(:) x_grid_b(:)]; mu_b = bsxfun(mu_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2_b = bsxfun(sigma_2_tx, state_permutations_b(:,1), state_permutations_b(:,2)); %applies binary function to these, and remains in the correct stacked order. %Discretize the operator [A_b, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t_base, x_base, mu_b, sigma_2_b); u_b = bsxfun(u_tx, state_permutations_b(:,1), state_permutations_b(:,2)); r_center=0.08; r_low=0.05; for i=1:21 rho(i) = r_center - abs(i-11)*(r_center-r_low)/10; %rho(i) = 0.03+0.001*i; v_b = simple_HJBE_discretized_univariate(A_b, state_permutations_b(:,1), u_b, rho(i)); % state_perm need to be in size N*I vrr = ValueMatch(v_b,x_base,Delta_p,Delta_m,h_p,h_m); % this is residual v1-omega*v, its a function of t and r vv_{i} = reshape(v_b,I,N); v_T(:,i)=vv_{i}(:,N); % v at last time node v_T1(:,i)=vv_{i}(:,N-1); % v at second to last time node v_1(:,i)=vv_{i}(:,1); % v at first time node v_2(:,i)=vv_{i}(:,2); % second time node v_z1(i,:)=vv_{i}(1,:);% v at z=1th v_z500(i,:)=vv_{i}(500,:); % v at z=500th v_zI(i,:)=vv_{i}(I,:); % at z last point vr(:,i)=vrr; % vr function as t and r end % How interest rate change affect v(z=1,t) figure() plot(rho,v_T(1,:)); hold on plot(rho,v_T1(1,:)); hold on plot(rho,v_1(1,:),'--');hold on plot(rho,v_2(1,:),'--'); legend('Nth v','N-1th v','1st v','2nd v') title('How v(z=1,t) change accross r change') ylabel('interest rate') [rho_t_grid,t_rho_grid] = meshgrid(t_base,rho); figure() surf(rho_t_grid,t_rho_grid,v_z1) title('3D plot for v at z=1st point across r and t') ylabel('interest rate') xlabel('time') [point_t_grid,t_rho_grid] = meshgrid(t_base,1:21); figure() surf(point_t_grid,t_rho_grid,v_z1) title('3D plot for v at z=1st point across r points(not value) and t') ylabel('rgrid point') xlabel('time') [vr_rho_grid,vr_t_grid] = meshgrid(rho,t_base); figure() surf(vr_rho_grid,vr_t_grid,vr) title('3D plot for vr') ylabel('time') xlabel('r') end
github
jlperla/continuous_time_methods-master
HJBE_discretized_nonuniform_univariate_test.m
.m
continuous_time_methods-master/matlab/tests/HJBE_discretized_nonuniform_univariate_test.m
7,946
utf_8
24b20fb4f3cd538ecfd99916137a9388
%Using the unit testing framework in matlab. See https://www.mathworks.com/help/matlab/matlab_prog/write-simple-test-case-with-functions.html %To run tests: % runtests %would run all of them in the current directory % runtests('my_test') %runs just the my_test.m file % runtests('my_test/my_function_test') %runs only `my_function_test function in `my_test'. function tests = HJBE_discretized_nonuniform_univariate_test tests = functiontests(localfunctions); end %This is run at the beginning of the test. Not required. function setupOnce(testCase) addpath('../lib/'); testCase.TestData.tolerances.test_tol = 1e-9; testCase.TestData.tolerances.lower_test_tol = 1e-8; %For huge matrices, the inf norm can get a little different. testCase.TestData.tolerances.default_csv_precision = '%.10f'; %Should be higher precision than tolerances.test_tol end function simple_value_function_test(testCase) tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) exp(x); rho = 0.05; x_min = 1; x_max = 2; I = 1500; x = logspace(log10(x_min),log10(x_max),I)'; A = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho); %dlmwrite(strcat(mfilename, '_1_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_1_v_output.csv')); verifyTrue(testCase,norm(v - v_check, Inf) < tolerances.test_tol, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); %Solve with a uniform grid and check if similar after interpolation x_2 = linspace(x_min, x_max, 3 * I)'; %Twice as many points to be sure. A_2 = discretize_univariate_diffusion(x_2, mu_x(x_2), sigma_2_x(x_2)); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_2, success] = simple_HJBE_discretized_univariate(A_2, x_2, u_x(x_2), rho); %Make sure within range. This seems too large. verifyTrue(testCase, norm(interp1(x_2, v_2, x) - v,Inf) < 0.02, 'Not within range of interpolation'); end function GBM_adding_points_test(testCase) % Notice on csv files: %1._addpoint is for adding 20 points to the original grid; %2._22_v_output is result from randomly shifting existing points on the %grid %3._base_v_output is result for 1500 points uniform grid; tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) exp(x); rho = 0.05; x_min = 0.1; x_max = 3; I = 1500; I_extra = 20; %Linspace then merge in extra points x_base = linspace(x_min, x_max, I)'; x_extra = linspace(x_min, x_max, I_extra)'; x = unique([x_base; x_extra], 'sorted'); %Results from x_base, the uniform grid A = discretize_univariate_diffusion(x_base, mu_x(x_base), sigma_2_x(x_base)); u = u_x(x_base); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_base, success] = simple_HJBE_discretized_univariate(A, x_base, u, rho); % This writes the baseline uniform results for v %dlmwrite(strcat(mfilename, '_base_v_output.csv'), v_base, 'precision', tolerances.default_csv_precision); %Uncomment to save again % Results from x_add A_a = discretize_univariate_diffusion(x, mu_x(x), sigma_2_x(x)); u = u_x(x); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_a, success] = simple_HJBE_discretized_univariate(A_a, x, u, rho); % This writes the nonuniform results for v after adding points %dlmwrite(strcat(mfilename, '_addpoint_v_output.csv'), v_a, 'precision', tolerances.default_csv_precision); %Uncomment to save again % Check whether addpoint v is close to uniform v v_check = dlmread(strcat(mfilename, '_base_v_output.csv')); verifyTrue(testCase,norm(interp1(x, v_a, x_base) - v_check, Inf) < 1e-3, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); % Check by uniform grids % x = linspace(x_min, x_max, nn)'; % Data saved in HJBE_discretized_nonuniform_univarite_test_22_v_output.csv % % Add only one point to a uniform grid % x_base = linspace(x_min, x_max, nn - 1)'; % index = 3; % while length(x_base) ~= nn && index < 19 % x_base = unique([x_base; x_extra(index)], 'sorted'); % index = index + 1; % end % % if length(x_base) == nn % x = x_base; % else % print('Fail to construct a new x.'); % end end function NUF_shift_point_test(testCase) % Experiment1: Shift most points in from a uniform grid by a tiny number % This should be compared to the results generated from uniform grid tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) exp(x); rho = 0.05; x_min = 0.1; x_max = 3; I = 1500; x_base = linspace(x_min, x_max, I)'; shifts = (rand(I, 1) - 0.5) / (I * 10e4); shifts(1, 1) = 0; shifts(end, 1) = 0; shifts(601: 610, 1) = zeros(10, 1); shifts(1001: 1010, 1) = zeros(10, 1); x_s = x_base + shifts; A = discretize_univariate_diffusion(x_s, mu_x(x_s), sigma_2_x(x_s)); u = u_x(x_s); %Solve with nonuniform grid with random shifts epsilon [v, success] = simple_HJBE_discretized_univariate(A, x_s, u, rho); %dlmwrite(strcat(mfilename, '_22_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_22_v_output.csv')); %Solve with a uniform grid before using the base. %x_2 = linspace(x_min, x_max, 3 * I)'; %Twice as many points to be sure. A_2 = discretize_univariate_diffusion(x_base, mu_x(x_base), sigma_2_x(x_base)); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_2, success] = simple_HJBE_discretized_univariate(A_2, x_base, u_x(x_base), rho); verifyTrue(testCase,norm(interp1(x_base, v_2, x_s) - v_check, Inf) < 1e-6, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); end function NUF_shift_point_2_test(testCase) % Experiment2: Shift the nonuniform grid generated by adding point by a % tiny number. This should be compared to the results of adding point % test tolerances = testCase.TestData.tolerances; mu_x = @(x) -0.01 * x; sigma_bar = 0.1; sigma_2_x = @(x) (sigma_bar*x).^2; u_x = @(x) exp(x); rho = 0.05; x_min = 0.1; x_max = 3; I = 1500; I_extra = 20; %Linspace then merge in extra points x_base = linspace(x_min, x_max, I)'; x_extra = linspace(x_min, x_max, I_extra)'; x = unique([x_base; x_extra], 'sorted'); nn = length(x); shifts = (rand(nn, 1) - 0.5) / (nn * 10e4); shifts(1, 1) = 0; shifts(end, 1) = 0; shifts(601: 610, 1) = zeros(10, 1); shifts(1001: 1010, 1) = zeros(10, 1); x_s = x+shifts; A = discretize_univariate_diffusion(x_s, mu_x(x_s), sigma_2_x(x_s)); u = u_x(x_s); %Solve the simple problem: rho v(x) = u(x) + A v(x) for the above process. [v_s, success] = simple_HJBE_discretized_univariate(A, x_s, u, rho); %dlmwrite(strcat(mfilename, '_2222_v_output.csv'), v, 'precision', tolerances.default_csv_precision); %Uncomment to save again v_check = dlmread(strcat(mfilename, '_addpoint_v_output.csv')); verifyTrue(testCase,norm(interp1(x_s, v_s, x)- v_check, Inf) < 1e-6, 'v value no longer matches'); verifyTrue(testCase, success==true, 'unsuccesful'); end
github
jlperla/continuous_time_methods-master
optimal_stopping_diffusion.m
.m
continuous_time_methods-master/matlab/lib/optimal_stopping_diffusion.m
6,836
utf_8
2c932e105565b2a65bd30f7578635e60
% Modification of Ben Moll's: http://www.princeton.edu/~moll/HACTproject/option_simple_LCP.m % See notes and equation numbers in 'optimal_stopping.pdf' % Solves the HJB variational inequality that comes from a general diffusion process with optimal stopping. % min{rho v(t,x) - u(t,x) - mu(t,x)D_x v(t,x) - sigma(t,x)^2/2 D_xx v(x) - D_t v(t,x), v(t,x) - S(t,x)} = 0 % with a reflecting boundary at a x_min and x_max % unless S is very small, and u(x) is very large (i.e. no stopping), the reflecting boundary at x_min is unlikely to enter the solution % for a large x_min, it is unlikely to affect the stopping point. % Does so by using finite differences to discretize into the following complementarity problem: % min{rho v - u - A v, v - S} = 0, % where A is the discretized intensity matrix that comes from the finite difference scheme and the reflecting barrier at x_min and x_max function [results] = optimal_stopping_diffusion(p, settings) t = p.t; x = p.x; N = length(t); I = length(x); %% Default settings if ~isfield(settings, 'print_level') settings.print_level = 0; end if ~isfield(settings, 'error_tolerance') settings.error_tolerance = 1e-12; end if ~isfield(settings, 'pivot_tolerance') settings.pivot_tolerance = 1e-8; end if ~isfield(settings, 'method') settings.method = 'yuval'; %Default is the Yuval LCP downloaded from matlabcentral end if ~isfield(settings, 'basis_guess') settings.basis_guess = zeros(I*N,1); %Guess that it never binds? end %% Unpack parameters and settings [t_grid, x_grid] = meshgrid(t, x); %Generates permutations (stacked by t first, as we want) could look at: [t_grid(:) x_grid(:)] state_permutations = [t_grid(:) x_grid(:)]; mu = bsxfun(p.mu, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. sigma_2 = bsxfun(p.sigma_2, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. S = bsxfun(p.S, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. u = bsxfun(p.u, state_permutations(:,1), state_permutations(:,2)); %applies binary function to these, and remains in the correct stacked order. %% Discretize the operator %TODO: Should be able to nest the time-varying and stationary ones in this, but can't right now. if(N > 1) A = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2); else A = discretize_univariate_diffusion(x, mu, sigma_2, false); end %% Setup and solve the problem as a linear-complementarity problem (LCP) %Given the above construction for u, A, and S, we now have the discretized version % min{rho v - u - A v, v - S} = 0, %Convert this to the LCP form (see http://www.princeton.edu/~moll/HACTproject/option_simple.pdf) % z >= 0 % Bz + q >= 0 % z'(Bz + q) = 0 % with the change of variables z = v - S B = p.rho * speye(I*N) - A; %(6) q = -u + B*S; %(8) %% Solve the LCP version of the model %Choose based on the method type. if strcmp(settings.method, 'yuval')%Uses Yuval Tassa's Newton-based LCP solver, download from http://www.mathworks.com/matlabcentral/fileexchange/20952 %Box bounds, z_L <= z <= z_U. In this formulation this means 0 <= z_i < infinity z_L = zeros(I*N,1); %(12) z_U = inf(I*N,1); settings.error_tolerance = settings.error_tolerance/1000; %Fundamentally different order of magnitude than the others. [z, iter, converged] = LCP(B, q, z_L, z_U, settings); error = z.*(B*z + q); %(11) elseif strcmp(settings.method, 'lemke') [z,err,iter] = lemke(B, q, settings.basis_guess,settings.error_tolerance, settings.pivot_tolerance); error = z.*(B*z + q); %(11) converged = (err == 0); elseif strcmp(settings.method, 'knitro') % Uses Knitro Tomlab as a MPEC solver c = zeros(I*N, 1); %i.e. no objective function to minimize. Only looking for feasibility. z_iv = zeros(I*N,1); %initial guess. %Box bounds, z_L <= z <= z_U. In this formulation this means 0 <= z_i < infinity z_L = zeros(I*N,1); %(12) z_U = inf(I*N,1); %B*z + q >= 0, b_L <= B*z <= b_U (i.e. -q_i <= (B*z)_i <= infinity) b_L = -q; b_U = inf(I*N,1); %Each row in mpec is a complementarity pair. Require only 2 non-zeros in each row. %In mpec, Columns 1:2 refer to variables, columns 3:4 to linear constraints, and 5:6 to nonlinear constraints: % mpec = [ var1,var2 , lin1,lin2 , non1,non2 ; ... ]; %So a [2 0 3 0 0 0] row would say "x_2 _|_ c_3" for the 3rd linear constrant, and c_3 := A(3,:) x num_complementarity_constraints = I*N; mpec = sparse(num_complementarity_constraints, 6); %The first row is the variable index, and the third is the row of the linear constraint matrix. mpec(:, 1) = (1:I*N)'; %So says x_i _|_ c_i for all i. mpec(:, 3) = (1:I*N)'; %Creates a LCP Prob = lcpAssign(c, z_L, z_U, z_iv, B, b_L, b_U, mpec, 'LCP Problem'); %Add a few settings. Knitro is the only MPEC solver in TOMLAB Prob.PriLevOpt = settings.print_level; Prob.KNITRO.options.MAXIT = settings.max_iter; if ~isfield(settings, 'knitro_ALG') Prob.KNITRO.options.ALG = 3; %Knitro Algorithm. 0 is auto, 3 is SLQP else Prob.KNITRO.options.ALG = settings.knitro_ALG; end Prob.KNITRO.options.BLASOPTION = 0; %Can use blas/mkl... might be more useful for large problems. Prob.KNITRO.options.FEASTOL = settings.error_tolerance; %Feasibility tolerance on linear constraints. % Solve the LP (with MPEC pairs) using KNITRO: Result = tomRun('knitro',Prob); z = Result.x_k(1:I*N); %Strips out the slack variables automatically added by the MPEC error = z.*(B*z + q); %(11) converged = (Result.ExitFlag == 0); iter = Result.Iter; else results = NaN; assert(false, 'Unsupported method to solve the LCP'); end %% Package Results %% Convert from z back to v v = z + S; %(7) calculate value function, unravelling the "z = v - S" change of variables %Discretization results results.x = x; results.A = A; results.S = S; %Solution results.v = v; results.converged = converged; results.iterations = iter; results.LCP_error = max(abs(error)); results.LCP_L2_error = norm(error,2); end
github
jlperla/continuous_time_methods-master
simple_joint_HJBE_stationary_distribution_univariate.m
.m
continuous_time_methods-master/matlab/lib/simple_joint_HJBE_stationary_distribution_univariate.m
2,898
utf_8
16afd41183f79902c52da542e96c6872
%Takes the discretized operator A, the grid x, and finds the stationary distribution f. function [v, f, success] = simple_joint_HJBE_stationary_distribution_univariate(A, x, u, rho, settings) I = length(x); if nargin < 5 settings.default = true; %Just creates as required. end if(~isfield(settings, 'normalization')) settings.normalization = 'sum'; %The only method supported right now is a direct sum %Otherwise, could consider better quadrature methods using x such as trapezoidal or simpsons rule. end if ~isfield(settings, 'print_level') settings.print_level = false; end if(isfield(settings, 'max_iterations')) %OTherwise use the default max_iterations = settings.max_iterations; %Number of iterations else max_iterations = 10*I; %The default is too small for our needs end if(isfield(settings, 'tolerance')) %OTherwise use the default tolerance = settings.tolerance; %Number of iterations else tolerance = []; %Empty tells it to use default end if(~isfield(settings, 'preconditioner')) settings.preconditioner = 'none'; %Default is no preconditioner. end if(~isfield(settings, 'sparse')) settings.sparse = true; end if(isfield(settings, 'initial_guess')) initial_guess = settings.initial_guess; else initial_guess = []; end %Create the joint system y = sparse([u; sparse(I,1); 1]); %(66) X = [(rho * eye(I) - A) sparse(I,I); sparse(I,I) A'; sparse(1,I) ones(1,I)]; %(67). Only supporting simple sum. if(settings.sparse == true) if(strcmp(settings.preconditioner,'jacobi')) preconditioner = diag(diag(X)); %Jacobi preconditioner is easy to calculate. Helps a little elseif(strcmp(settings.preconditioner,'incomplete_LU')) %Matter if it is negative or positive? [L,U] = ilu(X(1:end-1,:)) preconditioner = L; elseif(strcmp(settings.preconditioner,'none')) preconditioner = []; else assert(false, 'unsupported preconditioner'); end [val,flag,relres,iter] = lsqr(X, y, tolerance, max_iterations, preconditioner, [], initial_guess); %Linear least squares. Note tolerance changes with I if(flag==0) success = true; %Extracts the solution. v = val(1:I); f = val(I+1:end); else if(settings.print_level>0) disp('Failure to converge: flag and residual'); [flag, relres] end success = false; f = NaN; v = NaN; end else %Otherwise solve as a dense system val = full(X) \ full(y); v = val(1:I); f = val(I+1:end); success = true; end end
github
jlperla/continuous_time_methods-master
simple_optimal_stopping_diffusion.m
.m
continuous_time_methods-master/matlab/lib/simple_optimal_stopping_diffusion.m
6,496
utf_8
e46fcf40131efca018a2a0f4ee6ef1ae
% Modification of Ben Moll's: http://www.princeton.edu/~moll/HACTproject/option_simple_LCP.m % See notes and equation numbers in 'optimal_stopping.pdf' % Solves the HJB variational inequality that comes from a general diffusion process with optimal stopping. % min{rho v(x) - u(x) - mu(x)v'(x) - sigma(x)^2/2 v''(x), v(x) - S(x)} = 0 % with a reflecting boundary at a x_min and x_max % unless S is very small, and u(x) is very large (i.e. no stopping), the reflecting boundary at x_min is unlikely to enter the solution % for a large x_min, it is unlikely to affect the stopping point. % Does so by using finite differences to discretize into the following complementarity problem: % min{rho v - u - A v, v - S} = 0, % where A is the discretized intensity matrix that comes from the finite difference scheme and the reflecting barrier at x_min and x_max function [results] = simple_optimal_stopping_diffusion(p, settings) %% Default settings if ~isfield(settings, 'print_level') settings.print_level = 0; end if ~isfield(settings, 'error_tolerance') settings.error_tolerance = 1e-12; end if ~isfield(settings, 'pivot_tolerance') settings.pivot_tolerance = 1e-8; end if ~isfield(settings, 'method') settings.method = 'yuval'; %Default is the Yuval LCP downloaded from matlabcentral end if ~isfield(settings, 'basis_guess') settings.basis_guess = zeros(settings.I,1); %Guess that it never binds? end %% Unpack parameters and settings rho = p.rho; %Discount rate u_x = p.u_x; %utility function mu_x = p.mu_x; %Drift function sigma_2_x = p.sigma_2_x; %diffusion term sigma(x)^2 S_x = p.S_x; %payoff function on exit. x_min = p.x_min; %Not just a setting as a boundary value occurs here x_max = p.x_max; %Not just a setting as a boundary value occurs here. %Settings for the solution method I = settings.I; %number of grid variables for x %Create uniform grid and determine step sizes. x = linspace(x_min, x_max, I)'; %% Discretize the operator %This is for generic diffusion functions with mu_x = mu(x) and sigma_x = sigma(x) mu = mu_x(x); %vector of constant drifts sigma_2 = sigma_2_x(x); % %Discretize the operator Delta = x(2) - x(1); A = discretize_univariate_diffusion(x, mu, sigma_2, false); %Note that this is not checking for absorbing states! %% Setup and solve the problem as a linear-complementarity problem (LCP) %Given the above construction for u, A, and S, we now have the discretized version % min{rho v - u - A v, v - S} = 0, %Convert this to the LCP form (see http://www.princeton.edu/~moll/HACTproject/option_simple.pdf) % z >= 0 % Bz + q >= 0 % z'(Bz + q) = 0 % with the change of variables z = v - S u = u_x(x); S = S_x(x); B = rho * speye(I) - A; %(6) q = -u + B*S; %(8) %% Solve the LCP version of the model %Choose based on the method type. if strcmp(settings.method, 'yuval')%Uses Yuval Tassa's Newton-based LCP solver, download from http://www.mathworks.com/matlabcentral/fileexchange/20952 %Box bounds, z_L <= z <= z_U. In this formulation this means 0 <= z_i < infinity z_L = zeros(I,1); %(12) z_U = inf(I,1); settings.error_tolerance = settings.error_tolerance/1000; %Fundamentally different order of magnitude than the others. [z, iter, converged] = LCP(B, q, z_L, z_U, settings); error = z.*(B*z + q); %(11) elseif strcmp(settings.method, 'lemke') [z,err,iter] = lemke(B, q, settings.basis_guess,settings.error_tolerance, settings.pivot_tolerance); error = z.*(B*z + q); %(11) converged = (err == 0); elseif strcmp(settings.method, 'knitro') % Uses Knitro Tomlab as a MPEC solver c = zeros(I, 1); %i.e. no objective function to minimize. Only looking for feasibility. z_iv = zeros(I,1); %initial guess. %Box bounds, z_L <= z <= z_U. In this formulation this means 0 <= z_i < infinity z_L = zeros(I,1); %(12) z_U = inf(I,1); %B*z + q >= 0, b_L <= B*z <= b_U (i.e. -q_i <= (B*z)_i <= infinity) b_L = -q; b_U = inf(I,1); %Each row in mpec is a complementarity pair. Require only 2 non-zeros in each row. %In mpec, Columns 1:2 refer to variables, columns 3:4 to linear constraints, and 5:6 to nonlinear constraints: % mpec = [ var1,var2 , lin1,lin2 , non1,non2 ; ... ]; %So a [2 0 3 0 0 0] row would say "x_2 _|_ c_3" for the 3rd linear constrant, and c_3 := A(3,:) x num_complementarity_constraints = I; mpec = sparse(num_complementarity_constraints, 6); %The first row is the variable index, and the third is the row of the linear constraint matrix. mpec(:, 1) = (1:I)'; %So says x_i _|_ c_i for all i. mpec(:, 3) = (1:I)'; %Creates a LCP Prob = lcpAssign(c, z_L, z_U, z_iv, B, b_L, b_U, mpec, 'LCP Problem'); %Add a few settings. Knitro is the only MPEC solver in TOMLAB Prob.PriLevOpt = settings.print_level; Prob.KNITRO.options.MAXIT = settings.max_iter; if ~isfield(settings, 'knitro_ALG') Prob.KNITRO.options.ALG = 3; %Knitro Algorithm. 0 is auto, 3 is SLQP else Prob.KNITRO.options.ALG = settings.knitro_ALG; end Prob.KNITRO.options.BLASOPTION = 0; %Can use blas/mkl... might be more useful for large problems. Prob.KNITRO.options.FEASTOL = settings.error_tolerance; %Feasibility tolerance on linear constraints. % Solve the LP (with MPEC pairs) using KNITRO: Result = tomRun('knitro',Prob); z = Result.x_k(1:I); %Strips out the slack variables automatically added by the MPEC error = z.*(B*z + q); %(11) converged = (Result.ExitFlag == 0); iter = Result.Iter; else results = NaN; assert(false, 'Unsupported method to solve the LCP'); end %% Package Results %% Convert from z back to v v = z + S; %(7) calculate value function, unravelling the "z = v - S" change of variables %Discretization results results.x = x; results.A = A; results.S = S; %Solution results.v = v; results.converged = converged; results.iterations = iter; results.LCP_error = max(abs(error)); results.LCP_L2_error = norm(error,2); end
github
jlperla/continuous_time_methods-master
discretize_univariate_diffusion.m
.m
continuous_time_methods-master/matlab/lib/discretize_univariate_diffusion.m
4,082
utf_8
03ba4ed2a62e7d0f59f353bce684430e
% Modification of Ben Moll's: http://www.princeton.edu/~moll/HACTproject/option_simple_LCP.m %For algebra and equation numbers, see the 'operator_discretization_finite_differences.pdf' %This function takes a grid on [x_min, x_max] and discretizing a general diffusion defined by the following SDE %d x_t = mu(x_t)dt + sigma(x_t)^2 dW_t %Subject to reflecting barrier at x_min and x_max %Pass in the vector of the grid x, and the vectors of mu and sigma_2 at the nodes, and returns a sparse discretized operator. function [A, Delta_p, Delta_m] = discretize_univariate_diffusion(x, mu, sigma_2, check_absorbing_states) if nargin < 4 check_absorbing_states = true; end I = length(x); %number of grid variables for x %Check if the grid is uniform tol = 1E-10; %Tolerance for seeing if the grid is uniform Delta_p = [diff(x)' (x(I)-x(I-1))]'; %(35) Find distances between grid points. Delta_m = [x(2)-x(1) diff(x)']'; % %(34) \Delta_{i, -} if(check_absorbing_states) %In some circumstances, such as in optimal stopping problems, we can ignore these issues. assert(sigma_2(1) > 0 || mu(1) >= 0, 'Cannot jointly have both sigma = 0 or mu < 0 at x_min, or an absorbing state'); assert(sigma_2(end) > 0 || mu(end) <= 0, 'Cannot jointly have both sigma = 0 or mu > 0 at x_max, or an absorbing state'); end if(abs(min(Delta_p) - max(Delta_p)) < tol) %i.e. a uniform grid within tolerance Delta = x(2)-x(1); % (1) Delta_2 = Delta^2; %Just squaring the Delta for the second order terms in the finite differences. %% Construct sparse A matrix with uniform grid mu_m = min(mu,0); %General notation of plus/minus. mu_p = max(mu,0); X = - mu_m/Delta + sigma_2/(2*Delta_2); % (7) Y = - mu_p/Delta + mu_m/Delta - sigma_2/Delta_2; % (8) Z = mu_p/Delta + sigma_2/(2*Delta_2); %(9) %Creates a tri-diagonal matrix. See the sparse matrix tricks documented below A = spdiags([[X(2:I); NaN] Y [NaN; Z(1:I - 1)]], [-1 0 1], I,I);% (10) interior is correct. Corners will require adjustment %Manually adjust the boundary values at the corners. A(1,1) = Y(1) + X(1); %Reflecting barrier, (10) and (5) A(I,I) = Y(I) + Z(I); %Reflecting barrier, (10) and (6) else %% Construct sparse A matrix with non-uniform gird %For non-uniform grid, \Delta_{i, +}=x_{i+1} - x_{i} and \Delta_{i, -}=x_{i} - x_{i-1} mu_m = min(mu,0); %General notation of plus/minus. mu_p = max(mu,0); X = - mu_m./Delta_m + sigma_2 ./(Delta_m.*(Delta_p + Delta_m)); %(31) Y = - mu_p./Delta_p + mu_m./Delta_m - sigma_2./(Delta_p .* Delta_m); % (32) Z = mu_p./Delta_p + sigma_2 ./ (Delta_p.*(Delta_p + Delta_m)); % (33) %Creates a tri-diagonal matrix. See the sparse matrix tricks documented below A = spdiags([[X(2:I); NaN] Y [NaN; Z(1:I - 1)]], [-1 0 1], I,I);% (36) interior is the same as one for uniform grid case. Corners will require adjustment %Manually adjust the boundary values at the corners. A(1,1) = Y(1) + X(1); %Reflecting barrier, top corner of (36) A(I,I) = Y(I) + Z(I); %Reflecting barrier, bottom corner of (36) end end %Sparse matrix trick: spdiags takes vector(s) and offset(s). It returns the vector(s) in sparse a diagonal matrix where the diagonal is offset by the other argument. %For example: % norm(spdiags([1;2;3], 0, 3, 3) - diag([1 2 3]), Inf) % on the true diagonal, offset 0. % norm(spdiags([2;3;9999], -1, 3, 3)- [0 0 0; 2 0 0; 0 3 0], Inf) %on the diagonal below. Note that the last element is skipped since only 2 points on off diagonal. % norm(spdiags([9999;2;3], 1, 3, 3)- [0 2 0; 0 0 3; 0 0 0], Inf) %on the diagonal above. Note that the first element is skipped since only 2 points on off diagonal. %Alternatively this can be done in a single operation to form a tridiagonal matrix by stacking up the arrays, where the 2nd argument is a list of the offsets to apply the columns to) %Can add them as sparse matrices. For example, the above code is equivalent to %A = spdiags(Y, 0, I, I) + spdiags(X(2:I),-1, I, I) + spdiags([0;Z(1:I-1)], 1, I, I);
github
jlperla/continuous_time_methods-master
discretize_time_varying_univariate_diffusion.m
.m
continuous_time_methods-master/matlab/lib/discretize_time_varying_univariate_diffusion.m
4,398
utf_8
fe952d4c7af49c5f6b9f9a12eb03f75c
%For algebra and equation numbers, see the 'operator_discretization_finite_differences.pdf' %This function takes a grid on [x_min, x_max], [t_min, t_max] and discretizing a general diffusion defined by the following SDE %d x_t = mu(t, x_t)dt + sigma(t, x_t)^2 dW_t %Subject to reflecting barrier at x_min and x_max and a stationary requirement at t_max %Pass in the vector of the grid x, and the vectors of mu and sigma_2 at the nodes, and returns a sparse discretized operator. %The mu and sigma_2 are assumed to be already stacked correctly (i.e., keeping all time together). %This so far is the explicit time procedure (Nov.26) function [A, Delta_p, Delta_m, h_p, h_m] = discretize_time_varying_univariate_diffusion(t, x, mu, sigma_2) I = length(x); %number of grid variables for x N = length(t); %Could check if the grid is uniform Delta_p = [diff(x)' (x(I)-x(I-1))]'; %(35) Find distances between grid points. Delta_m = [x(2)-x(1) diff(x)']'; % %(34) \Delta_{i, -} h_p = [diff(t)' (t(N)-t(N-1))]'; % (67) h_{+} h_m = [t(2)-t(1) diff(t)']'; % %(68) h{i, -} % stack delta's into R^NI Delta_stack_p = repmat(Delta_p,N,1); Delta_stack_m = repmat(Delta_m,N,1); D_h_stack_p = kron(1./h_p(1:N), ones(I,1)); %Stacks up 1/h_+ for each spatial dimension. %% Construct sparse A matrix with non-uniform grid (uniform case is just a generalization of non-uniform) mu_m = min(mu,0); %General notation of plus/minus. mu_p = max(mu,0); X = - mu_m./Delta_stack_m + sigma_2 ./(Delta_stack_m.*(Delta_stack_p + Delta_stack_m)); %(74) Y = - mu_p./Delta_stack_p + mu_m./Delta_stack_m - sigma_2./(Delta_stack_p .* Delta_stack_m); % (75) Z = mu_p./Delta_stack_p + sigma_2 ./ (Delta_stack_p.*(Delta_stack_p + Delta_stack_m)); % (76) %Creating A using the spdiags banded matrix style bands = [X (Y - [D_h_stack_p(1:I*(N-1)); zeros(I,1)]) Z D_h_stack_p]; %Need to manually tweak the corners at every time period. If the boundary values for the stochastic process were to change could modify here. for n = 1:N %Implement the LHS boundary value for each n bands((n-1)*I + 1, 2) = bands((n-1)*I + 1, 2) + X((n-1)*I + 1); %i.e. Y+X in left corner for every t if n > 1 %Don't need to do this for the first corner because at corner of the banded matrix construction bands((n-1)*I + 1, 1) = 0; end %Implement the RHS boundary value for each n bands(n*I, 2) = bands(n*I, 2) + Z(n*I); %i.e. Z + Y in right corner for every t if n < N %Don't need to do this for the last corner bands(n*I, 3) = 0; end end %Make banded matrix. Tridiagonal with an additional term spaced I to the right of the main diagonal A = spdiags([[bands(2:end,1);nan(1,1)] bands(:,2) [nan(1,1); bands(1:end - 1,3)] [nan(I,1); bands(1:end - I,4)]],...%padding the bands as appropriate where spdiags ignores the data. nan helps catch errors [-1 0 1 I],... %location of the bands. Match to the number of nan in the preceding matrix, For negative bands off diagonal, spdiags ignores data at end, for positive it ignores data at beginning N*I, N*I); %size of resulting matrix end %Useful code for playing around with spdiags %To generate the matrix % [10 100 0 0; 2 20 200 0; 0 3 30 300; 0 0 4 40] %from the following: %testbands = [1 10 100; 2 20 200; 3 30 300; 4 40 400] %testA = full(spdiags([[testbands(2:end,1);NaN] testbands(:,2) [NaN; testbands(1:end-1,3)]], [-1 0 1], size(testbands, 1),size(testbands, 1))) % % Construct the A matrix in pieces % A = spdiags([nan(I,1); D_h_stack_p], [I], N*I, N*I); %Start with the off-diagonal of 1/h_p % for n=1:N % i_corner = I*(n-1)+1; % Xn = X(i_corner:i_corner+I-1); % Yn = Y(i_corner:i_corner+I-1); % Zn = Z(i_corner:i_corner+I-1); % A_n = spdiags([[Xn(2:I); NaN] Yn [NaN; Zn(1:I - 1)]], [-1 0 1], I,I);% (77) for each time node indexed by n, A_n is different as mu_n changes. The procedure similar to that in time-invariant case % A_n(1,1) = Yn(1) + Xn(1);%Reflecting barrier, top corner of (77) % A_n(I,I) = Yn(I) + Zn(I);%Reflecting barrier, bottom corner of (77) % A(i_corner:i_corner+I-1,i_corner:i_corner+I-1) = A_n; % end % A = A + spdiags(-[D_h_stack_p(1:I*(N-1)); zeros(I,1)], [0], N*I, N*I); %Putting 0's at the end
github
jlperla/continuous_time_methods-master
LCP.m
.m
continuous_time_methods-master/matlab/lib/LCP.m
5,203
utf_8
8fbbd2626f905e54a8c206b3570719e0
function [x, iter, converged] = LCP(M,q,l,u,settings) %LCP Solve the Linear Complementarity Problem. % % USAGE % x = LCP(M,q) solves the LCP % % x >= 0 % Mx + q >= 0 % x'(Mx + q) = 0 % % x = LCP(M,q,l,u) solves the generalized LCP (a.k.a MCP) % % l < x < u => Mx + q = 0 % x = u => Mx + q < 0 % l = x => Mx + q > 0 % % x = LCP(M,q,l,u,x0,display) allows the optional initial value 'x0' and % a binary flag 'display' which controls the display of iteration data. % % Parameters: % tol - Termination criterion. return when 0.5*phi(x)'*phi(x) < tol. % mu - Initial value of Levenberg-Marquardt mu coefficient. % mu_step - Coefficient by which mu is multiplied / divided. % mu_min - Value below which mu is set to zero (pure Gauss-Newton). % max_iter - Maximum number of (succesful) Levenberg-Marquardt steps. % b_tol - Tolerance of degenerate complementarity: Dimensions where % max( min(abs(x-l),abs(u-x)) , abs(phi(x)) ) < b_tol % are clamped to the nearest constraint and removed from % the linear system. % % ALGORITHM % This function implements the semismooth algorithm as described in [1], % with a least-squares minimization of the Fischer-Burmeister function using % a Levenberg-Marquardt trust-region scheme with mu-control as in [2]. % % [1] A. Fischer, A Newton-Type Method for Positive-Semidefinite Linear % Complementarity Problems, Journal of Optimization Theory and % Applications: Vol. 86, No. 3, pp. 585-608, 1995. % % [2] M. S. Bazarraa, H. D. Sherali, and C. M. Shetty, Nonlinear % Programming: Theory and Algorithms. John Wiley and Sons, 1993. % % Copyright (c) 2008, Yuval Tassa % tassa at alice dot huji dot ac dot il %tol = 1.0e-12; % mu = 1e-3; % mu_step = 5; % mu_min = 1e-5; % max_iter = 20; % b_tol = 1e-6; n = size(M,1); if nargin < 3 || isempty(l) l = zeros(n,1); if nargin < 4 || isempty(u) u = inf(n,1); end end if nargin < 5 settings.print_level = 0; end if ~isfield(settings, 'x_iv') settings.x_iv = min(max(zeros(n,1),l),u); %Changed to 0 as default, rather than 1. end if ~isfield(settings, 'error_tolerance') settings.error_tolerance = 1.0e-12; end if ~isfield(settings, 'lm_mu') settings.lm_mu = 1e-3; end if ~isfield(settings, 'lm_mu_min') settings.lm_mu_min = 1e-5; end if ~isfield(settings, 'lm_mu_step') settings.lm_mu_step = 5; end if ~isfield(settings, 'max_iter') settings.max_iter = 20; end if ~isfield(settings, 'b_tol') settings.b_tol = 1e-6; end %Unpack all settings and parameters display = (settings.print_level > 0); tol = settings.error_tolerance; mu = settings.lm_mu; mu_min = settings.lm_mu_min; mu_step = settings.lm_mu_step; max_iter = settings.max_iter; b_tol = settings.b_tol; %Main algorithm lu = [l u]; x = settings.x_iv; [psi,phi,J] = FB(x,q,M,l,u); new_x = true; warning off MATLAB:nearlySingularMatrix for iter = 1:max_iter if new_x [mlu,ilu] = min([abs(x-l),abs(u-x)],[],2); bad = max(abs(phi),mlu) < b_tol; psi = psi - 0.5*phi(bad)'*phi(bad); J = J(~bad,~bad); phi = phi(~bad); new_x = false; nx = x; nx(bad) = lu(find(bad)+(ilu(bad)-1)*n); end H = J'*J + mu*speye(sum(~bad)); Jphi = J'*phi; d = -H\Jphi; nx(~bad) = x(~bad) + d; [npsi,nphi,nJ] = FB(nx,q,M,l,u); r = (psi - npsi) / -(Jphi'*d + 0.5*d'*H*d); % actual reduction / expected reduction if r < 0.3 % small reduction, increase mu mu = max(mu*mu_step,mu_min); end if r > 0 % some reduction, accept nx x = nx; psi = npsi; phi = nphi; J = nJ; new_x = true; if r > 0.8 % large reduction, decrease mu mu = mu/mu_step * (mu > mu_min); end end if display disp(sprintf('iter = %2d, psi = %3.0e, r = %3.1f, mu = %3.0e',iter,psi,r,mu)); end if psi < tol break; end end warning on MATLAB:nearlySingularMatrix x = min(max(x,l),u); converged = (iter < max_iter); function [psi,phi,J] = FB(x,q,M,l,u) n = length(x); Zl = l >-inf & u==inf; Zu = l==-inf & u <inf; Zlu = l >-inf & u <inf; Zf = l==-inf & u==inf; a = x; b = M*x+q; a(Zl) = x(Zl)-l(Zl); a(Zu) = u(Zu)-x(Zu); b(Zu) = -b(Zu); if any(Zlu) nt = sum(Zlu); at = u(Zlu)-x(Zlu); bt = -b(Zlu); st = sqrt(at.^2 + bt.^2); a(Zlu) = x(Zlu)-l(Zlu); b(Zlu) = st -at -bt; end s = sqrt(a.^2 + b.^2); phi = s - a - b; phi(Zu) = -phi(Zu); phi(Zf) = -b(Zf); psi = 0.5*phi'*phi; if nargout == 3 if any(Zlu) M(Zlu,:) = -sparse(1:nt,find(Zlu),at./st-ones(nt,1),nt,n) - sparse(1:nt,1:nt,bt./st-ones(nt,1))*M(Zlu,:); end da = a./s-ones(n,1); db = b./s-ones(n,1); da(Zf) = 0; db(Zf) = -1; J = sparse(1:n,1:n,da) + sparse(1:n,1:n,db)*M; end
github
jlperla/continuous_time_methods-master
stationary_distribution_discretized_univariate.m
.m
continuous_time_methods-master/matlab/lib/stationary_distribution_discretized_univariate.m
5,544
utf_8
18fe7580476e59859ec139c501e32912
%Takes the discretized operator A, the grid x, and finds the stationary distribution f. function [f, success] = stationary_distribution_discretized_univariate(A, x, settings) I = length(x); if nargin < 3 settings.default = true; %Just creates as required. end %TODO: Consider adding in a 'dense' option for small matrices. if(~isfield(settings, 'method')) settings.method = 'eigenproblem_all'; end if(~isfield(settings, 'normalization')) settings.normalization = 'sum'; %The only method supported right now is a direct sum %Otherwise, could consider better quadrature methods using x such as trapezoidal or simpsons rule. end if ~isfield(settings, 'display') settings.display = false; %Tolerance end assert(I == size(A,1) && I == size(A,2)); %Make sure sizes match if(strcmp(settings.method, 'eigenproblem')) %Will use sparsity opts.isreal = true; if(isfield(settings, 'num_basis_vectors')) %Otherwise use the default opts.p = settings.num_basis_vectors; %Number of Lanczos basis vectors. Need to increase often end if(isfield(settings, 'max_iterations')) %OTherwise use the default opts.maxit = settings.max_iterations; %Number of iterations end [V, D, flag] = eigs(A',1,'sm', opts);%The eigenvalue with the smallest magnitude should be the zero eigenvalue if((flag ~= 0) || (abs(D - 0.0) > 1E-9)) %The 'sm' one is hopefully the zero, but maybe not if there are convergence issues. Also, the algorithm may simply not converge. if(settings.display) disp('The eigenvalue is not zero or did not converge. Try increasing the num_basis_vectors or max_iterations. Otherwise, consider eigenproblem_all'); end success = false; f = NaN; return; end f = V / sum(V); %normalize to sum to 1. Could add other normalizations using the grid 'x' depending on settings.normalization success = true; elseif(strcmp(settings.method, 'eigenproblem_all')) %Will use sparsity but computes all of the eigenvaluse/eigenvectors. Use if `eigenproblem' didn't work. opts.isreal = true; if(isfield(settings, 'num_basis_vectors')) %OTherwise use the default opts.p = settings.num_basis_vectors; %Number of Lanczos basis vectors. end if(isfield(settings, 'max_iterations')) %OTherwise use the default opts.maxit = settings.max_iterations; %Number of iterations end [V,D] = eigs(A', I, 'sm',opts); %Gets all of the eigenvalues and eigenvectors. Might be slow, so try `eigenproblem` first. zero_index = find(abs(diag(D) - 0) < 1E-9); if(isempty(zero_index)) if(settings.display) disp('Cannot find eigenvalue of 0.'); end success = false; f = NaN; return; end f = V(:,zero_index) / sum(V(:,zero_index)); %normalize to sum to 1. Could add other normalizations using the grid 'x' depending on settings.normalization success = true; elseif(strcmp(settings.method, 'LLS')) %Solves a linear least squares problem adding in the sum constraint if(isfield(settings, 'max_iterations')) %OTherwise use the default max_iterations = settings.max_iterations; %Number of iterations else max_iterations = 10*I; %The default is too small for our needs end if(isfield(settings, 'tolerance')) %OTherwise use the default tolerance = settings.tolerance; %Number of iterations else tolerance = []; %Empty tells it to use default end if(~isfield(settings, 'preconditioner')) settings.preconditioner = 'incomplete_LU'; %Default is incomplete_LU end if(strcmp(settings.preconditioner,'jacobi')) preconditioner = diag(diag(A)); %Jacobi preconditioner is easy to calculate. Helps a little elseif(strcmp(settings.preconditioner,'incomplete_cholesky')) %Matter if it is negative or positive? Possible this is doing it incorrectly. preconditioner =-ichol(-A, struct('type','ict','droptol',1e-3,'diagcomp',1));% ichol(A, struct('diagcomp', 10, 'type','nofill','droptol',1e-1)); %matlab formula exists elseif(strcmp(settings.preconditioner,'incomplete_LU')) %Matter if it is negative or positive? [L,U] = ilu(A); preconditioner = L; elseif(strcmp(settings.preconditioner,'none')) preconditioner = []; else assert(false, 'unsupported preconditioner'); end if(isfield(settings, 'initial_guess')) initial_guess = settings.initial_guess / sum(settings.initial_guess); %It normalized to 1 for simplicity. else initial_guess = []; end Delta = x(2) - x(1); [f,flag,relres,iter] = lsqr([A';ones(1,I)], sparse([zeros(I,1);1]), tolerance, max_iterations, preconditioner, [], initial_guess); %Linear least squares. Note tolerance changes with I if(flag==0) success = true; else if(settings.display) disp('Failure to converge: flag and residual'); [flag, relres] end success = false; f = NaN; end end end
github
jlperla/continuous_time_methods-master
simple_HJBE_discretized_univariate.m
.m
continuous_time_methods-master/matlab/lib/simple_HJBE_discretized_univariate.m
761
utf_8
78aad7cc10394b8df25366a34a51a53b
%Takes the discretized operator A, the grid x, and finds the stationary distribution f. function [v, success] = simple_HJBE_discretized_univariate(A, x, u, rho, settings) I = length(x); assert(I == size(A,1) && I == size(A,2)); %Make sure sizes match if nargin < 5 settings.default = true; %Just creates as required. end if(~isfield(settings, 'method')) settings.method = 'sparse_system'; end if ~isfield(settings, 'print_level') settings.print_level = 0; end if(strcmp(settings.method, 'sparse_system')) %Solve as a simple sparse system of equations. %More advanced solvers could use preconditioners, etc. v = (rho * speye(I) - A) \ u; success = true; end end
github
BoianAlexandrov/HNMF-master
outputGreenNMF.m
.m
HNMF-master/outputGreenNMF.m
783
utf_8
b631997750825de4e8242d51f6dce3c4
%% Output of the simulations function [Sf, Comp, Dr, Det, Wf] = outputGreenNMF(max_number_of_sources, RECON, SILL_AVG, numT, nd, xD, t0, S) close all x = 1:1:max_number_of_sources; y1 = RECON; y2 = SILL_AVG; createfigureNS(x, y1, y2) [aic_values, aic_min, nopt] = AIC( RECON, SILL_AVG, numT, nd); name1 = sprintf('Results/Solution_4det_%dsources.mat',nopt); name2 = sprintf('Results/Solution_4det_%dsources.mat',nopt); load(name1) load(name2) [Sf, Comp, Dr, Det, Wf] = CompRes(Cent,Solution,t0,numT,S,xD); disp(' ') disp(['The number of estimated by GreenNMF sources = ' num2str(nopt)]); disp(' ') disp([ ' A ' 'x ' 'y ' 'u ' 'Dx ' 'Dy ']); disp(Solution)
github
hafezbazrafshan/LQR-OPF-master
checkPowerFlowsPerNode.m
.m
LQR-OPF-master/checkPowerFlowsPerNode.m
3,025
utf_8
66ea172afd1b9026da17bef296e26c0a
function [checkpf, checkEqs,realGen_check, reactiveGen_check, ... realLoad_check,reactiveLoad_check]... = checkPowerFlowsPerNode(VS,thetaS,pgS,qgS, pdS,qdS) % CHECKPOWERFLOWS Validates given power flow solution. % [checkpf,checkEqs,realGen_check,... % reactiveGen_check, realLoad_check,... % reactiveLoad_check] = checkPowerFlows(VS, thetaS, pgS, qgS, pdS, qdS ) % validates given power flow solution. This is a node by node % implementation. See checkPowerFlows for a vectorized implementation. % % Description of outputs: % 1. checkpf: is a scalar binary which equals 1 when all power flow % equations are satisfied with absolute accuracy 1e-3. % 2. checkEqs: is a vector of size(2*N,1), expressing the difference with zero % for any of the equations in CDC 2016 paper equations (2c)-(3b) % 3. realGen_check: is a vector of size(G,1), expressing the difference with % zero for equations (2c) % 4. reactiveGen_check: is a vector of size(G,1), expressing the difference % with zero for equations (2d) % 5. realLoad_check: is a vector of size(L,1), expressing the difference with % zero for equations (3a) % 6. reactiveLoad_check: is a vector of size(L,1), expressing the difference % with zero for equations (3d) % % Description of inputs: % 1. VS: the steady-state voltage magnitude power flow solution % 2. thetaS: the steady-state voltage phase power flow solution (in Radians) % 3. pgS: the generator real power set points set points and the calculated pg for slack bus % 4. qgS: the generator reactive power inputs % 5. pdS: the steady-state real power loads used to run the power flow % 6. qdS: the steady-state reactive power loads used to run the power flow % % See also checkPowerFlows % % Required modifications: % 1. Fix equation number references. global N G L node_set gen_set... load_set Ymat Gmat Bmat realGen_check=ones(G,1); reactiveGen_check=ones(G,1); % checking the first 2G equations % [manual equations (16a), (16b)] for ii=1:length(gen_set) idx=gen_set(ii); % network index realGen_check(ii)=+pdS(idx)- pgS(ii) +... VS(idx).*(Gmat(idx,:)*(VS.*cos(thetaS(idx)-thetaS))+Bmat(idx,:)*(VS.*sin(thetaS(idx)-thetaS))); reactiveGen_check(ii) =+qdS(idx)-qgS(ii) +... VS(idx).*(-Bmat(idx,:)*(VS.*cos(thetaS(idx)-thetaS))+Gmat(idx,:)*(VS.*sin(thetaS(idx)-thetaS))); end % checking the 2L equations for power flows % [manual (16c), (16d)] realLoad_check=ones(L,1); reactiveLoad_check=ones(L,1); for ii=1:length(load_set) idx=load_set(ii); % network index realLoad_check(ii)=pdS(idx)+... VS(idx).*(Gmat(idx,:)*(VS.*cos(thetaS(idx)-thetaS))+Bmat(idx,:)*(VS.*sin(thetaS(idx)-thetaS))); reactiveLoad_check(ii) =+qdS(idx) +... VS(idx).*(-Bmat(idx,:)*(VS.*cos(thetaS(idx)-thetaS))+Gmat(idx,:)*(VS.*sin(thetaS(idx)-thetaS))); end checkEqs=[realGen_check; reactiveGen_check; realLoad_check;reactiveLoad_check]; if sum(abs(checkEqs))<1e-3 disp('Power flow equations satisfied'); checkpf=1; else disp('Power flow equations NOT satisfied'); checkpf=0; end end
github
gctronic/e-puck-library-master
OpenEpuck.m
.m
e-puck-library-master/library/matlab/matlab files/OpenEpuck.m
553
utf_8
1374131feb92d077a351f85a5740e359
%! \brief Open the communication with the e-puck % \params port The port in wich the e-puck is paired to. % it must be a string like that "COM11" if e-puck is paired % on COM 11. %/ function OpenEpuck(port) global EpuckPort; EpuckPort = serial(port,'BaudRate', 115200,'inputBuffersize',4096,'OutputBufferSize',4096,'ByteOrder','littleendian'); try fopen(EpuckPort); catch % could not open the port, delete the global variable clear EpuckPort clear global EpuckPort; disp 'Error, Could not open serial port' return; end return
github
gctronic/e-puck-library-master
CloseEpuck.m
.m
e-puck-library-master/library/matlab/matlab files/CloseEpuck.m
153
utf_8
45c5daa80365a8c5266f36e3ba47573f
%! \brief Close the communication with the e-puck function CloseEpuck() global EpuckPort; fclose(EpuckPort); clear EpuckPort; clear global EpuckPort; end
github
gctronic/e-puck-library-master
two_complement.m
.m
e-puck-library-master/tool/ePic/two_complement.m
597
utf_8
824666e5ce11c268e2dcc8608edb553c
function value=two_complement(rawdata) if (mod(max(size(rawdata)),2) == 1) error('The data to be converted must be 16 bits and the vector does not contain pairs of numbers') end value=zeros(1,max(size(rawdata))/2); j=1; for i=1:2:max(size(rawdata)) if (bitget(rawdata(i+1),8)==1) % Negatif number -> two'complement value(j)=-(invert_bin(rawdata(i))+bitshift(invert_bin(rawdata(i+1)),8)+1); else value(j)=rawdata(i)+bitshift(rawdata(i+1),8); end j=j+1; end function value=invert_bin(value) for i=1:8 value=bitset(value,i,mod(bitget(value,i)+1,2)); end
github
gctronic/e-puck-library-master
controller_pos.m
.m
e-puck-library-master/tool/ePic/controller_pos.m
3,562
utf_8
f625e31e5b3d2b88fb870f79abb0c704
% controller_pos is an exemple controller. % --------------------------------------------- % It drives the epuck from the current position which is define as [0 0 0] % to a goal position which can be set by the user. % The control uses a smooth controller which drives the e-puck along % smooth curves from the current position to the goal position. function controller_pos() % This function is executed after the update data timer % global ePic object. Use get and set methods to access the different % fields and check if the required sensors are activated using the % updateDet methode. For more information about this different commands, % please read the help file. global ePic; global handles_save; persistent goal_position; % a global variable for the controller state global ControllerState; % 0 = controller halted, all other states are active transition or static states; % Controller states (content of ControllerState variable) % 0 = "controller off" state % 1 = transition to "controller on" state is in progress (initiated by user in main.m) % -1 = transition to "controller off" state is in progress (initiated by user in main.m) % -2 = means that the controller is in "suspend" state (automatically activated when control goal has been reached) % % all other states can be used freely in this function (e.g. to signify "controller on" state) % put your controller variable declarations here (if possible not declared % as "global" but as "persistent") persistent done; %-----------------------------------------------% % main code for the different controller states % %-----------------------------------------------% %-------------------------------------------------------------------------% % if controller is to be switched on, execute initialization code and go to % "on"-state if (ControllerState == 1) disp 'Controller has been switched on!'; ControllerState = 2; %----------------------------% % setup controller variables % %----------------------------% % activate required "sensors" ePic = activate(ePic,'speed'); ePic = activate(ePic,'pos'); ePic = activate(ePic,'odom'); % reset odometry ePic = set(ePic, 'odom' , [0 0 0]); % ----------- set goal position in m ----------- % [m m rad] goal_position = [-0.2 -0.3 .64]; done = 0; %-------------------------------------------------------------------------% % if controller is to be switched off, execute termination code and go to "off"-state elseif (ControllerState == -1) ePic = set(ePic,'speed',[0 0]); disp 'Controller has been switched off!'; ControllerState = 0; %-------------------------------------------------------------------------% % if controller is in suspend state elseif (ControllerState==-2) % don't do anything, and wait for user to switch controller off %-------------------------------------------------------------------------% % controller running, write your own code here elseif (ControllerState~=0) if (done == 0) % call GoTo function [dist, dangle] = controllersub_GoToFct(goal_position); [val,up] = get(ePic,'odom'); % comment this lines if you don't want to display the position graph figure(432); scatter([goal_position(1), val(1)], [goal_position(2), val(2)], 'b'); hold on; % check for limits if (dist < 0.005) done = 1; ePic = set(ePic,'speed',[0 0]); end else ControllerState = -2; % go to suspend state end end
github
gctronic/e-puck-library-master
main.m
.m
e-puck-library-master/tool/ePic/main.m
87,934
utf_8
6eeefa1ec55877edf2bdb3579b034718
function varargout = main(varargin) % MAIN M-file for main.fig % MAIN, by itself, creates a new MAIN or raises the existing % singleton*. % % H = MAIN returns the handle to a new MAIN or the handle to % the existing singleton*. % % MAIN('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MAIN.M with the given input arguments. % % MAIN('Property','Value',...) creates a new MAIN or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before main_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to main_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 % Copyright 2002-2003 The MathWorks, Inc. % Edit the above text to modify the response to help main % Last Modified by GUIDE v2.5 13-Nov-2008 11:29:53 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @main_OpeningFcn, ... 'gui_OutputFcn', @main_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 main is made visible. function main_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 main (see VARARGIN) % Choose default command line output for main handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes main wait for user response (see UIRESUME) % uiwait(handles.figure1); global ePic; % Creating ePic global object ePic = ePicKernel(); global ControllerState; % controller is off be default ControllerState = 0; global pathDatas; % path graph pathDatas = zeros(10000,2); global pathDatai; pathDatai = 1; global timer1_period; % update timer timer1_period=0.1; global timer1; global p_buffer; % pointer for value save circular buffer p_buffer = 0; global buff_size; buff_size = 1; global valuesSensors; valuesSensors = zeros(1,3); axes(handles.axes_path); scatter(0,0); % clear plot set(handles.axes_path,'XTick',[]); set(handles.axes_path,'XTickLabel',[]); set(handles.axes_path,'YTick',[]); set(handles.axes_path,'YTickLabel',[]); img = imread('epuck.tif'); axes(handles.axes_epuck); image(img); set(handles.axes_epuck,'XTick',[]); set(handles.axes_epuck,'XTickLabel',[]); set(handles.axes_epuck,'YTick',[]); set(handles.axes_epuck,'YTickLabel',[]); % timer 1 settings timer1 = timer('TimerFcn',@btm_timer1_Callback,'period',timer1_period); set(timer1,'ExecutionMode','fixedDelay'); set(timer1,'BusyMode','drop'); % Autodetect serial ports serialTmp = instrhwinfo('serial'); if (size(serialTmp.SerialPorts,1) > 0) set(handles.str_port,'String',serialTmp.SerialPorts); else set(handles.str_port,'String','no port detected'); end drawnow; % if epic is connected, disconnect ePic if (get(ePic,'connectionState') == 1) ePic = disconnect(ePic); end % --- Outputs from this function are returned to the command line. function varargout = main_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; % Initialse controls function ResetControls(handles) set(handles.ck_LED_1,'Value',0); set(handles.ck_LED_2,'Value',0); set(handles.ck_LED_3,'Value',0); set(handles.ck_LED_4,'Value',0); set(handles.ck_LED_5,'Value',0); set(handles.ck_LED_6,'Value',0); set(handles.ck_LED_7,'Value',0); set(handles.ck_LED_8,'Value',0); set(handles.ck_LED_B,'Value',0); set(handles.ck_LED_F,'Value',0); % --- Executes on button press in btmConnect. function btmConnect_Callback(hObject, eventdata, handles) % hObject handle to btmConnect (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; global timer1; % global variable for the timer global timer1_period; % global variable for the period of timer1 global handles_save; Sel_Sensor_Callback(hObject, eventdata, handles); % Initialise Sensor Selection set(handles.txt_err_timer,'Visible','off'); set(handles.txt_timer_stop,'Visible','off'); port = get(handles.str_port,'String'); if length(port) > 1 port = port{get(handles.str_port,'Value')}; end if (get(ePic,'connectionState') == 0) set(handles.btmConnect,'String','Connecting...'); set(handles.btmConnect,'Enable','off'); guidata(hObject, handles); drawnow(); % Open serial connection and init timer [ePic result] = connect(ePic, port); if (result == 1) set(handles.str_port,'Enable','off'); set(handles.btmConnect,'String','Disconnect'); ResetControls(handles); % create and start timer. Save handles for timer callback function handles_save = handles; timer1_period = str2num(get(handles.str_time,'String')); set(timer1,'period',timer1_period); start(timer1); else % Connection error msgbox('Connection error. Try an other port or switch the e-puck on'); set(handles.btmConnect,'String','Connect'); end set(handles.btmConnect,'Enable','on'); else set(handles.btmConnect,'String','Disconnecting...'); set(handles.btmConnect,'Enable','off'); guidata(hObject, handles); drawnow(); % Close serial connection and kill timer stop(timer1); [ePic result] = disconnect(ePic); if (result == 1) set(handles.str_port,'Enable','on'); set(handles.btmConnect,'String','Connect'); set(handles.btmConnect,'Enable','on'); end end set(handles.txt_err_timer,'Visible','off'); % --- Executes on button press in ck_LED_0. function ck_LED_0_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_0 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_0 global ePic; if ( get(handles.ck_LED_0,'Value')) ePic = set(ePic,'ledON', 0); else ePic = set(ePic,'ledOFF',0); end % --- Executes on button press in ck_LED_1. function ck_LED_1_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_1 global ePic; if ( get(handles.ck_LED_1,'Value')) ePic = set(ePic,'ledON', 1); else ePic = set(ePic,'ledOFF',1); end % --- Executes on button press in ck_LED_2. function ck_LED_2_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_2 global ePic; if ( get(handles.ck_LED_2,'Value')) ePic = set(ePic,'ledON', 2); else ePic = set(ePic,'ledOFF',2); end % --- Executes on button press in ck_LED_3. function ck_LED_3_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_3 global ePic; if ( get(handles.ck_LED_3,'Value')) ePic = set(ePic,'ledON', 3); else ePic = set(ePic,'ledOFF',3); end % --- Executes on button press in ck_LED_4. function ck_LED_4_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_4 global ePic; if ( get(handles.ck_LED_4,'Value')) ePic = set(ePic,'ledON', 4); else ePic = set(ePic,'ledOFF',4); end % --- Executes on button press in checkbox5. function ck_LED_5_Callback(hObject, eventdata, handles) % hObject handle to checkbox5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox5 global ePic; if ( get(handles.ck_LED_5,'Value')) ePic = set(ePic,'ledON', 5); else ePic = set(ePic,'ledOFF',5); end % --- Executes on button press in checkbox6. function ck_LED_6_Callback(hObject, eventdata, handles) % hObject handle to checkbox6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox6 global ePic; if ( get(handles.ck_LED_6,'Value')) ePic = set(ePic,'ledON', 6); else ePic = set(ePic,'ledOFF',6); end % --- Executes on button press in checkbox7. function ck_LED_7_Callback(hObject, eventdata, handles) % hObject handle to checkbox7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox7 global ePic; if ( get(handles.ck_LED_7,'Value')) ePic = set(ePic,'ledON', 7); else ePic = set(ePic,'ledOFF',7); end % --- Executes on button press in checkbox8. function ck_LED_8_Callback(hObject, eventdata, handles) % hObject handle to checkbox8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox8 global ePic; if ( get(handles.ck_LED_8,'Value')) ePic = set(ePic,'ledON', 10); set(handles.ck_LED_1,'Value',1); set(handles.ck_LED_2,'Value',1); set(handles.ck_LED_3,'Value',1); set(handles.ck_LED_4,'Value',1); set(handles.ck_LED_5,'Value',1); set(handles.ck_LED_6,'Value',1); set(handles.ck_LED_7,'Value',1); set(handles.ck_LED_B,'Value',1); set(handles.ck_LED_F,'Value',1); else ePic = set(ePic,'ledOFF',10); set(handles.ck_LED_1,'Value',0); set(handles.ck_LED_2,'Value',0); set(handles.ck_LED_3,'Value',0); set(handles.ck_LED_4,'Value',0); set(handles.ck_LED_5,'Value',0); set(handles.ck_LED_6,'Value',0); set(handles.ck_LED_7,'Value',0); set(handles.ck_LED_B,'Value',0); set(handles.ck_LED_F,'Value',0); end % --- Executes on button press in ck_LED_B. function ck_LED_B_Callback(hObject, eventdata, handles) % hObject handle to ck_LED_B (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_LED_B global ePic; if ( get(handles.ck_LED_B,'Value')) ePic = set(ePic,'ledON', 8); else ePic = set(ePic,'ledOFF',8); end % --- Executes on button press in checkbox10. function ck_LED_F_Callback(hObject, eventdata, handles) % hObject handle to checkbox10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of checkbox10 global ePic; if ( get(handles.ck_LED_F,'Value')) ePic = set(ePic,'ledON', 9); else ePic = set(ePic,'ledOFF',9); end % --- Executes on selection change in Sel_Sensor. function Sel_Sensor_Callback(hObject, eventdata, handles) % hObject handle to Sel_Sensor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns Sel_Sensor contents as cell array % contents{get(hObject,'Value')} returns selected item from Sel_Sensor global ePic; % disable update ePic = updateDef(ePic, 'external',0); set (handles.ck_autoAcc,'Value',0); % for sensor data saving buff_size_Callback(hObject, eventdata, handles); sel_value = get(handles.Sel_Sensor,'Value'); % show/hide led selection if (sel_value == 10) set(handles.uipanel_LEDSelect,'Visible','on'); else set(handles.uipanel_LEDSelect,'Visible','off'); end if (sel_value <=5) set (handles.ck_autoAcc,'Visible','off'); else set (handles.ck_autoAcc,'Visible','on'); end ePic = set(ePic, 'external', sel_value); % --- Executes during object creation, after setting all properties. function Sel_Sensor_CreateFcn(hObject, eventdata, handles) % hObject handle to Sel_Sensor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value1_Callback(hObject, eventdata, handles) % hObject handle to str_value1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value1 as text % str2double(get(hObject,'String')) returns contents of str_value1 as a double % --- Executes during object creation, after setting all properties. function str_value1_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value2_Callback(hObject, eventdata, handles) % hObject handle to str_value2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value2 as text % str2double(get(hObject,'String')) returns contents of str_value2 as a double % --- Executes during object creation, after setting all properties. function str_value2_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value3_Callback(hObject, eventdata, handles) % hObject handle to str_value3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value3 as text % str2double(get(hObject,'String')) returns contents of str_value3 as a double % --- Executes during object creation, after setting all properties. function str_value3_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ck_sensorLED_4. function ck_sensorLED_4_Callback(hObject, eventdata, handles) % hObject handle to ck_sensorLED_4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_sensorLED_4 % --- Executes on button press in ck_sensorLED_3. function ck_sensorLED_3_Callback(hObject, eventdata, handles) % hObject handle to ck_sensorLED_3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_sensorLED_3 % --- Executes on button press in ck_sensorLED_1. function ck_sensorLED_1_Callback(hObject, eventdata, handles) % hObject handle to ck_sensorLED_1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_sensorLED_1 % --- Executes on button press in ck_sensorLED_2. function ck_sensorLED_2_Callback(hObject, eventdata, handles) % hObject handle to ck_sensorLED_2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_sensorLED_2 % --- Executes on button press in ck_sensorLED_5. function ck_sensorLED_5_Callback(hObject, eventdata, handles) % hObject handle to ck_sensorLED_5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_sensorLED_5 % --- Executes on button press in btm_timer1. function btm_timer1_Callback(hObject, eventdata, handles) % hObject handle to btm_timer1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) tstart = tic; global ePic; global handles_save; global valuesSensors; % used for saving value to MATLAB workspace global p_buffer; global buff_size; global pathDatas; % used to plot path global pathDatai; global ControllerState; global timer1_period; ePic = update(ePic); % time step : read the requested values % Selected sensor selectedSensor = get(handles_save.Sel_Sensor,'Value'); selectedSensorValue = 0; [val, up] = get(ePic, 'accel'); % Accelerometers if (up >= 1) if (selectedSensor == 1) selectedSensorValue = val; end end [val, up] = get(ePic, 'proxi'); % Proximity sensors if (up >= 1) set(handles_save.str_prox1,'String',val(1)); set(handles_save.str_prox2,'String',val(2)); set(handles_save.str_prox3,'String',val(3)); set(handles_save.str_prox4,'String',val(4)); set(handles_save.str_prox5,'String',val(5)); set(handles_save.str_prox6,'String',val(6)); set(handles_save.str_prox7,'String',val(7)); set(handles_save.str_prox8,'String',val(8)); if (selectedSensor == 2) selectedSensorValue = val; end end [val, up] = get(ePic, 'micro'); % Microphones if (up >= 1) if (selectedSensor == 3) selectedSensorValue = val; end end [val, up] = get(ePic, 'light'); % Light sensors if (up >= 1) if (selectedSensor == 4) selectedSensorValue = val; end end [val, up] = get(ePic, 'speed'); % Motors speed if (up >= 1) set(handles_save.str_getLSpeed,'String',val(1)); set(handles_save.str_getRSpeed,'String',val(2)); end [val, up] = get(ePic, 'pos'); % Motors position if (up >= 1) set(handles_save.str_getLPos,'String',val(1)); set(handles_save.str_getRPos,'String',val(2)); end [val, up] = get(ePic, 'floor'); % Floor sensors if (up >= 1) if (selectedSensor == 5) selectedSensorValue = val; end end % External sensors -------------------------------- % Depend of the current selected sensor if (selectedSensor == 10) % five led IR sensor ledIR(1) = get(handles_save.ck_sensorLED_1,'Value'); ledIR(2) = get(handles_save.ck_sensorLED_2,'Value'); ledIR(3) = get(handles_save.ck_sensorLED_3,'Value'); ledIR(4) = get(handles_save.ck_sensorLED_4,'Value'); ledIR(5) = get(handles_save.ck_sensorLED_5,'Value'); ePic = set(ePic,'ledIR',ledIR); end if (selectedSensor > 6) % External sensor [val, up] = get(ePic, 'external'); if (up >= 1) if (selectedSensor == 13) selectedSensorValue = val(1); else selectedSensorValue = val; end end end % Display selected sensor value in the global field tmp_text = ''; for i=1:size(selectedSensorValue,2) tmp_text{i} = num2str(selectedSensorValue(i)); end set(handles_save.txt_sensor,'String',tmp_text); % Save values in global variable p_buffer = p_buffer + 1; if (buff_size>-1 && p_buffer>buff_size) set(handles_save.btm_SaveSensors,'BackgroundColor','g'); p_buffer = 1; end if (size(selectedSensorValue,2) ~= size(valuesSensors,2)) valuesSensors = zeros(buff_size,size(selectedSensorValue,2)); end valuesSensors(p_buffer,:) = selectedSensorValue; % Update odometry ----------------------------------------- ePic = updateOdometry(ePic); [val, up] = get(ePic,'odom'); if (up > 0) set(handles_save.txt_odoX,'String',num2str(100 * val(1))); set(handles_save.txt_odoY,'String',num2str(100 * val(2))); set(handles_save.txt_odoT,'String',num2str(val(3))); end % Graph e-puck path --------------------------------------- if (get(handles_save.ck_drawPath,'Value')==1) [val, up] = get(ePic,'odom'); if (up > 0) % Refresh path graph pathDatas(pathDatai,:) = val(1:2); pathDatai = pathDatai+1; if (pathDatai==10001) pathDatai = 1; end end end % Controller execution ------------------------------------ % (ControllerState==-1 means that switching off is in progress) if (((get(handles_save.ck_controller,'Value')==1) || (ControllerState==-1)) && (get(ePic,'connectionState') == 1)) tmp = get(handles_save.str_controller,'String'); tmp = tmp{get(handles_save.str_controller,'Value')}; try eval(strtok(tmp,'.')); catch set(handles_save.txt_timer_stop,'Visible','on'); set(handles_save.ck_controller,'Value',0); err =lasterror; assignin('base', 'ERROR_msg_controller',err); error_file = ''; for i=1:size(err.stack,1) error_file = sprintf('%sFile : %s \n Name : %s, Line : %d \n\n',error_file ,err.stack(i,1).file, err.stack(i,1).name, err.stack(i,1).line); end error_msg = sprintf('Error identifier : \n %s \n \n Error message : \n %s \n \n %s', err.identifier,err.message,error_file); msgbox(error_msg, 'Controller error','error'); end end % Check if timer is not too slow if (timer1_period<toc(tstart)) set(handles_save.txt_err_timer,'Visible','on'); end % --- Executes on button press in ck_autoAcc. function ck_autoAcc_Callback(hObject, eventdata, handles) % hObject handle to ck_autoAcc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_autoAcc % Refresh the sensor selection global ePic; if (status(ePic,'external') ~= 0) if get(handles.ck_autoAcc,'Value') == 0 ePic=updateDef(ePic,'external',-1); else ePic=updateDef(ePic,'external',1); end end % --- Executes during object creation, after setting all properties. function figure1_CreateFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes on button press in btm_stop. function btm_stop_Callback(hObject, eventdata, handles) % hObject handle to btm_stop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; ePic=set(ePic,'speed', [0 0]); function edit6_Callback(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit6 as text % str2double(get(hObject,'String')) returns contents of edit6 as a double % --- Executes during object creation, after setting all properties. function edit6_CreateFcn(hObject, eventdata, handles) % hObject handle to edit6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit7_Callback(hObject, eventdata, handles) % hObject handle to edit7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit7 as text % str2double(get(hObject,'String')) returns contents of edit7 as a double % --- Executes during object creation, after setting all properties. function edit7_CreateFcn(hObject, eventdata, handles) % hObject handle to edit7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit8_Callback(hObject, eventdata, handles) % hObject handle to edit8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit8 as text % str2double(get(hObject,'String')) returns contents of edit8 as a double % --- Executes during object creation, after setting all properties. function edit8_CreateFcn(hObject, eventdata, handles) % hObject handle to edit8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit9_Callback(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit9 as text % str2double(get(hObject,'String')) returns contents of edit9 as a double % --- Executes during object creation, after setting all properties. function edit9_CreateFcn(hObject, eventdata, handles) % hObject handle to edit9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_getLSpeed_Callback(hObject, eventdata, handles) % hObject handle to str_getLSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_getLSpeed as text % str2double(get(hObject,'String')) returns contents of str_getLSpeed as a double % --- Executes during object creation, after setting all properties. function str_getLSpeed_CreateFcn(hObject, eventdata, handles) % hObject handle to str_getLSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_getRSpeed_Callback(hObject, eventdata, handles) % hObject handle to str_getRSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_getRSpeed as text % str2double(get(hObject,'String')) returns contents of str_getRSpeed as a double % --- Executes during object creation, after setting all properties. function str_getRSpeed_CreateFcn(hObject, eventdata, handles) % hObject handle to str_getRSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_getLPos_Callback(hObject, eventdata, handles) % hObject handle to str_getLPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_getLPos as text % str2double(get(hObject,'String')) returns contents of str_getLPos as a double % --- Executes during object creation, after setting all properties. function str_getLPos_CreateFcn(hObject, eventdata, handles) % hObject handle to str_getLPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_getRPos_Callback(hObject, eventdata, handles) % hObject handle to str_getRPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_getRPos as text % str2double(get(hObject,'String')) returns contents of str_getRPos as a double % --- Executes during object creation, after setting all properties. function str_getRPos_CreateFcn(hObject, eventdata, handles) % hObject handle to str_getRPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ck_updateMotorS. function ck_updateMotorS_Callback(hObject, eventdata, handles) % hObject handle to ck_updateMotorS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_updateMotorS % --- Executes on button press in ck_updateMotorP. function ck_updateMotorP_Callback(hObject, eventdata, handles) % hObject handle to ck_updateMotorP (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_updateMotorP function str_setLSpeed_Callback(hObject, eventdata, handles) % hObject handle to str_setLSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_setLSpeed as text % str2double(get(hObject,'String')) returns contents of str_setLSpeed as a double % --- Executes during object creation, after setting all properties. function str_setLSpeed_CreateFcn(hObject, eventdata, handles) % hObject handle to str_setLSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_setRSpeed_Callback(hObject, eventdata, handles) % hObject handle to str_setRSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_setRSpeed as text % str2double(get(hObject,'String')) returns contents of str_setRSpeed as a double % --- Executes during object creation, after setting all properties. function str_setRSpeed_CreateFcn(hObject, eventdata, handles) % hObject handle to str_setRSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_setLPos_Callback(hObject, eventdata, handles) % hObject handle to str_setLPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_setLPos as text % str2double(get(hObject,'String')) returns contents of str_setLPos as a double % --- Executes during object creation, after setting all properties. function str_setLPos_CreateFcn(hObject, eventdata, handles) % hObject handle to str_setLPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_setRPos_Callback(hObject, eventdata, handles) % hObject handle to str_setRPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_setRPos as text % str2double(get(hObject,'String')) returns contents of str_setRPos as a double % --- Executes during object creation, after setting all properties. function str_setRPos_CreateFcn(hObject, eventdata, handles) % hObject handle to str_setRPos (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in btm_setMotorS. function btm_setMotorS_Callback(hObject, eventdata, handles) % hObject handle to btm_setMotorS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; ePic=set(ePic,'speed', [str2num(get(handles.str_setLSpeed,'String')) str2num(get(handles.str_setRSpeed,'String'))]); % --- Executes on button press in btm_setMotorP. function btm_setMotorP_Callback(hObject, eventdata, handles) % hObject handle to btm_setMotorP (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes during object creation, after setting all properties. function axes_joystick_CreateFcn(hObject, eventdata, handles) % hObject handle to axes_joystick (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: place code in OpeningFcn to populate axes_joystick %axes(handles.axes_joystick);axis off; % drawnow; % --- Executes on button press in btm_changeTime. function btm_changeTime_Callback(hObject, eventdata, handles) % hObject handle to btm_changeTime (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global timer1; global timer1_period; global ePic; % If connected to the e-puck : change the time between two data refresh if (get(ePic,'connectionState') == 1) stop (timer1); set(handles.txt_err_timer,'Visible','off'); timer1_period = str2num(get(handles.str_time,'String')); set(timer1,'TimerFcn',@btm_timer1_Callback,'Period',timer1_period); set(handles.txt_timer_stop,'Visible','off'); set(handles.txt_err_timer,'Visible','off'); start(timer1); end function str_time_Callback(hObject, eventdata, handles) % hObject handle to str_time (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_time as text % str2double(get(hObject,'String')) returns contents of str_time as a double % --- Executes during object creation, after setting all properties. function str_time_CreateFcn(hObject, eventdata, handles) % hObject handle to str_time (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ck_controller. function ck_controller_Callback(hObject, eventdata, handles) % hObject handle to ck_controller (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ControllerState; global ePic; if (get(ePic,'connectionState') == 1) % Hint: get(hObject,'Value') returns toggle state of ck_controller if (get(hObject,'Value')==1) ControllerState = 1; % go to controller initialization state else ControllerState = -1; % go to controller deinitialization state end else set(hObject,'Value',1-get(hObject,'Value')); end set(handles.txt_timer_stop,'Visible','off'); function str_controller_Callback(hObject, eventdata, handles) % hObject handle to str_controller (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_controller as text % str2double(get(hObject,'String')) returns contents of str_controller as a double % --- Executes during object creation, after setting all properties. function str_controller_CreateFcn(hObject, eventdata, handles) % hObject handle to str_controller (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on mouse press over axes background. function axes_joystick_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to axes_joystick (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; vect=get(handles.axes_joystick,'CurrentPoint'); side = vect(1,1); speed = 1000 * vect(1,2); if (side > 0) vl = speed; vr = speed- side*speed; else vl = speed + side*speed; vr = speed; end set(handles.str_setLSpeed,'String',round(vl)); set(handles.str_setRSpeed,'String',round(vr)); ePic=set(ePic,'speed', [str2num(get(handles.str_setLSpeed,'String')) str2num(get(handles.str_setRSpeed,'String'))]); function str_prox8_Callback(hObject, eventdata, handles) % hObject handle to str_prox8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox8 as text % str2double(get(hObject,'String')) returns contents of str_prox8 as a double % --- Executes during object creation, after setting all properties. function str_prox8_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox7_Callback(hObject, eventdata, handles) % hObject handle to str_prox7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox7 as text % str2double(get(hObject,'String')) returns contents of str_prox7 as a double % --- Executes during object creation, after setting all properties. function str_prox7_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox6_Callback(hObject, eventdata, handles) % hObject handle to str_prox6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox6 as text % str2double(get(hObject,'String')) returns contents of str_prox6 as a double % --- Executes during object creation, after setting all properties. function str_prox6_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox5_Callback(hObject, eventdata, handles) % hObject handle to str_prox5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox5 as text % str2double(get(hObject,'String')) returns contents of str_prox5 as a double % --- Executes during object creation, after setting all properties. function str_prox5_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox1_Callback(hObject, eventdata, handles) % hObject handle to str_prox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox1 as text % str2double(get(hObject,'String')) returns contents of str_prox1 as a double % --- Executes during object creation, after setting all properties. function str_prox1_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox2_Callback(hObject, eventdata, handles) % hObject handle to str_prox2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox2 as text % str2double(get(hObject,'String')) returns contents of str_prox2 as a double % --- Executes during object creation, after setting all properties. function str_prox2_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox3_Callback(hObject, eventdata, handles) % hObject handle to str_prox3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox3 as text % str2double(get(hObject,'String')) returns contents of str_prox3 as a double % --- Executes during object creation, after setting all properties. function str_prox3_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_prox4_Callback(hObject, eventdata, handles) % hObject handle to str_prox4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_prox4 as text % str2double(get(hObject,'String')) returns contents of str_prox4 as a double % --- Executes during object creation, after setting all properties. function str_prox4_CreateFcn(hObject, eventdata, handles) % hObject handle to str_prox4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value4_Callback(hObject, eventdata, handles) % hObject handle to str_value4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value4 as text % str2double(get(hObject,'String')) returns contents of str_value4 as a double % --- Executes during object creation, after setting all properties. function str_value4_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value5_Callback(hObject, eventdata, handles) % hObject handle to str_value5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value5 as text % str2double(get(hObject,'String')) returns contents of str_value5 as a double % --- Executes during object creation, after setting all properties. function str_value5_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value5 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value6_Callback(hObject, eventdata, handles) % hObject handle to str_value6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value6 as text % str2double(get(hObject,'String')) returns contents of str_value6 as a double % --- Executes during object creation, after setting all properties. function str_value6_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value6 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value7_Callback(hObject, eventdata, handles) % hObject handle to str_value7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value7 as text % str2double(get(hObject,'String')) returns contents of str_value7 as a double % --- Executes during object creation, after setting all properties. function str_value7_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_value8_Callback(hObject, eventdata, handles) % hObject handle to str_value8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_value8 as text % str2double(get(hObject,'String')) returns contents of str_value8 as a double % --- Executes during object creation, after setting all properties. function str_value8_CreateFcn(hObject, eventdata, handles) % hObject handle to str_value8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in ck_updateProximity. function ck_updateProximity_Callback(hObject, eventdata, handles) % hObject handle to ck_updateProximity (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_updateProximity % --- Executes on button press in ck_autoSaveVal. function ck_autoSaveVal_Callback(hObject, eventdata, handles) % hObject handle to ck_autoSaveVal (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_autoSaveVal Sel_Sensor_Callback(hObject, eventdata, handles); % --- Executes on button press in btm_SaveSensors. function btm_SaveSensors_Callback(hObject, eventdata, handles) % hObject handle to btm_SaveSensors (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global valuesSensors; global p_buffer; global buff_size; persistent cpt; if isempty(cpt) cpt = 0; end if (buff_size>-1) if (size(valuesSensors,1)~=1 && p_buffer > 0) valuesSensors = [valuesSensors(p_buffer+1:buff_size,:); valuesSensors(1:p_buffer,:)]; end else valuesSensors = valuesSensors(1:p_buffer,:); end cpt = cpt + 1; tmp = sprintf('sensors_%03d',cpt); assignin('base', tmp,valuesSensors); % --- Executes during object creation, after setting all properties. function btmConnect_CreateFcn(hObject, eventdata, handles) % hObject handle to btmConnect (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes on button press in ck_drawPath. function ck_drawPath_Callback(hObject, eventdata, handles) % hObject handle to ck_drawPath (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of ck_drawPath % --- Executes on button press in btm_erase. function btm_erase_Callback(hObject, eventdata, handles) % hObject handle to btm_erase (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global pathDatas; global pathDatai; global ePic; pathDatas = zeros(10000,2); pathDatai = 1; ePic = reset(ePic,'odom'); setappdata(gcbf,'running',true); axes(handles.axes_path); scatter(0,0); % clear plot set(handles.axes_path,'XTick',[]); set(handles.axes_path,'XTickLabel',[]); set(handles.axes_path,'YTick',[]); set(handles.axes_path,'YTickLabel',[]); drawnow; % --- Executes during object creation, after setting all properties. function ck_drawPath_CreateFcn(hObject, eventdata, handles) % hObject handle to ck_drawPath (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called %btm_erase_Callback(); function str_width_Callback(hObject, eventdata, handles) % hObject handle to str_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_width as text % str2double(get(hObject,'String')) returns contents of str_width as a double % --- Executes during object creation, after setting all properties. function str_width_CreateFcn(hObject, eventdata, handles) % hObject handle to str_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sel_zoom_Callback(hObject, eventdata, handles) % hObject handle to sel_zoom (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of sel_zoom as text % str2double(get(hObject,'String')) returns contents of sel_zoom as a double % --- Executes during object creation, after setting all properties. function sel_zoom_CreateFcn(hObject, eventdata, handles) % hObject handle to sel_zoom (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function str_heigth_Callback(hObject, eventdata, handles) % hObject handle to str_heigth (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_heigth as text % str2double(get(hObject,'String')) returns contents of str_heigth as a double % --- Executes during object creation, after setting all properties. function str_heigth_CreateFcn(hObject, eventdata, handles) % hObject handle to str_heigth (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in radiobutton2. function radiobutton2_Callback(hObject, eventdata, handles) % hObject handle to radiobutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton2 % --- Executes on button press in radiobutton3. function radiobutton3_Callback(hObject, eventdata, handles) % hObject handle to radiobutton3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton3 % --- Executes on button press in btm_Capture. function btm_Capture_Callback(hObject, eventdata, handles) % hObject handle to btm_Capture (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global timer1; global ePic; % transfert the picture stop (timer1); ePic = updateDef(ePic,'image',2); ePic = updateImage(ePic); imagedata = get(ePic,'image'); start(timer1); % display image 1 setappdata(gcbf,'running',true); axes(handles.axes_picture1); image(imagedata); set(handles.axes_picture1,'XTick',[]); set(handles.axes_picture1,'XTickLabel',[]); set(handles.axes_picture1,'YTick',[]); set(handles.axes_picture1,'YTickLabel',[]); % display image 2 imagedata2 = filter_image2(imagedata); axes(handles.axes_picture2); image(imagedata2); set(handles.axes_picture2,'XTick',[]); set(handles.axes_picture2,'XTickLabel',[]); set(handles.axes_picture2,'YTick',[]); set(handles.axes_picture2,'YTickLabel',[]); % Update drawnow; % --- Executes on button press in btm_setCamParam. function btm_setCamParam_Callback(hObject, eventdata, handles) % hObject handle to btm_setCamParam (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; heigth = str2num(get(handles.str_heigth,'String')); width = str2num(get(handles.str_width,'String')); if (heigth > 40) || (width > 40) button = questdlg('The maximum camera resolution is 40x40 pixels. If you choose to continue with higher resolution you should expect some bugs ;-).','Camera parameters update','Continue', 'Abort','Abort'); if (strcmp(button,'Abort')) return; end end switch get(handles.sel_zoom,'Value') case 1 val_zoom = 1; case 2 val_zoom = 4; otherwise val_zoom = 8; end mode = get(handles.sel_imgmode,'Value')-1; ePic=set(ePic,'camMode', mode); ePic=set(ePic,'camSize', [width heigth]); ePic=set(ePic,'camZoom', val_zoom); function str_saveName_Callback(hObject, eventdata, handles) % hObject handle to str_saveName (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of str_saveName as text % str2double(get(hObject,'String')) returns contents of str_saveName as a double % --- Executes during object creation, after setting all properties. function str_saveName_CreateFcn(hObject, eventdata, handles) % hObject handle to str_saveName (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in sel_imgmode. function sel_imgmode_Callback(hObject, eventdata, handles) % hObject handle to sel_imgmode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns sel_imgmode contents as cell array % contents{get(hObject,'Value')} returns selected item from sel_imgmode % --- Executes during object creation, after setting all properties. function sel_imgmode_CreateFcn(hObject, eventdata, handles) % hObject handle to sel_imgmode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function axes_epuck_CreateFcn(hObject, eventdata, handles) % hObject handle to axes_epuck (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: place code in OpeningFcn to populate axes_epuck % --- Executes on mouse press over axes background. function axes_epuck_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to axes_epuck (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes when user attempts to close figure1. function figure1_CloseRequestFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: delete(hObject) closes the figure global ePic; global timer1; if (get(ePic,'connectionState') == 1) stop(timer1); delete(timer1); clear('timer1'); [ePic result] = disconnect(ePic); if (result == 1) set(handles.str_port,'Enable','on'); set(handles.btmConnect,'String','Connect'); set(handles.btmConnect,'Enable','on'); end end delete(hObject); % --- Executes on button press in btm_Refreshgraph. function btm_Refreshgraph_Callback(hObject, eventdata, handles) % hObject handle to btm_Refreshgraph (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global pathDatas; global timer1; % transfert the picture stop (timer1); setappdata(gcbf,'running',true); axes(handles.axes_path); scatter(pathDatas(:,1),pathDatas(:,2)); set(handles.axes_path,'XTick',[]); set(handles.axes_path,'XTickLabel',[]); set(handles.axes_path,'YTick',[]); set(handles.axes_path,'YTickLabel',[]); drawnow; start(timer1); % --- Executes on button press in btm_browsw. function btm_browsw_Callback(hObject, eventdata, handles) % hObject handle to btm_browsw (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) filename = uigetfile; if (filename == 0) else tmp_str = get(handles.str_controller,'String'); for i=1:9 tmp_str{11-i} = tmp_str{10-i}; end tmp_str{1} = filename; set(handles.str_controller,'String',tmp_str); end % --- Executes on button press in btm_add_com. function btm_add_com_Callback(hObject, eventdata, handles) % hObject handle to btm_add_com (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) answer = inputdlg('Please enter the com port to add. Format : COMx','Add a port'); if (size(answer,1) == 1) tmp = get(handles.str_port,'String'); if (length(tmp) > 1 ) for i=1:length(tmp) answer{i+1} = tmp{i}; end end set(handles.str_port,'String',answer); end % --- Executes on selection change in str_port. function str_port_Callback(hObject, eventdata, handles) % hObject handle to str_port (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns str_port contents as cell array % contents{get(hObject,'Value')} returns selected item from str_port % --- Executes during object creation, after setting all properties. function str_port_CreateFcn(hObject, eventdata, handles) % hObject handle to str_port (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function txt_sensor_Callback(hObject, eventdata, handles) % hObject handle to txt_sensor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of txt_sensor as text % str2double(get(hObject,'String')) returns contents of txt_sensor as a double % --- Executes during object creation, after setting all properties. function txt_sensor_CreateFcn(hObject, eventdata, handles) % hObject handle to txt_sensor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over txt_timer_stop. function txt_timer_stop_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to txt_timer_stop (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(hObject,'Visible','Off'); % --- Executes on selection change in buff_size. function buff_size_Callback(hObject, eventdata, handles) % hObject handle to buff_size (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns buff_size contents as cell array % contents{get(hObject,'Value')} returns selected item from buff_size global p_buffer; global buff_size; global valuesSensors; p_buffer = 0; tmp = get(handles.buff_size,'String'); val = get(handles.buff_size,'Value'); if (val~=10) if (val > 0) buff_size = str2num(tmp{val}); end valuesSensors = zeros(buff_size,3); set(handles.btm_SaveSensors,'BackgroundColor','r'); else buff_size=-1; valuesSensors=zeros(1000,3); set(handles.btm_SaveSensors,'BackgroundColor','g'); end % --- Executes during object creation, after setting all properties. function buff_size_CreateFcn(hObject, eventdata, handles) % hObject handle to buff_size (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in btm_buffer_state. function btm_buffer_state_Callback(hObject, eventdata, handles) % hObject handle to btm_buffer_state (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in btm_save_images. function btm_save_images_Callback(hObject, eventdata, handles) % hObject handle to btm_save_images (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; persistent cpt; if isempty(cpt) cpt = 0; end imagedata = get(ePic,'image'); imagedata2 = filter_image2(imagedata); cpt = cpt + 1; tmp1 = sprintf('image_%03d_org',cpt); tmp2 = sprintf('image_%03d_fil',cpt); assignin('base', tmp1,imagedata); assignin('base', tmp2,imagedata2); % --- Executes during object deletion, before destroying properties. function figure1_DeleteFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function txt_odoX_Callback(hObject, eventdata, handles) % hObject handle to txt_odoX (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of txt_odoX as text % str2double(get(hObject,'String')) returns contents of txt_odoX as a double % --- Executes during object creation, after setting all properties. function txt_odoX_CreateFcn(hObject, eventdata, handles) % hObject handle to txt_odoX (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function txt_odoY_Callback(hObject, eventdata, handles) % hObject handle to txt_odoY (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of txt_odoY as text % str2double(get(hObject,'String')) returns contents of txt_odoY as a double % --- Executes during object creation, after setting all properties. function txt_odoY_CreateFcn(hObject, eventdata, handles) % hObject handle to txt_odoY (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function txt_odoT_Callback(hObject, eventdata, handles) % hObject handle to txt_odoT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of txt_odoT as text % str2double(get(hObject,'String')) returns contents of txt_odoT as a double % --- Executes during object creation, after setting all properties. function txt_odoT_CreateFcn(hObject, eventdata, handles) % hObject handle to txt_odoT (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in btm_ode_reset. function btm_ode_reset_Callback(hObject, eventdata, handles) % hObject handle to btm_ode_reset (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; ePic = set(ePic,'odom',[0 0 0]); % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over txt_err_timer. function txt_err_timer_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to txt_err_timer (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(hObject,'Visible','Off'); % --- Executes on button press in btm_resetSensors. %function btm_resetSensors_Callback(hObject, eventdata, handles) % hObject handle to btm_resetSensors (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in btm_ResetSensors. function btm_ResetSensors_Callback(hObject, eventdata, handles) % hObject handle to btm_ResetSensors (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global valuesSensors; global p_buffer; global buff_size; p_buffer=0; if (buff_size>-1) valuesSensors=zeros(buff_size,size(valuesSensors,2)); set(handles.btm_SaveSensors,'BackgroundColor','r'); else valuesSensors=zeros(1000,size(valuesSensors,2)); set(handles.btm_SaveSensors,'BackgroundColor','g'); end % -------------------------------------------------------------------- function menu_Sensors_Callback(hObject, eventdata, handles) % hObject handle to menu_Sensors (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; % epuck accelerometers if (status(ePic,'accel') == 0) set(handles.menu_Accel,'Checked','off'); else set(handles.menu_Accel,'Checked','on'); end % epuck proximity sensors if (status(ePic,'proxi') == 0) set(handles.menu_Proximity,'Checked','off'); else set(handles.menu_Proximity,'Checked','on'); end % epuck light sensors if (status(ePic,'light') == 0) set(handles.menu_Light,'Checked','off'); else set(handles.menu_Light,'Checked','on'); end % epuck microphone if (status(ePic,'micro') == 0) set(handles.menu_Micro,'Checked','off'); else set(handles.menu_Micro,'Checked','on'); end % epuck motor speed if (status(ePic,'speed') == 0) set(handles.menu_MotorSpeed,'Checked','off'); else set(handles.menu_MotorSpeed,'Checked','on'); end % epuck encoder position if (status(ePic,'pos') == 0) set(handles.menu_Wheel,'Checked','off'); else set(handles.menu_Wheel,'Checked','on'); end % epuck odometry if (status(ePic,'odom') == 0) set(handles.menu_Odometry,'Checked','off'); else set(handles.menu_Odometry,'Checked','on'); end % epuck floor sensors if (status(ePic,'floor') == 0) set(handles.menu_floor,'Checked','off'); else set(handles.menu_floor,'Checked','on'); end % epuck external (turret) sensors if (status(ePic,'external') == 0) set(handles.menu_External,'Checked','off'); else set(handles.menu_External,'Checked','on'); end % -------------------------------------------------------------------- function menu_Accel_Callback(hObject, eventdata, handles) % hObject handle to menu_Accel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'accel') == 1) ePic=deactivate(ePic,'accel'); else ePic=activate(ePic,'accel'); end % -------------------------------------------------------------------- function menu_Proximity_Callback(hObject, eventdata, handles) % hObject handle to menu_Proximity (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'proxi') == 1) ePic=deactivate(ePic,'proxi'); else ePic=activate(ePic,'proxi'); end % -------------------------------------------------------------------- function menu_Light_Callback(hObject, eventdata, handles) % hObject handle to menu_Light (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'light') == 1) ePic=deactivate(ePic,'light'); else ePic=activate(ePic,'light'); end % -------------------------------------------------------------------- function menu_Micro_Callback(hObject, eventdata, handles) % hObject handle to menu_Micro (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'micro') == 1) ePic=deactivate(ePic,'micro'); else ePic=activate(ePic,'micro'); end % -------------------------------------------------------------------- function menu_MotorSpeed_Callback(hObject, eventdata, handles) % hObject handle to menu_MotorSpeed (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'speed') == 1) ePic=deactivate(ePic,'speed'); else ePic=activate(ePic,'speed'); end % -------------------------------------------------------------------- function menu_Wheel_Callback(hObject, eventdata, handles) % hObject handle to menu_Wheel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'pos') == 1) ePic=deactivate(ePic,'pos'); %We also deactivate odometry if there is no encoders ePic=deactivate(ePic,'odom'); else ePic=activate(ePic,'pos'); end % -------------------------------------------------------------------- function menu_Odometry_Callback(hObject, eventdata, handles) % hObject handle to menu_Odometry (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'odom') == 1) ePic=deactivate(ePic,'odom'); else ePic=activate(ePic,'odom'); % We want to activate encoders to use odometry ePic=activate(ePic,'pos'); end % -------------------------------------------------------------------- function menu_floor_Callback(hObject, eventdata, handles) % hObject handle to menu_floor (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'floor') == 1) ePic=deactivate(ePic,'floor'); else ePic=activate(ePic,'floor'); end % -------------------------------------------------------------------- function menu_External_Callback(hObject, eventdata, handles) % hObject handle to menu_External (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; if (status(ePic,'external') ~= 0) ePic=deactivate(ePic,'external'); else ePic=updateDef(ePic,'external',-1); end % --- Executes on button press in btm_edit_controller. function btm_edit_controller_Callback(hObject, eventdata, handles) % hObject handle to btm_edit_controller (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) tmp = get(handles.str_controller,'String'); tmp = tmp{get(handles.str_controller,'Value')}; tmp_str = sprintf('edit %s', tmp); eval(tmp_str); % -------------------------------------------------------------------- function workspace_Callback(hObject, eventdata, handles) % hObject handle to workspace (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function load_wsp_Callback(hObject, eventdata, handles) % hObject handle to load_wsp (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global ePic; filename = uigetfile('*.wsp','Select an ePic workspace file'); if (filename == 0) else % do sometings newData1 = importdata(filename); % Create new variables in the base workspace from those fields. vars = fieldnames(newData1); data = newData1.(vars{1}); names = newData1.(vars{2}); for i=1:length(data) switch str2mat(names(i)) % sensors case 's_accel' ePic = updateDef(ePic,'accel',data(i)); case 's_proxi' ePic = updateDef(ePic,'proxi',data(i)); case 's_light' ePic = updateDef(ePic,'light',data(i)); case 's_micro' ePic = updateDef(ePic,'micro',data(i)); case 's_speed' ePic = updateDef(ePic,'speed',data(i)); case 's_pos' ePic = updateDef(ePic,'pos',data(i)); case 's_odom' ePic = updateDef(ePic,'odom',data(i)); case 's_floor' ePic = updateDef(ePic,'floor',data(i)); case 's_external' ePic = updateDef(ePic,'external',data(i)); % other parameters case 'refreshtime' set (handles.str_time,'String', num2str(data(i))); btm_changeTime_Callback(hObject, eventdata, handles); otherwise end end msgbox('Workspace successfully loaded'); end % --- Executes on button press in btm_plot. function btm_plot_Callback(hObject, eventdata, handles) % hObject handle to btm_plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) global valuesSensors; global p_buffer; global buff_size; if (buff_size>-1) if (size(valuesSensors,1)~=1 && p_buffer > 0) valuesSensors = [valuesSensors(p_buffer+1:buff_size,:); valuesSensors(1:p_buffer,:)]; end else valuesSensors = valuesSensors(1:p_buffer,:); end figure; plot(valuesSensors); % -------------------------------------------------------------------- function menu_opendoc_Callback(hObject, eventdata, handles) % hObject handle to menu_opendoc (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) open 'Documentation\ePic2_doc.pdf';
github
gctronic/e-puck-library-master
two_complement.m
.m
e-puck-library-master/tool/ePic/@ePicKernel/private/two_complement.m
597
utf_8
824666e5ce11c268e2dcc8608edb553c
function value=two_complement(rawdata) if (mod(max(size(rawdata)),2) == 1) error('The data to be converted must be 16 bits and the vector does not contain pairs of numbers') end value=zeros(1,max(size(rawdata))/2); j=1; for i=1:2:max(size(rawdata)) if (bitget(rawdata(i+1),8)==1) % Negatif number -> two'complement value(j)=-(invert_bin(rawdata(i))+bitshift(invert_bin(rawdata(i+1)),8)+1); else value(j)=rawdata(i)+bitshift(rawdata(i+1),8); end j=j+1; end function value=invert_bin(value) for i=1:8 value=bitset(value,i,mod(bitget(value,i)+1,2)); end
github
jtomelin/caixeiro-viajante-algoritmo-genetico-master
cvfun.m
.m
caixeiro-viajante-algoritmo-genetico-master/cvfun.m
683
utf_8
4aed36af92ca49b1e057789977bf50fa
%Funcao de custo para o problema do caixeiro viajante function dist=cvfun(pop) % Utiliza variaveis globais "x" e "y" global x y [Npop,Ncidade]=size(pop); tour=[pop pop(:,1)]; % gera a matriz 20x21 da populacao onde a ultima % coluna eh a copia da primeira coluna (o agente deve voltar a cidade inicial) %distancia entre as cidades for i=1:Ncidade for j=1:Ncidade dcidade(i,j)=sqrt((x(i)-x(j))^2+(y(i)-y(j))^2); end % i end % j % custo de cada cromossomo for i=1:Npop dist(i,1)=0; for j=1:Ncidade % Soma das distancias para cada cromossomo dist(i,1)=dist(i)+dcidade(tour(i,j),tour(i,j+1)); end % j end % i end
github
aayush-k/Local-Feature-Matching-master
get_features.m
.m
Local-Feature-Matching-master/code/get_features.m
4,250
utf_8
072ff4a20bda044515a18de8bd55e28e
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays % Returns a set of feature descriptors for a given set of interest points. % 'image' can be grayscale or color, your choice. % 'x' and 'y' are nx1 vectors of x and y coordinates of interest points. % The local features should be centered at x and y. % 'feature_width', in pixels, is the local feature width. You can assume % that feature_width will be a multiple of 4 (i.e. every cell of your % local SIFT-like feature will have an integer width and height). % If you want to detect and describe features at multiple scales or % particular orientations you can add input arguments. % 'features' is the array of computed features. It should have the % following size: [length(x) x feature dimensionality] (e.g. 128 for % standard SIFT) function [features] = get_features(image, x, y, feature_width) features = []; binIntervals = -180:45:180; for ind = 1:length(x) xF = x(ind); yF = y(ind); siftDescriptor = []; [r, c] = size(image); left = max(1, round(xF - feature_width/2)); right = min(c, round(xF + feature_width/2 - 1)); top = max(1, round(yF - feature_width/2)); bottom = min(r, round(yF + feature_width/2 - 1)); subMat = image(top:bottom, left:right); [gradMag, gradDir] = imgradient(subMat); [rGradDir, cGradDir] = size(gradDir); for i = 1:4:feature_width for j = 1:4:feature_width % iterate through each 4x4 cell bins = zeros(1,8); for m = i:i+3 for n = j:j+3 if m < rGradDir && n < cGradDir direction = gradDir(m, n); binInd = find(histcounts(direction, binIntervals)); bins(binInd) = bins(binInd) + gradMag(m, n); end end end siftDescriptor = [siftDescriptor bins]; end end siftDescriptor = (siftDescriptor / norm(siftDescriptor)) .^ 0.5; features = [features reshape(siftDescriptor, [], 1)]; end % To start with, you might want to simply use normalized patches as your % local feature. This is very simple to code and works OK. However, to get % full credit you will need to implement the more effective SIFT descriptor % (See Szeliski 4.1.2 or the original publications at % http://www.cs.ubc.ca/~lowe/keypoints/) % Your implementation does not need to exactly match the SIFT reference. % Here are the key properties your (baseline) descriptor should have: % (1) a 4x4 grid of cells, each feature_width/4. 'cell' in this context % nothing to do with the Matlab data structue of cell(). It is simply % the terminology used in the feature literature to describe the spatial % bins where gradient distributions will be described. % (2) each cell should have a histogram of the local distribution of % gradients in 8 orientations. Appending these histograms together will % give you 4x4 x 8 = 128 dimensions. % (3) Each feature vector should be normalized to unit length % % You do not need to perform the interpolation in which each gradient % measurement contributes to multiple orientation bins in multiple cells % As described in Szeliski, a single gradient measurement creates a % weighted contribution to the 4 nearest cells and the 2 nearest % orientation bins within each cell, for 8 total contributions. This type % of interpolation probably will help, though. % You do not have to explicitly compute the gradient orientation at each % pixel (although you are free to do so). You can instead filter with % oriented filters (e.g. a filter that responds to edges with a specific % orientation). All of your SIFT-like feature can be constructed entirely % from filtering fairly quickly in this way. % You do not need to do the normalize -> threshold -> normalize again % operation as detailed in Szeliski and the SIFT paper. It can help, though. % Another simple trick which can help is to raise each element of the final % feature vector to some power that is less than one. end
github
aayush-k/Local-Feature-Matching-master
show_correspondence2.m
.m
Local-Feature-Matching-master/code/show_correspondence2.m
1,618
utf_8
d754a0a7f9f2ca2960dfea8e0518a162
% Automated Panorama Stitching stencil code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by Henry Hu <[email protected]> and James Hays % Visualizes corresponding points between two images. Corresponding points % will be matched by a line of random color. % This function provides another method of visualization. You can use % either this function or show_correspondence.m % You do not need to modify anything in this function, although you can if % you want to. function [ h ] = show_correspondence2(imgA, imgB, X1, Y1, X2, Y2) h = figure(3); Height = max(size(imgA,1),size(imgB,1)); Width = size(imgA,2)+size(imgB,2); numColors = size(imgA, 3); newImg = zeros(Height, Width,numColors); newImg(1:size(imgA,1),1:size(imgA,2),:) = imgA; newImg(1:size(imgB,1),1+size(imgA,2):end,:) = imgB; imshow(newImg, 'Border', 'tight') shiftX = size(imgA,2); hold on % set(h, 'Position', [100 100 900 700]) for i = 1:size(X1,1) cur_color = rand(3,1); plot([X1(i) shiftX+X2(i)],[Y1(i) Y2(i)],'*-','Color', cur_color, 'LineWidth',2) end hold off fprintf('Saving visualization to vis.jpg\n') visualization_image = frame2im(getframe(h)); % getframe() is unreliable. Depending on the rendering settings, it will % grab foreground windows instead of the figure in question. It could also % return an image that is not 800x600 if the figure is resized or partially % off screen. % try % %trying to crop some of the unnecessary boundary off the image % visualization_image = visualization_image(81:end-80, 51:end-50,:); % catch % ; % end imwrite(visualization_image, 'vis_arrows.jpg', 'quality', 100)
github
aayush-k/Local-Feature-Matching-master
show_correspondence.m
.m
Local-Feature-Matching-master/code/show_correspondence.m
2,215
utf_8
2d4943c5a3ff072fa99f194331ba8180
% CS 4476 / 6476: Computer Vision, Georgia Tech % Written by Henry Hu <[email protected]> and James Hays % Visualizes corresponding points between two images. Corresponding points % will have the same random color. % You do not need to modify anything in this function, although you can if % you want to. function [ h ] = show_correspondence(imgA, imgB, X1, Y1, X2, Y2) h = figure(2); % set(h, 'Position', [100 100 900 700]) % subplot(1,2,1); % imshow(image1, 'Border', 'tight') % % subplot(1,2,2); % imshow(image2, 'Border', 'tight') Height = max(size(imgA,1),size(imgB,1)); Width = size(imgA,2)+size(imgB,2); numColors = size(imgA, 3); newImg = zeros(Height, Width,numColors); newImg(1:size(imgA,1),1:size(imgA,2),:) = imgA; newImg(1:size(imgB,1),1+size(imgA,2):end,:) = imgB; imshow(newImg, 'Border', 'tight') shiftX = size(imgA,2); hold on for i = 1:size(X1,1) cur_color = rand(3,1); plot(X1(i),Y1(i), 'o', 'LineWidth',2, 'MarkerEdgeColor','k',... 'MarkerFaceColor', cur_color, 'MarkerSize',10) plot(X2(i)+shiftX,Y2(i), 'o', 'LineWidth',2, 'MarkerEdgeColor','k',... 'MarkerFaceColor', cur_color, 'MarkerSize',10) end hold off; % for i = 1:size(X1,1) % cur_color = rand(3,1); % subplot(1,2,1); % hold on; % plot(X1(i),Y1(i), 'o', 'LineWidth',2, 'MarkerEdgeColor','k',... % 'MarkerFaceColor', cur_color, 'MarkerSize',10) % % hold off; % % subplot(1,2,2); % hold on; % plot(X2(i),Y2(i), 'o', 'LineWidth',2, 'MarkerEdgeColor','k',... % 'MarkerFaceColor', cur_color, 'MarkerSize',10) % hold off; % end fprintf('Saving visualization to vis.jpg\n') visualization_image = frame2im(getframe(h)); % getframe() is unreliable. Depending on the rendering settings, it will % grab foreground windows instead of the figure in question. It could also % return an image that is not 800x600 if the figure is resized or partially % off screen. % try % %trying to crop some of the unnecessary boundary off the image % visualization_image = visualization_image(81:end-80, 51:end-50,:); % catch % ; % end imwrite(visualization_image, 'vis_dots.jpg', 'quality', 100)
github
aayush-k/Local-Feature-Matching-master
get_interest_points.m
.m
Local-Feature-Matching-master/code/get_interest_points.m
4,341
utf_8
627f44b3ca3d41aa59bcc5ecfdd57455
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays % 1. Compute the horizontal and vertical derivatives of the image Ix and Iy by convolving the original image with derivatives of Gaussians (Section 3.2.3). % 2. Compute the three images corresponding to the outer products of these gradients. (The matrix A is symmetric, so only three entries are needed.) % 3. Convolve each of these images with a larger Gaussian. % 4. Compute a scalar interest measure using one of the formulas discussed above. % 5. Find local maxima above a certain threshold and report them as detected feature point locations. % Returns a set of interest points for the input image % 'image' can be grayscale or color, your choice. % 'feature_width', in pixels, is the local feature width. It might be % useful in this function in order to (a) suppress boundary interest % points (where a feature wouldn't fit entirely in the image, anyway) % or (b) scale the image filters being used. Or you can ignore it. % 'x' and 'y' are nx1 vectors of x and y coordinates of interest points. % 'confidence' is an nx1 vector indicating the strength of the interest % point. You might use this later or not. % 'scale' and 'orientation' are nx1 vectors indicating the scale and % orientation of each interest point. These are OPTIONAL. By default you % do not need to make scale and orientation invariant local features. function [x, y, confidence, scale, orientation] = get_interest_points(image, feature_width) % Implement the Harris corner detector (See Szeliski 4.1.1) to start with. % You can create additional interest point detector functions (e.g. MSER) % for extra credit. % BLUR image?? % alpha = 0.06 as proposed by harris alpha = 0.04; threshold = 0.02 % gaussian kernels for the original image and the derivatives smallGaussian = fspecial('gaussian', [feature_width, feature_width], 1); largeGaussian = fspecial('gaussian', [feature_width, feature_width], 2); % filter original image GausImg = imfilter(image, smallGaussian); % calculate derivative products [I_x, I_y] = imgradientxy(GausImg); I_x2 = I_x .^ 2; I_y2 = I_y .^ 2; I_xy = I_x .* I_y; % apply gaussian to derivative products GausI_x2 = imfilter(I_x2, largeGaussian); GausI_y2 = imfilter(I_y2, largeGaussian); GausI_xy = imfilter(I_xy, largeGaussian); % calculate har har = (GausI_x2 .* GausI_y2) - (GausI_xy .^ 2) - (alpha .* (GausI_x2 + GausI_y2) .^ 2); % remove edges to account for wrong detections har(1:feature_width, :) = 0; har(:, 1:feature_width) = 0; har(end - feature_width:end, :) = 0; har(:, end - feature_width:end) = 0; % threshold the har and extract connected componented threshedHar = har > threshold; CC = bwconncomp(threshedHar); % get dimensions [rows, cols] = size(har); % initialize arrays to x = zeros(CC.NumObjects, 1); y = zeros(CC.NumObjects, 1); confidence = zeros(CC.NumObjects, 1); for ind = 1:CC.NumObjects % get indices of blob regions blobPixelInds = CC.PixelIdxList{ind} % mask to get original har values blobPixelVals = har(blobPixelInds) % get maximum [maxV, maxI] = max(blobPixelVals) % column indices x(ind) = floor(blobPixelInds(maxI) / rows); y(ind) = mod(blobPixelInds(maxI), rows); confidence(ind) = maxV; end % BWLABEL (old), BWCONNCOMP (new) % take max value in each component % % If you're finding spurious interest point detections near the boundaries, % it is safe to simply suppress the gradients / corners near the edges of % the image. % The lecture slides and textbook are a bit vague on how to do the % non-maximum suppression once you've thresholded the cornerness score. % You are free to experiment. Here are some helpful functions: % BWLABEL and the newer BWCONNCOMP will find connected components in % thresholded binary image. You could, for instance, take the maximum value % within each component. % COLFILT can be used to run a max() operator on each sliding window. You % could use this to ensure that every interest point is at a local maximum % of cornerness. % Placeholder that you can delete -- random points % x = ceil(rand(500,1) * size(image,2)); % y = ceil(rand(500,1) * size(image,1)); end
github
aayush-k/Local-Feature-Matching-master
cheat_interest_points.m
.m
Local-Feature-Matching-master/code/cheat_interest_points.m
1,111
utf_8
9d93fe7e1b0c34e407f2e5d3528315bf
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays % This function is provided for development and debugging but cannot be % used in the final handin. It 'cheats' by generating interest points from % known correspondences. It will only work for the three image pairs with % known correspondences. % 'eval_file' is the file path to the list of known correspondences. % 'scale_factor' is needed to map from the original image coordinates to % the resolution being used for the current experiment. % 'x1' and 'y1' are nx1 vectors of x and y coordinates of interest points % in the first image. % 'x1' and 'y1' are mx1 vectors of x and y coordinates of interest points % in the second image. For convenience, n will equal m but don't expect % that to be the case when interest points are created independently per % image. function [x1, y1, x2, y2] = cheat_interest_points(eval_file, scale_factor) load(eval_file) x1 = x1 .* scale_factor; y1 = y1 .* scale_factor; x2 = x2 .* scale_factor; y2 = y2 .* scale_factor; end
github
aayush-k/Local-Feature-Matching-master
show_ground_truth_corr.m
.m
Local-Feature-Matching-master/code/show_ground_truth_corr.m
441
utf_8
98f706af0be75ce44da3822986ef85b2
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays function show_ground_truth_corr() image1 = imread('../data/Notre Dame/921919841_a30df938f2_o.jpg'); image2 = imread('../data/Notre Dame/4191453057_c86028ce1f_o.jpg'); corr_file = '../data/Notre Dame/921919841_a30df938f2_o_to_4191453057_c86028ce1f_o.mat'; load(corr_file) show_correspondence(image1, image2, x1, y1, x2, y2)
github
aayush-k/Local-Feature-Matching-master
match_features.m
.m
Local-Feature-Matching-master/code/match_features.m
2,023
utf_8
ddb965c0b19bfc79a8e1157c7ceb1e5a
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays % 'features1' and 'features2' are the n x feature dimensionality features % from the two images. % If you want to include geometric verification in this stage, you can add % the x and y locations of the interest points as additional features. % % 'matches' is a k x 2 matrix, where k is the number of matches. The first % column is an index in features1, the second column is an index % in features2. % 'Confidences' is a k x 1 matrix with a real valued confidence for every % match. % 'matches' and 'confidences' can empty, e.g. 0x2 and 0x1. function [matches, confidences] = match_features(features1, features2) % This function does not need to be symmetric (e.g. it can produce % different numbers of matches depending on the order of the arguments). % To start with, simply implement the "ratio test", equation 4.18 in % section 4.1.3 of Szeliski. For extra credit you can implement various % forms of spatial verification of matches. % 1 - (NN1/NN2) dists = pdist2(features1, features2, 'euclidean'); [sortDistVal, sortDistInd] = sort(dists, 2); % Ratio Test ratioT = sortDistVal(:,1) ./ sortDistVal(:,2); threshold = 0.95; mask = ratioT < threshold; confidences = 1 ./ ratioT(mask); matches = zeros(size(confidences, 1), 2); matches(:, 1) = find(mask); matches(:, 2) = sortDistInd(mask, 1); % % Placeholder that you can delete. Random matches and confidences % num_features = min(size(features1, 1), size(features2,1)); % matches = zeros(num_features, 2); % matches(:,1) = randperm(num_features); % matches(:,2) = randperm(num_features); % confidences = rand(num_features,1); % Sort the matches so that the most confident onces are at the top of the % list. You should probably not delete this, so that the evaluation % functions can be run on the top matches easily. [confidences, ind] = sort(confidences, 'descend'); matches = matches(ind,:);
github
aayush-k/Local-Feature-Matching-master
collect_ground_truth_corr.m
.m
Local-Feature-Matching-master/code/collect_ground_truth_corr.m
2,009
utf_8
f59689693ec3d8d895fededdbc1efe39
% Local Feature Stencil Code % CS 4476 / 6476: Computer Vision, Georgia Tech % Written by James Hays function collect_ground_truth_corr() %An interactive method to specify and then save many point correspondences %between two photographs, which will be used to generate a projective %transformation. Run this before generate_transform.m %Pick a dozen corresponding points throughout the images, although more is %better. image1 = imread('../data/Notre Dame/921919841_a30df938f2_o.jpg'); image2 = imread('../data/Notre Dame/4191453057_c86028ce1f_o.jpg'); image1 = double(image1)/255; image2 = double(image2)/255; output_file = '../data/Notre Dame/921919841_a30df938f2_o_to_4191453057_c86028ce1f_o.mat'; %this function checks if some corresponding points are already saved, and %if so resumes work from there. if(exist(output_file,'file')) load(output_file) h = show_correspondence(image1, image2, x1, y1, x2, y2) else x1 = zeros(0,1); %x locations in image 1 y1 = zeros(0,1); %y locations in image 1 x2 = zeros(0,1); %corresponding x locations in image 2 y2 = zeros(0,1); %corresponding y locations in image 2 h = figure; subplot(1,2,1); imshow(image1) subplot(1,2,2); imshow(image2) end fprintf('Click on a negative coordinate (Above or to the left of the left image) to stop\n') while(1) [x,y] = ginput(1); if(x <= 0 || y <= 0) break end subplot(1,2,1); hold on; plot(x,y,'ro'); hold off; x1 = [x1;x]; y1 = [y1;y]; [x,y] = ginput(1); if(x <= 0 || y <= 0) break end subplot(1,2,2); hold on; plot(x,y,'ro'); hold off; x2 = [x2;x]; y2 = [y2;y]; fprintf('( %5.2f, %5.2f) matches to ( %5.2f, %5.2f)\n', x1(end), y1(end), x2(end), y2(end)); fprintf('%d total points corresponded\n', length(x1)); end fprintf('saving matched points\n') save(output_file, 'x1', 'y1', 'x2', 'y2')
github
aayush-k/Local-Feature-Matching-master
evaluate_correspondence.m
.m
Local-Feature-Matching-master/code/evaluate_correspondence.m
3,952
utf_8
35e20889ed67de05a8a5706b3d1fcada
% Local Feature Stencil Code % Computater Vision % Written by Henry Hu <[email protected]> and James Hays % You do not need to modify anything in this function, although you can if % you want to. function evaluate_correspondence(imgA, imgB, ground_truth_correspondence_file, scale_factor, x1_est, y1_est, x2_est, y2_est) % ground_truth_correspondence_file = '../data/Notre Dame/921919841_a30df938f2_o_to_4191453057_c86028ce1f_o.mat'; % = imread('../data/Notre Dame/921919841_a30df938f2_o.jpg'); % = imread('../data/Notre Dame/4191453057_c86028ce1f_o.jpg'); x1_est = x1_est ./ scale_factor; y1_est = y1_est ./ scale_factor; x2_est = x2_est ./ scale_factor; y2_est = y2_est ./ scale_factor; good_matches = zeros(length(x1_est),1); %indicator vector load(ground_truth_correspondence_file) %loads variables x1, y1, x2, y2 % x1 91x1 728 double % x2 91x1 728 double % y1 91x1 728 double % y2 91x1 728 double h = figure(4); Height = max(size(imgA,1),size(imgB,1)); Width = size(imgA,2)+size(imgB,2); numColors = size(imgA, 3); newImg = zeros(Height, Width,numColors); newImg(1:size(imgA,1),1:size(imgA,2),:) = imgA; newImg(1:size(imgB,1),1+size(imgA,2):end,:) = imgB; imshow(newImg, 'Border', 'tight') shiftX = size(imgA,2); hold on; for i = 1:length(x1_est) fprintf('( %4.0f, %4.0f) to ( %4.0f, %4.0f)', x1_est(i), y1_est(i), x2_est(i), y2_est(i)); %for each x1_est, find nearest ground truth point in x1 x_dists = x1_est(i) - x1; y_dists = y1_est(i) - y1; dists = sqrt( x_dists.^2 + y_dists.^2 ); [dists, best_matches] = sort(dists); current_offset = [x1_est(i) - x2_est(i), y1_est(i) - y2_est(i)]; most_similar_offset = [x1(best_matches(1)) - x2(best_matches(1)), y1(best_matches(1)) - y2(best_matches(1))]; %match_dist = sqrt( (x2_est(i) - x2(best_matches(1)))^2 + (y2_est(i) - y2(best_matches(1)))^2); match_dist = sqrt( sum((current_offset - most_similar_offset).^2)); %A match is bad if there's no ground truth point within 150 pixels or %if nearest ground truth correspondence offset isn't within 25 pixels %of the estimated correspondence offset. fprintf(' g.t. point %4.0f px. Match error %4.0f px.', dists(1), match_dist); if(dists(1) > 150 || match_dist > 40) good_matches(i) = 0; edgeColor = [1 0 0]; fprintf(' incorrect\n'); else good_matches(i) = 1; edgeColor = [0 1 0]; fprintf(' correct\n'); end cur_color = rand(1,3); plot(x1_est(i)*scale_factor,y1_est(i)*scale_factor, 'o', 'LineWidth',2, 'MarkerEdgeColor',edgeColor,... 'MarkerFaceColor', cur_color, 'MarkerSize',10) plot(x2_est(i)*scale_factor+shiftX,y2_est(i)*scale_factor, 'o', 'LineWidth',2, 'MarkerEdgeColor',edgeColor,... 'MarkerFaceColor', cur_color, 'MarkerSize',10) end hold off; fprintf('%d total good matches, %d total bad matches.', sum(good_matches), length(x1_est) - sum(good_matches)) fprintf(' %.2f%% accuracy\n', sum(good_matches) / length(x1_est)); fprintf('Saving visualization to eval.jpg\n') visualization_image = frame2im(getframe(h)); % getframe() is unreliable. Depending on the rendering settings, it will % grab foreground windows instead of the figure in question. It could also % return an image that is not 800x600 if the figure is resized or partially % off screen. % try % %trying to crop some of the unnecessary boundary off the image % visualization_image = visualization_image(81:end-80, 51:end-50,:); % catch % ; % end imwrite(visualization_image, 'eval.jpg', 'quality', 100)
github
akileshbadrinaaraayanan/IITH-master
imdb_cnn_train.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/imdb_cnn_train.m
11,107
utf_8
a957bb75bebf326aa0d9d848e0c4293d
function imdb_cnn_train(imdb, opts, varargin) % Train a CNN model on a dataset supplied by imdb opts.lite = false ; opts.numFetchThreads = 0 ; opts.train.batchSize = opts.batchSize ; opts.train.numEpochs = 25 ; opts.train.continue = true ; opts.train.useGpu = false ; opts.train.prefetch = false ; opts.train.learningRate = [0.001*ones(1, 10) 0.0001*ones(1, 10) 0.00001*ones(1,10)] ; opts.train.expDir = opts.expDir ; opts = vl_argparse(opts, varargin) ; % ------------------------------------------------------------------------- % Network initialization % ------------------------------------------------------------------------- net = initializeNetwork(imdb, opts) ; % Initialize average image if isempty(net.normalization.averageImage), % compute the average image averageImagePath = fullfile(opts.expDir, 'average.mat') ; if exist(averageImagePath, 'file') load(averageImagePath, 'averageImage') ; else train = find(imdb.images.set == 1) ; bs = 256 ; fn = getBatchWrapper(net.normalization, opts.numFetchThreads) ; for t=1:bs:numel(train) batch_time = tic ; batch = train(t:min(t+bs-1, numel(train))) ; fprintf('computing average image: processing batch starting with image %d ...', batch(1)) ; temp = fn(imdb, batch) ; im{t} = mean(temp, 4) ; batch_time = toc(batch_time) ; fprintf(' %.2f s (%.1f images/s)\n', batch_time, numel(batch)/ batch_time) ; end averageImage = mean(cat(4, im{:}),4) ; save(averageImagePath, 'averageImage') ; end net.normalization.averageImage = averageImage ; clear averageImage im temp ; end % ------------------------------------------------------------------------- % Stochastic gradient descent % ------------------------------------------------------------------------- fn = getBatchWrapper(net.normalization, opts.numFetchThreads) ; [net,info] = cnn_train(net, imdb, fn, opts.train, 'conserveMemory', true) ; % Save model net = vl_simplenn_move(net, 'cpu'); saveNetwork(fullfile(opts.expDir, 'final-model.mat'), net); % ------------------------------------------------------------------------- function saveNetwork(fileName, net) % ------------------------------------------------------------------------- layers = net.layers; % Replace the last layer with softmax layers{end}.type = 'softmax'; layers{end}.name = 'prob'; % Remove fields corresponding to training parameters ignoreFields = {'filtersMomentum', ... 'biasesMomentum',... 'filtersLearningRate',... 'biasesLearningRate',... 'filtersWeightDecay',... 'biasesWeightDecay',... 'class'}; for i = 1:length(layers), layers{i} = rmfield(layers{i}, ignoreFields(isfield(layers{i}, ignoreFields))); end classes = net.classes; normalization = net.normalization; save(fileName, 'layers', 'classes', 'normalization'); % ------------------------------------------------------------------------- function fn = getBatchWrapper(opts, numThreads) % ------------------------------------------------------------------------- fn = @(imdb,batch) getBatch(imdb,batch,opts,numThreads) ; % ------------------------------------------------------------------------- function [im,labels] = getBatch(imdb, batch, opts, numThreads) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir '/'], imdb.images.name(batch)) ; im = imdb_get_batch(images, opts, ... 'numThreads', numThreads, ... 'prefetch', nargout == 0); labels = imdb.images.label(batch) ; % ------------------------------------------------------------------------- function net = initializeNetwork(imdb, opts) % ------------------------------------------------------------------------- scal = 1 ; init_bias = 0.1; numClass = length(imdb.classes.name); if ~isempty(opts.model) net = load(fullfile('data/models', opts.model)); % Load model if specified net.normalization.keepAspect = opts.keepAspect; fprintf('Initializing from model: %s\n', opts.model); % Replace the last but one layer with random weights net.layers{end-1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(1,1,4096,numClass,'single'), ... 'biases', zeros(1, numClass, 'single'), ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 10, ... 'biasesLearningRate', 20, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0); % Last layer is softmaxloss (switch to softmax for prediction) net.layers{end} = struct('type', 'softmaxloss') ; % Rename classes net.classes.name = imdb.classes.name; net.classes.description = imdb.classes.name; % TODO: add dropout layers if initializing from previous models return; end % Else initial model randomly net.layers = {} ; % Block 1 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(11, 11, 3, 96, 'single'), ... 'biases', zeros(1, 96, 'single'), ... 'stride', 4, ... 'pad', 0, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'pool', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'normalize', ... 'param', [5 1 0.0001/5 0.75]) ; % Block 2 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(5, 5, 48, 256, 'single'), ... 'biases', init_bias*ones(1, 256, 'single'), ... 'stride', 1, ... 'pad', 2, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'pool', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; net.layers{end+1} = struct('type', 'normalize', ... 'param', [5 1 0.0001/5 0.75]) ; % Block 3 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(3,3,256,384,'single'), ... 'biases', init_bias*ones(1,384,'single'), ... 'stride', 1, ... 'pad', 1, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; % Block 4 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(3,3,192,384,'single'), ... 'biases', init_bias*ones(1,384,'single'), ... 'stride', 1, ... 'pad', 1, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; % Block 5 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(3,3,192,256,'single'), ... 'biases', init_bias*ones(1,256,'single'), ... 'stride', 1, ... 'pad', 1, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'pool', ... 'method', 'max', ... 'pool', [3 3], ... 'stride', 2, ... 'pad', 0) ; % Block 6 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(6,6,256,4096,'single'),... 'biases', init_bias*ones(1,4096,'single'), ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'dropout', ... 'rate', 0.5) ; % Block 7 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(1,1,4096,4096,'single'),... 'biases', init_bias*ones(1,4096,'single'), ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; net.layers{end+1} = struct('type', 'relu') ; net.layers{end+1} = struct('type', 'dropout', ... 'rate', 0.5) ; % Block 8 net.layers{end+1} = struct('type', 'conv', ... 'filters', 0.01/scal * randn(1,1,4096,numClass,'single'), ... 'biases', zeros(1, numClass, 'single'), ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 1, ... 'biasesLearningRate', 2, ... 'filtersWeightDecay', 1, ... 'biasesWeightDecay', 0) ; % Block 9 net.layers{end+1} = struct('type', 'softmaxloss') ; % Other details net.normalization.imageSize = [227, 227, 3] ; net.normalization.interpolation = 'bicubic' ; net.normalization.border = 256 - net.normalization.imageSize(1:2) ; net.normalization.averageImage = [] ; net.normalization.keepAspect = true ;
github
akileshbadrinaaraayanan/IITH-master
get_rcnn_features.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/get_rcnn_features.m
2,567
utf_8
8ec7919f6877980bbd15cde85e9a3ffd
function code = get_rcnn_features(net, im, varargin) % GET_RCNN_FEATURES % This function gets the fc7 features for an image region, % extracted from the provided mask. opts.batchSize = 96 ; opts.regionBorder = 0.05; opts = vl_argparse(opts, varargin) ; if ~iscell(im) im = {im} ; end res = [] ; cache = struct() ; resetCache() ; % for each image function resetCache() cache.images = cell(1,opts.batchSize) ; cache.indexes = zeros(1, opts.batchSize) ; cache.numCached = 0 ; end function flushCache() if cache.numCached == 0, return ; end images = cat(4, cache.images{:}) ; images = bsxfun(@minus, images, net.normalization.averageImage) ; if net.useGpu images = gpuArray(images) ; end res = vl_simplenn(net, images, ... [], res, ... 'conserveMemory', true, ... 'sync', true) ; code_ = squeeze(gather(res(end).x)) ; code_ = bsxfun(@times, 1./sqrt(sum(code_.^2)), code_) ; for q=1:cache.numCached code{cache.indexes(q)} = code_(:,q) ; end resetCache() ; end function appendCache(i,im) cache.numCached = cache.numCached + 1 ; cache.images{cache.numCached} = im ; cache.indexes(cache.numCached) = i; if cache.numCached >= opts.batchSize flushCache() ; end end code = {} ; for k=1:numel(im) appendCache(k, getImage(opts, single(im{k}), net.normalization.imageSize(1), net.normalization.keepAspect)); end flushCache() ; end % ------------------------------------------------------------------------- function reg = getImage(opts, im, regionSize, keepAspect) % ------------------------------------------------------------------------- if keepAspect w = size(im,2) ; h = size(im,1) ; factor = [regionSize/h,regionSize/w]; factor = max(factor); %if any(abs(factor - 1) > 0.0001) im_resized = imresize(im, ... 'scale', factor, ... 'method', 'bicubic') ; %end w = size(im_resized,2) ; h = size(im_resized,1) ; reg = imcrop(im_resized, [fix((w-regionSize)/2)+1, fix((h-regionSize)/2)+1,... round(regionSize)-1, round(regionSize)-1]); else reg = imresize(im, [regionSize, regionSize], 'bicubic') ; end % reg = imresize(im, [regionSize, regionSize], 'bicubic') ; end
github
akileshbadrinaaraayanan/IITH-master
get_bcnn_features.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/get_bcnn_features.m
5,006
utf_8
dc6b3d661ab0ce34e4c10321d9784263
function [code, varargout]= get_bcnn_features(neta, netb, im, varargin) % GET_BCNN_FEATURES Get bilinear cnn features for an image % This function extracts the binlinear combination of CNN features % extracted from two different networks. % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is part of the BCNN and is made available under % the terms of the BSD license (see the COPYING file). nVargOut = max(nargout,1)-1; if nVargOut==1 assert(true, 'Number of output should not be two.') end opts.crop = true ; %opts.scales = 2.^(1.5:-.5:-3); % try a bunch of scales opts.scales = 2; opts.encoder = [] ; opts.regionBorder = 0.05; opts.normalization = 'sqrt_L2'; opts = vl_argparse(opts, varargin) ; % get parameters of the network info = vl_simplenn_display(neta) ; borderA = round(info.receptiveField(end)/2+1) ; averageColourA = mean(mean(neta.normalization.averageImage,1),2) ; imageSizeA = neta.normalization.imageSize; info = vl_simplenn_display(netb) ; borderB = round(info.receptiveField(end)/2+1) ; averageColourB = mean(mean(netb.normalization.averageImage,1),2) ; imageSizeB = netb.normalization.imageSize; keepAspect = neta.normalization.keepAspect; assert(all(imageSizeA == imageSizeB)); assert(neta.normalization.keepAspect==netb.normalization.keepAspect); if ~iscell(im) im = {im} ; end code = cell(1, numel(im)); if nVargOut==2 im_resA = cell(numel(im), 1); im_resB = cell(numel(im), 1); end % for each image for k=1:numel(im) im_cropped = imresize(single(im{k}), imageSizeA([2 1]), 'bilinear'); crop_h = size(im_cropped,1) ; crop_w = size(im_cropped,2) ; resA = [] ; resB = [] ; psi = cell(1, numel(opts.scales)); % for each scale for s=1:numel(opts.scales) if min(crop_h,crop_w) * opts.scales(s) < min(borderA, borderB), continue ; end if sqrt(crop_h*crop_w) * opts.scales(s) > 1024, continue ; end if keepAspect w = size(im{k},2) ; h = size(im{k},1) ; factor = [imageSizeA(1)/h,imageSizeA(2)/w]; factor = max(factor)*opts.scales(s) ; im_resized = imresize(single(im{k}), ... 'scale', factor, ... 'method', 'bilinear') ; w = size(im_resized,2) ; h = size(im_resized,1) ; im_resized = imcrop(im_resized, [fix((w-imageSizeA(1)*opts.scales(s))/2)+1, fix((h-imageSizeA(2)*opts.scales(s))/2)+1,... round(imageSizeA(1)*opts.scales(s))-1, round(imageSizeA(2)*opts.scales(s))-1]); else im_resized = imresize(single(im{k}), round(imageSizeA([2 1])*opts.scales(s)), 'bilinear'); end im_resizedA = bsxfun(@minus, im_resized, averageColourA) ; im_resizedB = bsxfun(@minus, im_resized, averageColourB) ; if nVargOut==2 im_resA{k} = im_resizedA; im_resB{k} = im_resizedB; end if neta.useGpu im_resizedA = gpuArray(im_resizedA) ; im_resizedB = gpuArray(im_resizedB) ; end resA = vl_simplenn(neta, im_resizedA, [], resA, ... 'conserveMemory', true, 'sync', true); resB = vl_simplenn(netb, im_resizedB, [], resB, ... 'conserveMemory', true, 'sync', true); A = gather(resA(end).x); B = gather(resB(end).x); psi{s} = bilinear_pool(A,B); feat_dim = max(cellfun(@length,psi)); code{k} = zeros(feat_dim, 1); end % pool across scales for s=1:numel(opts.scales), if ~isempty(psi{s}), code{k} = code{k} + psi{s}; end end assert(~isempty(code{k})); end % square-root and l2 normalize (like: Improved Fisher?) switch opts.normalization case 'sqrt_L2' for k=1:numel(im), code{k} = sign(code{k}).*sqrt(abs(code{k})); code{k} = code{k}./(norm(code{k}+eps)); end case 'L2' for k=1:numel(im), code{k} = code{k}./(norm(code{k}+eps)); end case 'sqrt' for k=1:numel(im), code{k} = sign(code{k}).*sqrt(abs(code{k})); end case 'none' end if nVargOut==2 varargout{1} = cat(4, im_resA{:}); varargout{2} = cat(4, im_resB{:}); end function psi = bilinear_pool(A, B) w1 = size(A,2) ; h1 = size(A,1) ; w2 = size(B,2) ; h2 = size(B,1) ; if w1*h1 <= w2*h2, %downsample B B = array_resize(B, w1, h1); A = reshape(A, [w1*h1 size(A,3)]); else %downsample A A = array_resize(A, w2, h2); B = reshape(B, [w2*h2 size(B,3)]); end % bilinear pool psi = A'*B; psi = psi(:); function Ar = array_resize(A, w, h) numChannels = size(A, 3); indw = round(linspace(1,size(A,2),w)); indh = round(linspace(1,size(A,1),h)); Ar = zeros(w*h, numChannels, 'single'); for i = 1:numChannels, Ai = A(indh,indw,i); Ar(:,i) = Ai(:); end
github
akileshbadrinaaraayanan/IITH-master
model_setup.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/model_setup.m
4,981
utf_8
dd2ecf29110db93049ea41940d366eaf
function [opts, imdb] = model_setup(varargin) % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is part of the BCNN and is made available under % the terms of the BSD license (see the COPYING file). setup ; opts.seed = 1 ; opts.batchSize = 128 ; opts.numEpochs = 100; opts.momentum = 0.9; opts.keepAspect = true; opts.useVal = false; opts.useGpu = 0 ; opts.regionBorder = 0.05 ; opts.numDCNNWords = 64 ; opts.numDSIFTWords = 256 ; opts.numSamplesPerWord = 1000 ; opts.printDatasetInfo = true ; opts.excludeDifficult = true ; opts.datasetSize = inf; opts.encoders = {struct('type', 'rcnn', 'opts', {})} ; opts.dataset = 'cub' ; opts.carsDir = '../data/car_ims'; opts.cubDir = '../data/CUB_200_2011'; opts.aircraftDir = '../data/oid-aircraft-beta-1'; opts.suffix = 'baseline' ; opts.prefix = 'v1' ; opts.model = '../data/models/imagenet-vgg-m.mat'; opts.modela = '../data/models/imagenet-vgg-m.mat'; opts.modelb = '../data/models/imagenet-vgg-s.mat'; opts.layer = 14; opts.layera = 14; opts.layerb = 14; %opts.bcnn = false; opts.bcnnScale = 1; opts.bcnnLRinit = false; opts.bcnnLayer = 14; opts.dataAugmentation = {'none', 'none', 'none'}; [opts, varargin] = vl_argparse(opts,varargin) ; opts.expDir = sprintf('data/%s/%s-seed-%02d', opts.prefix, opts.dataset, opts.seed) ; opts.imdbDir = fullfile(opts.expDir, 'imdb') ; opts.resultPath = fullfile(opts.expDir, sprintf('result-%s.mat', opts.suffix)) ; opts = vl_argparse(opts,varargin) ; if nargout <= 1, return ; end % Setup GPU if needed if opts.useGpu gpuDevice(opts.useGpu) ; end % ------------------------------------------------------------------------- % Setup encoders % ------------------------------------------------------------------------- models = {} ; modelPath = {}; for i = 1:numel(opts.encoders) if isstruct(opts.encoders{i}) name = opts.encoders{i}.name ; opts.encoders{i}.path = fullfile(opts.expDir, [name '-encoder.mat']) ; opts.encoders{i}.codePath = fullfile(opts.expDir, [name '-codes.mat']) ; [md, mdpath] = get_cnn_model_from_encoder_opts(opts.encoders{i}); models = horzcat(models, md) ; modelPath = horzcat(modelPath, mdpath); % models = horzcat(models, get_cnn_model_from_encoder_opts(opts.encoders{i})) ; else for j = 1:numel(opts.encoders{i}) name = opts.encoders{i}{j}.name ; opts.encoders{i}{j}.path = fullfile(opts.expDir, [name '-encoder.mat']) ; opts.encoders{i}{j}.codePath = fullfile(opts.expDir, [name '-codes.mat']) ; [md, mdpath] = get_cnn_model_from_encoder_opts(opts.encoders{i}{j}); models = horzcat(models, md) ; modelPath = horzcat(modelPath, mdpath); % models = horzcat(models, get_cnn_model_from_encoder_opts(opts.encoders{i}{j})) ; end end end % ------------------------------------------------------------------------- % Download CNN models % ------------------------------------------------------------------------- for i = 1:numel(models) if ~exist(modelPath{i}) error(['cannot find model ', models{i}]) ; end end % ------------------------------------------------------------------------- % Load dataset % ------------------------------------------------------------------------- vl_xmkdir(opts.expDir) ; vl_xmkdir(opts.imdbDir) ; imdbPath = fullfile(opts.imdbDir, sprintf('imdb-seed-%d.mat', opts.seed)) ; if exist(imdbPath) imdb = load(imdbPath) ; return ; end switch opts.dataset case 'cubcrop' imdb = cub_get_database(opts.cubDir, true, false); case 'cub' imdb = cub_get_database(opts.cubDir, false, opts.useVal); case 'aircraft-variant' imdb = aircraft_get_database(opts.aircraftDir, 'variant'); case 'cars' imdb = cars_get_database(opts.carsDir, false, opts.useVal); otherwise error('Unknown dataset %s', opts.dataset) ; end save(imdbPath, '-struct', 'imdb') ; if opts.printDatasetInfo print_dataset_info(imdb) ; end % ------------------------------------------------------------------------- function [model, modelPath] = get_cnn_model_from_encoder_opts(encoder) % ------------------------------------------------------------------------- p = find(strcmp('model', encoder.opts)) ; if ~isempty(p) [~,m,e] = fileparts(encoder.opts{p+1}) ; model = {[m e]} ; modelPath = encoder.opts{p+1}; else model = {} ; modelPath = {}; end % bilinear cnn models p = find(strcmp('modela', encoder.opts)) ; if ~isempty(p) [~,m,e] = fileparts(encoder.opts{p+1}) ; model = horzcat(model,{[m e]}) ; modelPath = horzcat(modelPath, encoder.opts{p+1}); end p = find(strcmp('modelb', encoder.opts)) ; if ~isempty(p) [~,m,e] = fileparts(encoder.opts{p+1}) ; model = horzcat(model,{[m e]}) ; modelPath = horzcat(modelPath, encoder.opts{p+1}); end
github
akileshbadrinaaraayanan/IITH-master
bcnn_asym_forward.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/bcnn_asym_forward.m
3,110
utf_8
ae749c28e094092f12b95926a2f4f0f1
function [code, varargout]= bcnn_asym_forward(neta, netb, im, varargin) % BCNN_ASYM_FORWARD run the forward passing of the two networks and output the % bilinear cnn features for batch of images. The images are pre-cropped, % resized and mean subtracted. The function doesn't preprocess the images % instead just get the bcnn outputs. % INPUT % neta: network A beased on MatConvNet structure % netb: network B beased on MatConvNet structure % im{1} : cell array of images input for network A % im{2} : cell array of images input for network B % OUTPUT % code: cell array of output bcnn codes % varargout: % varargout{1}: output of network A % varargout{2}: output of network B % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is part of the BCNN and is made available under % the terms of the BSD license (see the COPYING file). nVargOut = max(nargout,1)-1; if nVargOut==1 || nVargOut==2 || nVargOut==3 assert(true, 'Number of output problem') end % basic setting opts.crop = true ; opts.encoder = [] ; opts.regionBorder = 0.05; opts.normalization = 'sqrt'; opts.networkconservmemory = true; opts = vl_argparse(opts, varargin) ; % re-structure the images to 4-D arrays im_resA = im{1}; im_resB = im{2}; N = numel(im_resA); im_resA = cat(4, im_resA{:}); im_resB = cat(4, im_resB{:}); resA = [] ; resB = [] ; code = cell(1, N); % move images to GPU if neta.useGpu im_resA = gpuArray(im_resA) ; im_resB = gpuArray(im_resB) ; end % forward passsing resA = vl_bilinearnn(neta, im_resA, [], resA, ... 'conserveMemory', opts.networkconservmemory, 'sync', true); resB = vl_bilinearnn(netb, im_resB, [], resB, ... 'conserveMemory', opts.networkconservmemory, 'sync', true); % get the output of the last layers A = gather(resA(end).x); B = gather(resB(end).x); % compute outer product and pool across pixels for each image for k=1:N code{k} = bilinear_pool(squeeze(A(:,:,:,k)), squeeze(B(:,:,:,k))); assert(~isempty(code{k})); end % square-root and l2 normalize (like: Improved Fisher?) switch opts.normalization case 'sqrt' for k=1:N, code{k} = sign(code{k}).*sqrt(abs(code{k})); code{k} = code{k}./(norm(code{k}+eps)); end case 'L2' for k=1:N, code{k} = code{k}./(norm(code{k}+eps)); end case 'none' end if nVargOut==2 varargout{1} = resA; varargout{2} = resB; end function psi = bilinear_pool(A, B) w1 = size(A,2) ; h1 = size(A,1) ; w2 = size(B,2) ; h2 = size(B,1) ; if w1*h1 <= w2*h2, %downsample B B = array_resize(B, w1, h1); A = reshape(A, [w1*h1 size(A,3)]); else %downsample A A = array_resize(A, w2, h2); B = reshape(B, [w2*h2 size(B,3)]); end % bilinear pool psi = A'*B; psi = psi(:); function Ar = array_resize(A, w, h) numChannels = size(A, 3); indw = round(linspace(1,size(A,2),w)); indh = round(linspace(1,size(A,1),h)); Ar = zeros(w*h, numChannels, 'single'); for i = 1:numChannels, Ai = A(indh,indw,i); Ar(:,i) = Ai(:); end
github
akileshbadrinaaraayanan/IITH-master
vl_bilinearnn.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/vl_bilinearnn.m
11,132
utf_8
fd1ef3540067f57e543ae75b8fb91153
function res = vl_bilinearnn(net, x, dzdy, res, varargin) % VL_BILINEARNN is the extension of VL_SIMPLENN to suppport % 1.vl_nnbilinearpool() % 2.vl_nnbilinearclpool() % 3.vl_nnsqrt() % 4.vl_nnl2norm() % RES = VL_BILINEARENN(NET, X) evaluates the convnet NET on data X. % RES = VL_BILINEARNN(NET, X, DZDY) evaluates the convnent NET and its % derivative on data X and output derivative DZDY. % % The network has a simple (linear) topology, i.e. the computational % blocks are arranged in a sequence of layers. Please note that % there is no need to use this wrapper, which is provided for % convenience. Instead, the individual CNN computational blocks can % be evaluated directly, making it possible to create significantly % more complex topologies, and in general allowing greater % flexibility. % % The NET structure contains two fields: % % - net.layers: the CNN layers. % - net.normalization: information on how to normalize input data. % % The network expects the data X to be already normalized. This % usually involves rescaling the input image(s) and subtracting a % mean. % % RES is a structure array with one element per network layer plus % one representing the input. So RES(1) refers to the zeroth-layer % (input), RES(2) refers to the first layer, etc. Each entry has % fields: % % - res(i+1).x: the output of layer i. Hence res(1).x is the network % input. % % - res(i+1).aux: auxiliary output data of layer i. For example, % dropout uses this field to store the dropout mask. % % - res(i+1).dzdx: the derivative of the network output relative to % variable res(i+1).x, i.e. the output of layer i. In particular % res(1).dzdx is the derivative of the network output with respect % to the network input. % % - res(i+1).dzdw: the derivative of the network output relative to % the parameters of layer i. It can be a cell array for multiple % parameters. % % net.layers is a cell array of network layers. The following % layers, encapsulating corresponding functions in the toolbox, are % supported: % % Convolutional layer:: % The convolutional layer wraps VL_NNCONV(). It has fields: % % - layer.type = 'conv' % - layer.filters: the filters. % - layer.biases: the biases. % - layer.stride: the sampling stride (usually 1). % - layer.padding: the padding (usually 0). % % Max pooling layer:: % The max pooling layer wraps VL_NNPOOL(). It has fields: % % - layer.type = 'pool' % - layer.method: pooling method ('max' or 'avg'). % - layer.pool: the pooling size. % - layer.stride: the sampling stride (usually 1). % - layer.padding: the padding (usually 0). % % Normalization layer:: % The normalization layer wraps VL_NNNORMALIZE(). It has fields % % - layer.type = 'normalize' % - layer.param: the normalization parameters. % % ReLU layer:: % The ReLU layer wraps VL_NNRELU(). It has fields: % % - layer.type = 'relu' % % Dropout layer:: % The dropout layer wraps VL_NNDROPOUT(). It has fields: % % - layer.type = 'dropout' % - layer.rate: the dropout rate. % % Softmax layer:: % The softmax layer wraps VL_NNSOFTMAX(). It has fields % % - layer.type = 'softmax' % % Log-loss layer:: % The log-loss layer wraps VL_NNLOSS(). It has fields: % % - layer.type = 'loss' % - layer.class: the ground-truth class. % % Softmax-log-loss layer:: % The softmax-log-loss layer wraps VL_NNSOFTMAXLOSS(). It has % fields: % % - layer.type = 'softmaxloss' % - layer.class: the ground-truth class. % % Bilinear-pool layer:: % The bilinear-pool layer wraps VL_NNBILINEARPOOL(). It has fields: % % - layer.type = 'bilinearpool' % % Bilinear-cross-layer-pool layer:: % The bilinear-cross-layer-pool layer wraps VL_NNBILINEARCLPOOL(). It has fields: % % - layer.type = 'bilinearclpool' % - layer.layer1: one input from the output of layer1 % - layer.layer2: one input from the output of layer2 % % Square-root layer:: % The square-root layer wraps VL_NNSQRT(). It has fields: % % - layer.type = 'sqrt' % % L2 normalization layer:: % The l2 normalization layer wraps VL_NNL2NORM(). It has fields: % % - layer.type = 'l2norm' % % Custom layer:: % This can be used to specify custom layers. % % - layer.type = 'custom' % - layer.forward: a function handle computing the block. % - layer.backward: a function handle computing the block derivative. % % The first function is called as res(i+1) = forward(layer, res(i), res(i+1)) % where res() is the struct array specified before. The second function is % called as res(i) = backward(layer, res(i), res(i+1)). Note that the % `layer` structure can contain additional fields if needed. % % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is modified from VL_SIMPLENN.m of MATCONVNET package % and is made available under the terms of the BSD license (see the COPYING file). opts.res = [] ; opts.conserveMemory = false ; opts.sync = false ; opts.disableDropout = false ; opts.freezeDropout = false ; opts.doforward = true; opts = vl_argparse(opts, varargin); n = numel(net.layers) ; doforward = opts.doforward; if (nargin <= 2) || isempty(dzdy) doder = false ; else doder = true ; end docrosslayer = false; for i=1:n l = net.layers{i} ; if(strcmp(l.type, 'bilinearclpool')) docrosslayer = true; crlayer1 = l.layer1; crlayer2 = l.layer2; end end if(opts.doforward) gpuMode = isa(x, 'gpuArray') ; else gpuMode = isa(dzdy, 'gpuArray') ; end if nargin <= 3 || isempty(res) res = struct(... 'x', cell(1,n+1), ... 'dzdx', cell(1,n+1), ... 'dzdw', cell(1,n+1), ... 'aux', cell(1,n+1), ... 'time', num2cell(zeros(1,n+1)), ... 'backwardTime', num2cell(zeros(1,n+1))) ; end if(~isempty(x)) res(1).x = x ; end if doforward for i=1:n l = net.layers{i} ; res(i).time = tic ; switch l.type case 'conv' res(i+1).x = vl_nnconv(res(i).x, l.filters, l.biases, 'pad', l.pad, 'stride', l.stride) ; case 'pool' res(i+1).x = vl_nnpool(res(i).x, l.pool, 'pad', l.pad, 'stride', l.stride, 'method', l.method) ; case 'normalize' res(i+1).x = vl_nnnormalize(res(i).x, l.param) ; case 'softmax' res(i+1).x = vl_nnsoftmax(res(i).x) ; case 'loss' res(i+1).x = vl_nnloss(res(i).x, l.class) ; case 'softmaxloss' res(i+1).x = vl_nnsoftmaxloss(res(i).x, l.class) ; case 'relu' res(i+1).x = vl_nnrelu(res(i).x) ; case 'noffset' res(i+1).x = vl_nnnoffset(res(i).x, l.param) ; case 'bilinearpool' res(i+1).x = vl_nnbilinearpool(res(i).x); case 'bilinearclpool' x1 = res(l.layer1+1).x; x2 = res(l.layer2+1).x; res(i+1).x = vl_nnbilinearclpool(x1, x2); case 'sqrt' res(i+1).x = vl_nnsqrt(res(i).x); case 'l2norm' res(i+1).x = vl_nnl2norm(res(i).x); case 'dropout' if opts.disableDropout res(i+1).x = res(i).x ; elseif opts.freezeDropout [res(i+1).x, res(i+1).aux] = vl_nndropout(res(i).x, 'rate', l.rate, 'mask', res(i+1).aux) ; else [res(i+1).x, res(i+1).aux] = vl_nndropout(res(i).x, 'rate', l.rate) ; end case 'custom' res(i+1) = l.forward(l, res(i), res(i+1)) ; otherwise error('Unknown layer type %s', l.type) ; end if opts.conserveMemory & ~doder & i < numel(net.layers) - 1 % TODO: forget unnecesary intermediate computations even when % derivatives are required if ~docrosslayer res(i).x = [] ; else if i~=crlayer1+1 && i~=crlayer2+1 res(i).x = [] ; end end end if gpuMode & opts.sync % This should make things slower, but on MATLAB 2014a it is necessary % for any decent performance. wait(gpuDevice) ; end res(i).time = toc(res(i).time) ; end end if doder res(n+1).dzdx = dzdy ; for i=n:-1:1 l = net.layers{i} ; res(i).backwardTime = tic ; switch l.type case 'conv' [backprop, res(i).dzdw{1}, res(i).dzdw{2}] = ... vl_nnconv(res(i).x, l.filters, l.biases, ... res(i+1).dzdx, ... 'pad', l.pad, 'stride', l.stride) ; res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'pool' backprop = vl_nnpool(res(i).x, l.pool, res(i+1).dzdx, ... 'pad', l.pad, 'stride', l.stride, 'method', l.method) ; res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'normalize' backprop = vl_nnnormalize(res(i).x, l.param, res(i+1).dzdx) ; res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'softmax' res(i).dzdx = vl_nnsoftmax(res(i).x, res(i+1).dzdx) ; case 'loss' res(i).dzdx = vl_nnloss(res(i).x, l.class, res(i+1).dzdx) ; case 'softmaxloss' res(i).dzdx = vl_nnsoftmaxloss(res(i).x, l.class, res(i+1).dzdx) ; case 'relu' backprop = vl_nnrelu(res(i).x, res(i+1).dzdx) ; res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'noffset' backprop = vl_nnnoffset(res(i).x, l.param, res(i+1).dzdx) ; res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'bilinearpool' backprop = vl_nnbilinearpool(res(i).x, res(i+1).dzdx); res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'bilinearclpool' x1 = res(l.layer1+1).x; x2 = res(l.layer2+1).x; [y1, y2] = vl_nnbilinearclpool(x1, x2, res(i+1).dzdx); res(l.layer1+1).dzdx = updateGradient(res(l.layer1+1).dzdx, y1); res(l.layer2+1).dzdx = updateGradient(res(l.layer2+1).dzdx, y2); case 'sqrt' res(i).dzdx = vl_nnsqrt(res(i).x, res(i+1).dzdx); case 'l2norm' res(i).dzdx = vl_nnl2norm(res(i).x, res(i+1).dzdx); case 'dropout' if opts.disableDropout backprop = res(i+1).dzdx ; else backprop = vl_nndropout(res(i).x, res(i+1).dzdx, 'mask', res(i+1).aux) ; end res(i).dzdx = updateGradient(res(i).dzdx, backprop); case 'custom' res(i) = l.backward(l, res(i), res(i+1)) ; end if opts.conserveMemory res(i+1).dzdx = [] ; end if gpuMode & opts.sync wait(gpuDevice) ; end res(i).backwardTime = toc(res(i).backwardTime) ; end end % add up the gradient function g = updateGradient(y, backprop) if isempty(y) g = backprop; else g = y + backprop; end
github
akileshbadrinaaraayanan/IITH-master
bcnn_train_sw.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/bcnn_train_sw.m
11,154
utf_8
4537c6cb7fb3028503d506f65310b2d9
function [net, info] = bcnn_train_sw(net, imdb, getBatch, varargin) % BNN_TRAIN_SW training a symmetric BCNN % BCNN_TRAIN() is an example learner implementing stochastic gradient % descent with momentum to train a symmetric BCNN for image classification. % It can be used with different datasets by providing a suitable % getBatch function. % INPUT % net: a bcnn networks structure % getBatch: function to read a batch of images % imdb: imdb structure of a dataset % OUTPUT % net: an output of symmetric bcnn network after fine-tuning % info: log of training and validation % A symmetric BCNN consists of multiple layers of convolutions, pooling, and % nonlinear activation with bilinearpool, square-root and L2 normalization % and sofmaxloss on the top. % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is part of the BCNN and is made available under % the terms of the BSD license (see the COPYING file). % This function is modified from CNN_TRAIN of MatConvNet % basic setting opts.train = [] ; opts.val = [] ; opts.numEpochs = 300 ; opts.batchSize = 256 ; opts.useGpu = false ; opts.learningRate = 0.001 ; opts.continue = false ; opts.expDir = fullfile('data','exp') ; opts.conserveMemory = false ; opts.sync = true ; opts.prefetch = false ; opts.weightDecay = 0.0005 ; opts.momentum = 0.9; opts.errorType = 'multiclass' ; opts.plotDiagnostics = false ; opts.dataAugmentation = {'none','none','none'}; opts.scale = 1; 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 % ------------------------------------------------------------------------- % Network initialization % ------------------------------------------------------------------------- % set hyperparameters for i=1:numel(net.layers) if ~strcmp(net.layers{i}.type,'conv'), continue; end net.layers{i}.filtersMomentum = zeros(size(net.layers{i}.filters), ... class(net.layers{i}.filters)) ; net.layers{i}.biasesMomentum = zeros(size(net.layers{i}.biases), ... class(net.layers{i}.biases)) ; %#ok<*ZEROLIKE> if ~isfield(net.layers{i}, 'filtersLearningRate') net.layers{i}.filtersLearningRate = 1 ; end if ~isfield(net.layers{i}, 'biasesLearningRate') net.layers{i}.biasesLearningRate = 1 ; end if ~isfield(net.layers{i}, 'filtersWeightDecay') net.layers{i}.filtersWeightDecay = 1 ; end if ~isfield(net.layers{i}, 'biasesWeightDecay') net.layers{i}.biasesWeightDecay = 1 ; end end % ------------------------------------------------------------------------- % Move network to GPU or CPU % ------------------------------------------------------------------------- if opts.useGpu net = vl_simplenn_move(net, 'gpu') ; for i=1:numel(net.layers) if ~strcmp(net.layers{i}.type,'conv'), continue; end net.layers{i}.filtersMomentum = gpuArray(net.layers{i}.filtersMomentum) ; net.layers{i}.biasesMomentum = gpuArray(net.layers{i}.biasesMomentum) ; end end % ------------------------------------------------------------------------- % Train and validate % ------------------------------------------------------------------------- if opts.useGpu one = gpuArray(single(1)) ; else one = single(1) ; end info.train.objective = [] ; info.train.error = [] ; info.train.topFiveError = [] ; info.train.speed = [] ; info.val.objective = [] ; info.val.error = [] ; info.val.topFiveError = [] ; info.val.speed = [] ; lr = 0 ; res = [] ; for epoch=1:opts.numEpochs prevLr = lr ; lr = opts.learningRate(min(epoch, numel(opts.learningRate))) ; % fast-forward to where we stopped, true, opts.scale modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep)); modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ; if opts.continue if exist(modelPath(epoch),'file'), continue ; end if epoch > 1 fprintf('resuming by loading epoch %d\n', epoch-1) ; load(modelPath(epoch-1), 'net', 'info') ; end end train = opts.train(randperm(numel(opts.train))) ; val = opts.val ; info.train.objective(end+1) = 0 ; info.train.error(end+1) = 0 ; info.train.topFiveError(end+1) = 0 ; info.train.speed(end+1) = 0 ; info.val.objective(end+1) = 0 ; info.val.error(end+1) = 0 ; info.val.topFiveError(end+1) = 0 ; info.val.speed(end+1) = 0 ; % reset momentum if needed if prevLr ~= lr fprintf('learning rate changed (%f --> %f): resetting momentum\n', prevLr, lr) ; for l=1:numel(net.layers) if ~strcmp(net.layers{l}.type, 'conv'), continue ; end net.layers{l}.filtersMomentum = 0 * net.layers{l}.filtersMomentum ; net.layers{l}.biasesMomentum = 0 * net.layers{l}.biasesMomentum ; end end for t=1:opts.batchSize:numel(train) % get next image batch and labels batch = train(t:min(t+opts.batchSize-1, numel(train))) ; batch_time = tic ; fprintf('training: epoch %02d: processing batch %3d of %3d ...', epoch, ... fix((t-1)/opts.batchSize)+1, ceil(numel(train)/opts.batchSize)) ; [im, labels] = getBatch(imdb, batch, opts.dataAugmentation{1}, opts.scale) ; if opts.prefetch nextBatch = train(t+opts.batchSize:min(t+2*opts.batchSize-1, numel(train))) ; getBatch(imdb, nextBatch, opts.dataAugmentation{1}, opts.scale) ; end im = im{1}; im = cat(4, im{:}); if opts.useGpu im = gpuArray(im) ; end % backprop net.layers{end}.class = labels ; res = [] ; res = vl_bilinearnn(net, im, one, res, ... 'conserveMemory', opts.conserveMemory, ... 'sync', opts.sync) ; % gradient step for l=1:numel(net.layers) if ~strcmp(net.layers{l}.type, 'conv'), continue ; end net.layers{l}.filtersMomentum = ... opts.momentum * net.layers{l}.filtersMomentum ... - (lr * net.layers{l}.filtersLearningRate) * ... (opts.weightDecay * net.layers{l}.filtersWeightDecay) * net.layers{l}.filters ... - (lr * net.layers{l}.filtersLearningRate) / numel(batch) * res(l).dzdw{1} ; net.layers{l}.biasesMomentum = ... opts.momentum * net.layers{l}.biasesMomentum ... - (lr * net.layers{l}.biasesLearningRate) * .... (opts.weightDecay * net.layers{l}.biasesWeightDecay) * net.layers{l}.biases ... - (lr * net.layers{l}.biasesLearningRate) / numel(batch) * res(l).dzdw{2} ; net.layers{l}.filters = net.layers{l}.filters + net.layers{l}.filtersMomentum ; net.layers{l}.biases = net.layers{l}.biases + net.layers{l}.biasesMomentum ; end % print information batch_time = toc(batch_time) ; speed = numel(batch)/batch_time ; info.train = updateError(opts, info.train, net, res, batch_time) ; fprintf(' %.2f s (%.1f images/s)', batch_time, speed) ; n = t + numel(batch) - 1 ; fprintf(' err %.1f err5 %.1f', ... info.train.error(end)/n*100, info.train.topFiveError(end)/n*100) ; fprintf('\n') ; % debug info if opts.plotDiagnostics figure(2) ; vl_simplenn_diagnose(net,res) ; drawnow ; end end % next batch % evaluation on validation set for t=1:opts.batchSize:numel(val) batch_time = tic ; batch = val(t:min(t+opts.batchSize-1, numel(val))) ; fprintf('validation: epoch %02d: processing batch %3d of %3d ...', epoch, ... fix((t-1)/opts.batchSize)+1, ceil(numel(val)/opts.batchSize)) ; [im, labels] = getBatch(imdb, batch, opts.dataAugmentation{2}, opts.scale) ; if opts.prefetch nextBatch = val(t+opts.batchSize:min(t+2*opts.batchSize-1, numel(val))) ; getBatch(imdb, nextBatch, opts.dataAugmentation{2}, opts.scale) ; end im = im{1}; im = cat(4, im{:}); if opts.useGpu im = gpuArray(im) ; end net.layers{end}.class = labels ; res = [] ; res = vl_bilinearnn(net, im, [], res, ... 'disableDropout', true, ... 'conserveMemory', opts.conserveMemory, ... 'sync', opts.sync) ; % print information batch_time = toc(batch_time) ; speed = numel(batch)/batch_time ; info.val = updateError(opts, info.val, net, res, batch_time) ; fprintf(' %.2f s (%.1f images/s)', batch_time, speed) ; n = t + numel(batch) - 1 ; fprintf(' err %.1f err5 %.1f', ... info.val.error(end)/n*100, info.val.topFiveError(end)/n*100) ; fprintf('\n') ; end % save info.train.objective(end) = info.train.objective(end) / numel(train) ; info.train.error(end) = info.train.error(end) / numel(train) ; info.train.topFiveError(end) = info.train.topFiveError(end) / numel(train) ; info.train.speed(end) = numel(train) / info.train.speed(end) ; info.val.objective(end) = info.val.objective(end) / numel(val) ; info.val.error(end) = info.val.error(end) / numel(val) ; info.val.topFiveError(end) = info.val.topFiveError(end) / numel(val) ; info.val.speed(end) = numel(val) / info.val.speed(end) ; save(modelPath(epoch), 'net', 'info', '-v7.3') ; figure(1) ; clf ; subplot(1,2,1) ; semilogy(1:epoch, info.train.objective, 'k') ; hold on ; semilogy(1:epoch, info.val.objective, 'b') ; xlabel('training epoch') ; ylabel('energy') ; grid on ; h=legend('train', 'val') ; set(h,'color','none'); title('objective') ; subplot(1,2,2) ; switch opts.errorType case 'multiclass' plot(1:epoch, info.train.error, 'k') ; hold on ; plot(1:epoch, info.train.topFiveError, 'k--') ; plot(1:epoch, info.val.error, 'b') ; plot(1:epoch, info.val.topFiveError, 'b--') ; h=legend('train','train-5','val','val-5') ; case 'binary' plot(1:epoch, info.train.error, 'k') ; hold on ; plot(1:epoch, info.val.error, 'b') ; h=legend('train','val') ; end grid on ; xlabel('training epoch') ; ylabel('error') ; set(h,'color','none') ; title('error') ; drawnow ; print(1, modelFigPath, '-dpdf') ; end % ------------------------------------------------------------------------- function info = updateError(opts, info, net, res, speed) % ------------------------------------------------------------------------- predictions = gather(res(end-1).x) ; sz = size(predictions) ; n = prod(sz(1:2)) ; labels = net.layers{end}.class ; info.objective(end) = info.objective(end) + sum(double(gather(res(end).x))) ; info.speed(end) = info.speed(end) + speed ; switch opts.errorType case 'multiclass' [~,predictions] = sort(predictions, 3, 'descend') ; error = ~bsxfun(@eq, predictions, reshape(labels, 1, 1, 1, [])) ; info.error(end) = info.error(end) +.... sum(sum(sum(error(:,:,1,:))))/n ; info.topFiveError(end) = info.topFiveError(end) + ... sum(sum(sum(min(error(:,:,1:5,:),[],3))))/n ; case 'binary' error = bsxfun(@times, predictions, labels) < 0 ; info.error(end) = info.error(end) + sum(error(:))/n ; end
github
akileshbadrinaaraayanan/IITH-master
get_dcnn_features.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/get_dcnn_features.m
5,754
utf_8
75a8a8a1052928aa38fc0e3a6965005c
function code = get_dcnn_features(net, im, varargin) % GET_DCNN_FEATURES Get convolutional features for an image region % This function extracts the DCNN (CNN+FV) for an image. % These can be used as SIFT replacement in e.g. a Fisher Vector. % opts.useSIFT = false ; opts.crop = true ; %opts.scales = 2.^(1.5:-.5:-3); % as in CVPR14 submission opts.scales = 2; opts.encoder = [] ; opts.numSpatialSubdivisions = 1 ; opts.maxNumLocalDescriptorsReturned = +inf ; opts = vl_argparse(opts, varargin) ; % Find geometric parameters of the representation. x is set to the % leftmost pixel of the receptive field of the lefmost feature at % the last level of the network. This is computed by backtracking % from the last layer. Then we obtain a map % % x(u) = offset + stride * u % % from a feature index u to pixel coordinate v of the center of the % receptive field. if isempty(net) keepAspect = true; else keepAspect = net.normalization.keepAspect; end if opts.useSIFT binSize = 8; offset = 1 + 3/2 * binSize ; stride = 4; border = binSize*2 ; imageSize = [224 224]; else info = vl_simplenn_display(net) ; x=1 ; for l=numel(net.layers):-1:1 x=(x-1)*info.stride(2,l)-info.pad(2,l)+1 ; end offset = round(x + info.receptiveField(end)/2 - 0.5); stride = prod(info.stride(1,:)) ; border = round(info.receptiveField(end)/2+1) ; averageColour = mean(mean(net.normalization.averageImage,1),2) ; imageSize = net.normalization.imageSize; end if ~iscell(im) im = {im} ; end numNull = 0 ; numReg = 0 ; % for each image for k=1:numel(im) im_cropped = imresize(single(im{k}), imageSize([2 1]), 'bilinear'); crop_h = size(im_cropped,1) ; crop_w = size(im_cropped,2) ; psi = cell(1, numel(opts.scales)) ; loc = cell(1, numel(opts.scales)) ; res = [] ; % for each scale for s=1:numel(opts.scales) if min(crop_h,crop_w) * opts.scales(s) < border, continue ; end if sqrt(crop_h*crop_w) * opts.scales(s) > 1024, continue ; end % resize the cropped image and extract features everywhere if keepAspect w = size(im{k},2) ; h = size(im{k},1) ; factor = [imageSize(1)/h,imageSize(2)/w]; factor = max(factor)*opts.scales(s) ; %if any(abs(factor - 1) > 0.0001) im_resized = imresize(single(im{k}), ... 'scale', factor, ... 'method', 'bilinear') ; %end w = size(im_resized,2) ; h = size(im_resized,1) ; im_resized = imcrop(im_resized, [fix((w-imageSize(1)*opts.scales(s))/2)+1, fix((h-imageSize(2)*opts.scales(s))/2)+1,... round(imageSize(1)*opts.scales(s))-1, round(imageSize(2)*opts.scales(s))-1]); else im_resized = imresize(single(im{k}), round(imageSize([2 1])*opts.scales(s)), 'bilinear'); end % im_resized = imresize(im_cropped, opts.scales(s)) ; if opts.useSIFT [frames,descrs] = vl_dsift(mean(im_resized,3), ... 'size', binSize, ... 'step', stride, ... 'fast', 'floatdescriptors') ; ur = unique(frames(1,:)) ; vr = unique(frames(2,:)) ; [u,v] = meshgrid(ur,vr) ; %assert(isequal([u(:)';v(:)'], frames)) ; else im_resized = bsxfun(@minus, im_resized, averageColour) ; if net.useGpu im_resized = gpuArray(im_resized) ; end res = vl_simplenn(net, im_resized, [], res, ... 'conserveMemory', true, 'sync', true) ; w = size(res(end).x,2) ; h = size(res(end).x,1) ; descrs = permute(gather(res(end).x), [3 1 2]) ; descrs = reshape(descrs, size(descrs,1), []) ; [u,v] = meshgrid(... offset + (0:w-1) * stride, ... offset + (0:h-1) * stride) ; end u_ = (u - 1) / opts.scales(s) + 1 ; v_ = (v - 1) / opts.scales(s) + 1 ; loc_ = [u_(:)';v_(:)'] ; psi{s} = descrs; loc{s} = loc_; end % Concatenate features from all scales for r = 1:numel(psi) code{k} = cat(2, psi{:}) ; codeLoc{k} = cat(2, zeros(2,0), loc{:}) ; numReg = numReg + 1 ; numNull = numNull + isempty(code{k}) ; end end if numNull > 0 fprintf('%s: %d out of %d regions with null DCNN descriptor\n', ... mfilename, numNull, numReg) ; end % at this point code{i} contains all local featrues for image i if isempty(opts.encoder) % no gmm: return the local descriptors, but not too many! rng(0) ; for k=1:numel(code) code{k} = vl_colsubset(code{k}, opts.maxNumLocalDescriptorsReturned) ; end else % FV encoding for k=1:numel(code) descrs = opts.encoder.projection * bsxfun(@minus, code{k}, ... opts.encoder.projectionCenter) ; if opts.encoder.renormalize descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ; end tmp = {} ; break_u = get_intervals(codeLoc{k}(1,:), opts.numSpatialSubdivisions) ; break_v = get_intervals(codeLoc{k}(2,:), opts.numSpatialSubdivisions) ; for spu = 1:opts.numSpatialSubdivisions for spv = 1:opts.numSpatialSubdivisions sel = ... break_u(spu) <= codeLoc{k}(1,:) & codeLoc{k}(1,:) < break_u(spu+1) & ... break_v(spv) <= codeLoc{k}(2,:) & codeLoc{k}(2,:) < break_v(spv+1); tmp{end+1}= vl_fisher(descrs(:, sel), ... opts.encoder.means, ... opts.encoder.covariances, ... opts.encoder.priors, ... 'Improved') ; end end % normalization keeps norm = 1 code{k} = cat(1, tmp{:}) / opts.numSpatialSubdivisions ; end end function breaks = get_intervals(x,n) if isempty(x) breaks = ones(1,n+1) ; else x = sort(x(:)') ; breaks = x(round(linspace(1, numel(x), n+1))) ; end breaks(end) = +inf ;
github
akileshbadrinaaraayanan/IITH-master
imdb_bcnn_train.m
.m
IITH-master/Sem6/CS5190_Soft_Computing/cs13b1042_final_code/imdb_bcnn_train.m
17,253
utf_8
0df08e6209d5478cefffaf69a7fc339d
function imdb_bcnn_train(imdb, opts, varargin) % Train a bilinear CNN model on a dataset supplied by imdb % Copyright (C) 2015 Tsung-Yu Lin, Aruni RoyChowdhury, Subhransu Maji. % All rights reserved. % % This file is part of BCNN and is made available % under the terms of the BSD license (see the COPYING file). % % This file modified from IMDB_CNN_TRAIN of MatConvNet opts.lite = false ; opts.numFetchThreads = 0 ; opts.train.batchSize = opts.batchSize ; opts.train.numEpochs = opts.numEpochs ; opts.train.continue = true ; opts.train.useGpu = false ; opts.train.prefetch = false ; opts.train.learningRate = [0.001*ones(1, 10) 0.001*ones(1, 10) 0.001*ones(1,10)] ; opts.train.expDir = opts.expDir ; opts.train.dataAugmentation = opts.dataAugmentation; opts = vl_argparse(opts, varargin) ; opts.inittrain.weightDecay = 0 ; opts.inittrain.batchSize = 256 ; opts.inittrain.numEpochs = 300 ; opts.inittrain.continue = true ; opts.inittrain.useGpu = false ; opts.inittrain.prefetch = false ; opts.inittrain.learningRate = 0.001 ; opts.inittrain.expDir = fullfile(opts.expDir, 'init') ; opts.inittrain.nonftbcnnDir = fullfile(opts.expDir, 'nonftbcnn'); if(opts.useGpu) opts.train.useGpu = opts.useGpu; opts.inittrain.useGpu = opts.useGpu; end % initialize the network net = initializeNetwork(imdb, opts) ; shareWeights = ~isfield(net, 'netc'); if(~exist(fullfile(opts.expDir, 'fine-tuned-model'), 'dir')) mkdir(fullfile(opts.expDir, 'fine-tuned-model')) end if(shareWeights) % fine-tuning the symmetric B-CNN fn = getBatchWrapper(net.normalization, opts.numFetchThreads) ; [net,info] = bcnn_train_sw(net, imdb, fn, opts.train, 'conserveMemory', true, 'scale', opts.bcnnScale, 'momentum', opts.momentum) ; net = vl_simplenn_move(net, 'cpu'); saveNetwork(fullfile(opts.expDir, 'fine-tuned-model', 'final-model.mat'), net); else % fine-tuning the asymmetric B-CNN norm_struct(1) = net.neta.normalization; norm_struct(2) = net.netb.normalization; fn = getBatchWrapper(norm_struct, opts.numFetchThreads) ; % fn = getBatchWrapper(net.neta.normalization, opts.numFetchThreads) ; [net,info] = bcnn_train(net, fn, imdb, opts.train, 'conserveMemory', true, 'scale', opts.bcnnScale, 'momentum', opts.momentum) ; net.neta = vl_simplenn_move(net.neta, 'cpu'); net.netb = vl_simplenn_move(net.netb, 'cpu'); saveNetwork(fullfile(opts.expDir, 'fine-tuned-model', 'final-model-neta.mat'), net.neta); saveNetwork(fullfile(opts.expDir, 'fine-tuned-model', 'final-model-netb.mat'), net.netb); end % ------------------------------------------------------------------------- function saveNetwork(fileName, net) % ------------------------------------------------------------------------- layers = net.layers; % % % Replace the last layer with softmax % layers{end}.type = 'softmax'; % layers{end}.name = 'prob'; % Remove fields corresponding to training parameters ignoreFields = {'filtersMomentum', ... 'biasesMomentum',... 'filtersLearningRate',... 'biasesLearningRate',... 'filtersWeightDecay',... 'biasesWeightDecay',... 'class'}; for i = 1:length(layers), layers{i} = rmfield(layers{i}, ignoreFields(isfield(layers{i}, ignoreFields))); end classes = net.classes; normalization = net.normalization; save(fileName, 'layers', 'classes', 'normalization', '-v7.3'); % ------------------------------------------------------------------------- function fn = getBatchWrapper(opts, numThreads) % ------------------------------------------------------------------------- fn = @(imdb,batch,augmentation, scale) getBatch(imdb, batch, augmentation, scale, opts, numThreads) ; % ------------------------------------------------------------------------- function [im,labels] = getBatch(imdb, batch, augmentation, scale, opts, numThreads) % ------------------------------------------------------------------------- images = strcat([imdb.imageDir '/'], imdb.images.name(batch)) ; im = imdb_get_batch_bcnn(images, opts, ... 'numThreads', numThreads, ... 'prefetch', nargout == 0, 'augmentation', augmentation, 'scale', scale); labels = imdb.images.label(batch) ; numAugments = numel(im{1})/numel(batch); labels = reshape(repmat(labels, numAugments, 1), 1, numel(im{1})); function [im,labels] = getBatch_bcnn_fromdisk(imdb, batch, opts, numThreads) % ------------------------------------------------------------------------- im = cell(1, numel(batch)); for i=1:numel(batch) load(fullfile(imdb.imageDir, imdb.images.name{batch(i)})); im{i} = code; end im = cat(2, im{:}); im = reshape(im, 1, 1, size(im,1), size(im, 2)); labels = imdb.images.label(batch) ; function net = initializeNetwork(imdb, opts) % ------------------------------------------------------------------------- % get encoder setting encoderOpts.type = 'bcnn'; encoderOpts.modela = []; encoderOpts.layera = 14; encoderOpts.modelb = []; encoderOpts.layerb = 14; encoderOpts.shareWeight = false; encoderOpts = vl_argparse(encoderOpts, opts.encoders{1}.opts); scal = 1 ; init_bias = 0.1; numClass = length(imdb.classes.name); %% the case using two networks if ~encoderOpts.shareWeight assert(~isempty(encoderOpts.modela) && ~isempty(encoderOpts.modelb), 'at least one of the network is not specified') % load the pre-trained models encoder.neta = load(encoderOpts.modela); encoder.neta.layers = encoder.neta.layers(1:encoderOpts.layera); encoder.netb = load(encoderOpts.modelb); encoder.netb.layers = encoder.netb.layers(1:encoderOpts.layerb); encoder.regionBorder = 0.05; encoder.type = 'bcnn'; encoder.normalization = 'sqrt_L2'; % move models to GPU if opts.useGpu encoder.neta = vl_simplenn_move(encoder.neta, 'gpu') ; encoder.netb = vl_simplenn_move(encoder.netb, 'gpu') ; encoder.neta.useGpu = true ; encoder.netb.useGpu = true ; else encoder.neta = vl_simplenn_move(encoder.neta, 'cpu') ; encoder.netb = vl_simplenn_move(encoder.netb, 'cpu') ; encoder.neta.useGpu = false ; encoder.netb.useGpu = false ; end % set the bcnn_net structure net.neta = encoder.neta; net.netb = encoder.netb; net.neta.normalization.keepAspect = opts.keepAspect; net.netb.normalization.keepAspect = opts.keepAspect; netc.layers = {}; % get the bcnn feature dimension for i=numel(net.neta.layers):-1:1 if strcmp(net.neta.layers{i}.type, 'conv') idx = i; break; end end ch1 = numel(net.neta.layers{idx}.biases); for i=numel(net.netb.layers):-1:1 if strcmp(net.netb.layers{i}.type, 'conv') idx = i; break; end end ch2 = numel(net.netb.layers{idx}.biases); dim = ch1*ch2; % randomly initialize the softmax layer initialW = 0.001/scal *randn(1,1,dim, numClass,'single'); initialBias = init_bias.*ones(1, numClass, 'single'); netc.layers = {}; net.netc.layers = {}; net.netc.layers{end+1} = struct('type', 'sqrt'); net.netc.layers{end+1} = struct('type', 'l2norm'); netc.layers{end+1} = struct('type', 'conv', ... 'filters', initialW, ... 'biases', initialBias, ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 1000, ... 'biasesLearningRate', 1000, ... 'filtersWeightDecay', 0, ... 'biasesWeightDecay', 0) ; netc.layers{end+1} = struct('type', 'softmaxloss') ; % logistic regression for the softmax layers if(opts.bcnnLRinit) if exist(fullfile(opts.expDir, 'initial_fc.mat')) load(fullfile(opts.expDir, 'initial_fc.mat'), 'netc') ; else trainIdx = find(ismember(imdb.images.set, [1 2])); testIdx = find(ismember(imdb.images.set, 3)); % compute and cache the bilinear cnn features if ~exist(opts.inittrain.nonftbcnnDir) mkdir(opts.inittrain.nonftbcnnDir) batchSize = 10000; for b=1:ceil(numel(trainIdx)/batchSize) idxEnd = min(numel(trainIdx), b*batchSize); idx = trainIdx((b-1)*batchSize+1:idxEnd); codeCell = encoder_extract_for_images(encoder, imdb, imdb.images.id(idx), 'concatenateCode', false, 'scale', opts.bcnnScale); for i=1:numel(codeCell) code = codeCell{i}; savefast(fullfile(opts.inittrain.nonftbcnnDir, ['bcnn_nonft_', num2str(idx(i), '%05d')]), 'code'); end end end bcnndb = imdb; tempStr = sprintf('%05d\t', trainIdx); tempStr = textscan(tempStr, '%s', 'delimiter', '\t'); bcnndb.images.name = strcat('bcnn_nonft_', tempStr{1}'); bcnndb.images.id = bcnndb.images.id(trainIdx); bcnndb.images.label = bcnndb.images.label(trainIdx); bcnndb.images.set = bcnndb.images.set(trainIdx); bcnndb.imageDir = opts.inittrain.nonftbcnnDir; %train logistic regression [netc, info] = cnn_train(netc, bcnndb, @getBatch_bcnn_fromdisk, opts.inittrain, ... 'batchSize', opts.inittrain.batchSize, 'weightDecay', opts.inittrain.weightDecay, ... 'conserveMemory', true, 'expDir', opts.inittrain.expDir); save(fullfile(opts.expDir, 'initial_fc.mat'), 'netc', '-v7.3') ; end end for i=1:numel(netc.layers) net.netc.layers{end+1} = netc.layers{i}; end else %% the case with shared weights assert(strcmp(encoderOpts.modela, encoderOpts.modelb), 'neta and netb are required to be the same'); assert(~isempty(encoderOpts.modela), 'network is not specified'); net = load(encoderOpts.modela); % Load model if specified net.normalization.keepAspect = opts.keepAspect; % truncate the network at the last layer whose output is combined with another % layer's output to form the bcnn feature maxLayer = max(encoderOpts.layera, encoderOpts.layerb); net.layers = net.layers(1:maxLayer); % get the bcnn feature dimension for i=encoderOpts.layera:-1:1 if strcmp(net.layers{i}.type, 'conv') idx = i; break; end end mapSize1 = numel(net.layers{idx}.biases); for i=encoderOpts.layerb:-1:1 if strcmp(net.layers{i}.type, 'conv') idx = i; break; end end mapSize2 = numel(net.layers{idx}.biases); % stack bilinearpool, normalization, and softmax layers if(encoderOpts.layera==encoderOpts.layerb) net.layers{end+1} = struct('type', 'bilinearpool'); else net.layers{end+1} = struct('type', 'bilinearclpool', 'layer1', encoderOpts.layera, 'layer2', encoderOpts.layerb); end net.layers{end+1} = struct('type', 'sqrt'); net.layers{end+1} = struct('type', 'l2norm'); initialW = 0.001/scal * randn(1,1,mapSize1*mapSize2,numClass,'single'); initialBias = init_bias.*ones(1, numClass, 'single'); netc.layers = {}; netc.layers{end+1} = struct('type', 'conv', ... 'filters', initialW, ... 'biases', initialBias, ... 'stride', 1, ... 'pad', 0, ... 'filtersLearningRate', 1000, ... 'biasesLearningRate', 1000, ... 'filtersWeightDecay', 0, ... 'biasesWeightDecay', 0) ; netc.layers{end+1} = struct('type', 'softmaxloss') ; % logistic regression for the softmax layers if(opts.bcnnLRinit) netInit = net; if opts.train.useGpu netInit = vl_simplenn_move(netInit, 'gpu') ; end train = find(imdb.images.set==1|imdb.images.set==2); batchSize = 64; getBatchFn = getBatchWrapper(netInit.normalization, opts.numFetchThreads); if ~exist(opts.inittrain.nonftbcnnDir, 'dir') mkdir(opts.inittrain.nonftbcnnDir) % compute and cache the bilinear cnn features for t=1:batchSize:numel(train) fprintf('Initialization: extracting bcnn feature of batch %d/%d\n', ceil(t/batchSize), ceil(numel(train)/batchSize)); batch = train(t:min(numel(train), t+batchSize-1)); [im, labels] = getBatchFn(imdb, batch, opts.dataAugmentation{1}, opts.bcnnScale) ; if opts.train.prefetch nextBatch = train(t+batchSize:min(t+2*batchSize-1, numel(train))) ; getBatcFn(imdb, nextBatch, opts.dataAugmentation{1}, opts.bcnnScale) ; end im = im{1}; im = cat(4, im{:}); if opts.train.useGpu im = gpuArray(im) ; end net.layers{end}.class = labels ; res = [] ; res = vl_bilinearnn(netInit, im, [], res, ... 'disableDropout', true, ... 'conserveMemory', true, ... 'sync', true) ; codeb = squeeze(gather(res(end).x)); for i=1:numel(batch) code = codeb(:,i); savefast(fullfile(opts.inittrain.nonftbcnnDir, ['bcnn_nonft_', num2str(batch(i), '%05d')]), 'code'); end end end clear code res netInit if exist(fullfile(opts.expDir, 'initial_fc.mat'), 'file') load(fullfile(opts.expDir, 'initial_fc.mat'), 'netc') ; else bcnndb = imdb; tempStr = sprintf('%05d\t', train); tempStr = textscan(tempStr, '%s', 'delimiter', '\t'); bcnndb.images.name = strcat('bcnn_nonft_', tempStr{1}'); bcnndb.images.id = bcnndb.images.id(train); bcnndb.images.label = bcnndb.images.label(train); bcnndb.images.set = bcnndb.images.set(train); bcnndb.imageDir = opts.inittrain.nonftbcnnDir; %train logistic regression [netc, info] = cnn_train(netc, bcnndb, @getBatch_bcnn_fromdisk, opts.inittrain, ... 'batchSize', opts.inittrain.batchSize, 'weightDecay', opts.inittrain.weightDecay, ... 'conserveMemory', true, 'expDir', opts.inittrain.expDir); save(fullfile(opts.expDir, 'initial_fc.mat'), 'netc', '-v7.3') ; end end for i=1:numel(netc.layers) net.layers{end+1} = netc.layers{i}; end % Rename classes net.classes.name = imdb.classes.name; net.classes.description = imdb.classes.name; end function code = encoder_extract_for_images(encoder, imdb, imageIds, varargin) % ------------------------------------------------------------------------- opts.batchSize = 128 ; opts.maxNumLocalDescriptorsReturned = 500 ; opts.concatenateCode = true; opts.scale = 2; opts = vl_argparse(opts, varargin) ; [~,imageSel] = ismember(imageIds, imdb.images.id) ; imageIds = unique(imdb.images.id(imageSel)) ; n = numel(imageIds) ; % prepare batches n = ceil(numel(imageIds)/opts.batchSize) ; batches = mat2cell(1:numel(imageIds), 1, [opts.batchSize * ones(1, n-1), numel(imageIds) - opts.batchSize*(n-1)]) ; batchResults = cell(1, numel(batches)) ; % just use as many workers as are already available numWorkers = matlabpool('size') ; for b = numel(batches):-1:1 batchResults{b} = get_batch_results(imdb, imageIds, batches{b}, ... encoder, opts.maxNumLocalDescriptorsReturned, opts.scale) ; end code = cell(size(imageIds)) ; for b = 1:numel(batches) m = numel(batches{b}); for j = 1:m k = batches{b}(j) ; code{k} = batchResults{b}.code{j}; end end if opts.concatenateCode clear batchResults code = cat(2, code{:}) ; end function result = get_batch_results(imdb, imageIds, batch, encoder, maxn, scale) % ------------------------------------------------------------------------- m = numel(batch) ; im = cell(1, m) ; task = getCurrentTask() ; if ~isempty(task), tid = task.ID ; else tid = 1 ; end for i = 1:m fprintf('Task: %03d: encoder: extract features: image %d of %d\n', tid, batch(i), numel(imageIds)) ; im{i} = imread(fullfile(imdb.imageDir, imdb.images.name{imdb.images.id == imageIds(batch(i))})); if size(im{i}, 3) == 1, im{i} = repmat(im{i}, [1 1 3]);, end; %grayscale image end if ~isfield(encoder, 'numSpatialSubdivisions') encoder.numSpatialSubdivisions = 1 ; end code_ = get_bcnn_features(encoder.neta, encoder.netb,... im, ... 'regionBorder', encoder.regionBorder, ... 'normalization', encoder.normalization, ... 'scales', scale); result.code = code_ ;