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
|
songyouwei/coursera-machine-learning-assignments-master
|
loadubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex7/ex7/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
saveubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex7/ex7/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submit.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/submit.m
| 1,765 |
utf_8
|
b1804fe5854d9744dca981d250eda251
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance';
conf.itemName = 'Regularized Linear Regression and Bias/Variance';
conf.partArrays = { ...
{ ...
'1', ...
{ 'linearRegCostFunction.m' }, ...
'Regularized Linear Regression Cost Function', ...
}, ...
{ ...
'2', ...
{ 'linearRegCostFunction.m' }, ...
'Regularized Linear Regression Gradient', ...
}, ...
{ ...
'3', ...
{ 'learningCurve.m' }, ...
'Learning Curve', ...
}, ...
{ ...
'4', ...
{ 'polyFeatures.m' }, ...
'Polynomial Feature Mapping', ...
}, ...
{ ...
'5', ...
{ 'validationCurve.m' }, ...
'Validation Curve', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)'];
y = sin(1:3:30)';
Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)'];
yval = sin(1:10)';
if partId == '1'
[J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', J);
elseif partId == '2'
[J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5);
out = sprintf('%0.5f ', grad);
elseif partId == '3'
[error_train, error_val] = ...
learningCurve(X, y, Xval, yval, 1);
out = sprintf('%0.5f ', [error_train(:); error_val(:)]);
elseif partId == '4'
[X_poly] = polyFeatures(X(2,:)', 8);
out = sprintf('%0.5f ', X_poly);
elseif partId == '5'
[lambda_vec, error_train, error_val] = ...
validationCurve(X, y, Xval, yval);
out = sprintf('%0.5f ', ...
[lambda_vec(:); error_train(:); error_val(:)]);
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submitWithConfiguration.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
savejson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
saveubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex5/ex5/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submit.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/submit.m
| 1,567 |
utf_8
|
1dba733a05282b2db9f2284548483b81
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'multi-class-classification-and-neural-networks';
conf.itemName = 'Multi-class Classification and Neural Networks';
conf.partArrays = { ...
{ ...
'1', ...
{ 'lrCostFunction.m' }, ...
'Regularized Logistic Regression', ...
}, ...
{ ...
'2', ...
{ 'oneVsAll.m' }, ...
'One-vs-All Classifier Training', ...
}, ...
{ ...
'3', ...
{ 'predictOneVsAll.m' }, ...
'One-vs-All Classifier Prediction', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Neural Network Prediction Function' ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxdata)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ...
1 1 ; 1 2 ; 2 1 ; 2 2 ; ...
-1 1 ; -1 2 ; -2 1 ; -2 2 ; ...
1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ];
ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]';
t1 = sin(reshape(1:2:24, 4, 3));
t2 = cos(reshape(1:2:40, 4, 5));
if partId == '1'
[J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', J);
out = [out sprintf('%0.5f ', grad)];
elseif partId == '2'
out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1));
elseif partId == '3'
out = sprintf('%0.5f ', predictOneVsAll(t1, Xm));
elseif partId == '4'
out = sprintf('%0.5f ', predict(t1, t2, Xm));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submitWithConfiguration.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
savejson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
saveubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex3/ex3/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submit.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/submit.m
| 2,135 |
utf_8
|
eebb8c0a1db5a4df20b4c858603efad6
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'anomaly-detection-and-recommender-systems';
conf.itemName = 'Anomaly Detection and Recommender Systems';
conf.partArrays = { ...
{ ...
'1', ...
{ 'estimateGaussian.m' }, ...
'Estimate Gaussian Parameters', ...
}, ...
{ ...
'2', ...
{ 'selectThreshold.m' }, ...
'Select Threshold', ...
}, ...
{ ...
'3', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Cost', ...
}, ...
{ ...
'4', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Gradient', ...
}, ...
{ ...
'5', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Cost', ...
}, ...
{ ...
'6', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
n_u = 3; n_m = 4; n = 5;
X = reshape(sin(1:n_m*n), n_m, n);
Theta = reshape(cos(1:n_u*n), n_u, n);
Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
R = Y > 0.5;
pval = [abs(Y(:)) ; 0.001; 1];
Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed
yval = [R(:) ; 1; 0];
params = [X(:); Theta(:)];
if partId == '1'
[mu sigma2] = estimateGaussian(X);
out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
elseif partId == '2'
[bestEpsilon bestF1] = selectThreshold(yval, pval);
out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
elseif partId == '3'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', J(:));
elseif partId == '4'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', grad(:));
elseif partId == '5'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', J(:));
elseif partId == '6'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', grad(:));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submitWithConfiguration.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
savejson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
saveubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex8/ex8/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submit.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/submit.m
| 1,876 |
utf_8
|
8d1c467b830a89c187c05b121cb8fbfd
|
function submit()
addpath('./lib');
conf.assignmentSlug = 'linear-regression';
conf.itemName = 'Linear Regression with Multiple Variables';
conf.partArrays = { ...
{ ...
'1', ...
{ 'warmUpExercise.m' }, ...
'Warm-up Exercise', ...
}, ...
{ ...
'2', ...
{ 'computeCost.m' }, ...
'Computing Cost (for One Variable)', ...
}, ...
{ ...
'3', ...
{ 'gradientDescent.m' }, ...
'Gradient Descent (for One Variable)', ...
}, ...
{ ...
'4', ...
{ 'featureNormalize.m' }, ...
'Feature Normalization', ...
}, ...
{ ...
'5', ...
{ 'computeCostMulti.m' }, ...
'Computing Cost (for Multiple Variables)', ...
}, ...
{ ...
'6', ...
{ 'gradientDescentMulti.m' }, ...
'Gradient Descent (for Multiple Variables)', ...
}, ...
{ ...
'7', ...
{ 'normalEqn.m' }, ...
'Normal Equations', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId)
% Random Test Cases
X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))'];
Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2));
X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25];
Y2 = Y1.^0.5 + Y1;
if partId == '1'
out = sprintf('%0.5f ', warmUpExercise());
elseif partId == '2'
out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]'));
elseif partId == '3'
out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10));
elseif partId == '4'
out = sprintf('%0.5f ', featureNormalize(X2(:,2:4)));
elseif partId == '5'
out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]'));
elseif partId == '6'
out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10));
elseif partId == '7'
out = sprintf('%0.5f ', normalEqn(X2, Y2));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
submitWithConfiguration.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/lib/submitWithConfiguration.m
| 5,562 |
utf_8
|
4ac719ea6570ac228ea6c7a9c919e3f5
|
function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
savejson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/lib/jsonlab/savejson.m
| 17,462 |
utf_8
|
861b534fc35ffe982b53ca3ca83143bf
|
function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/lib/jsonlab/loadjson.m
| 18,732 |
ibm852
|
ab98cf173af2d50bbe8da4d6db252a20
|
function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
loadubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/lib/jsonlab/loadubjson.m
| 15,574 |
utf_8
|
5974e78e71b81b1e0f76123784b951a4
|
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github
|
songyouwei/coursera-machine-learning-assignments-master
|
saveubjson.m
|
.m
|
coursera-machine-learning-assignments-master/machine-learning-ex1/ex1/lib/jsonlab/saveubjson.m
| 16,123 |
utf_8
|
61d4f51010aedbf97753396f5d2d9ec0
|
function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github
|
yuanxy92/ConvexOptimization-master
|
l1_ls_nonneg.m
|
.m
|
ConvexOptimization-master/3rd/l1_ls_matlab/l1_ls_nonneg.m
| 7,985 |
utf_8
|
a65d1f604b6bb3e700f967b4eed0ba79
|
function [x,status,history] = l1_ls_nonneg(A,varargin)
%
% l1-Regularized Least Squares Problem Solver
%
% l1_ls solves problems of the following form:
%
% minimize ||A*x-y||^2 + lambda*sum(x_i),
% subject to x_i >= 0, i=1,...,n
%
% where A and y are problem data and x is variable (described below).
%
% CALLING SEQUENCES
% [x,status,history] = l1_ls_nonneg(A,y,lambda [,tar_gap[,quiet]])
% [x,status,history] = l1_ls_nonneg(A,At,m,n,y,lambda, [,tar_gap,[,quiet]]))
%
% if A is a matrix, either sequence can be used.
% if A is an object (with overloaded operators), At, m, n must be
% provided.
%
% INPUT
% A : mxn matrix; input data. columns correspond to features.
%
% At : nxm matrix; transpose of A.
% m : number of examples (rows) of A
% n : number of features (column)s of A
%
% y : m vector; outcome.
% lambda : positive scalar; regularization parameter
%
% tar_gap : relative target duality gap (default: 1e-3)
% quiet : boolean; suppress printing message when true (default: false)
%
% (advanced arguments)
% eta : scalar; parameter for PCG termination (default: 1e-3)
% pcgmaxi : scalar; number of maximum PCG iterations (default: 5000)
%
% OUTPUT
% x : n vector; classifier
% status : string; 'Solved' or 'Failed'
%
% history : matrix of history data. columns represent (truncated) Newton
% iterations; rows represent the following:
% - 1st row) gap
% - 2nd row) primal objective
% - 3rd row) dual objective
% - 4th row) step size
% - 5th row) pcg iterations
% - 6th row) pcg status flag
%
% USAGE EXAMPLES
% [x,status] = l1_ls_nonneg(A,y,lambda);
% [x,status] = l1_ls_nonneg(A,At,m,n,y,lambda,0.001);
%
% AUTHOR Kwangmoo Koh <[email protected]>
% UPDATE Apr 10 2008
%
% COPYRIGHT 2008 Kwangmoo Koh, Seung-Jean Kim, and Stephen Boyd
%------------------------------------------------------------
% INITIALIZE
%------------------------------------------------------------
% IPM PARAMETERS
MU = 2; % updating parameter of t
MAX_NT_ITER = 400; % maximum IPM (Newton) iteration
% LINE SEARCH PARAMETERS
ALPHA = 0.01; % minimum fraction of decrease in the objective
BETA = 0.5; % stepsize decrease factor
MAX_LS_ITER = 100; % maximum backtracking line search iteration
% VARIABLE ARGUMENT HANDLING
% if the second argument is a matrix or an operator, the calling sequence is
% l1_ls(A,At,y,lambda,m,n [,tar_gap,[,quiet]]))
% if the second argument is a vector, the calling sequence is
% l1_ls(A,y,lambda [,tar_gap[,quiet]])
if ( (isobject(varargin{1}) || ~isvector(varargin{1})) && nargin >= 6)
At = varargin{1};
m = varargin{2};
n = varargin{3};
y = varargin{4};
lambda = varargin{5};
varargin = varargin(6:end);
elseif (nargin >= 3)
At = A';
[m,n] = size(A);
y = varargin{1};
lambda = varargin{2};
varargin = varargin(3:end);
else
if (~quiet) disp('Insufficient input arguments'); end
x = []; status = 'Failed'; history = [];
return;
end
% VARIABLE ARGUMENT HANDLING
t0 = min(max(1,1/lambda),n/1e-3);
defaults = {1e-3,false,1e-3,5000,ones(n,1),t0};
given_args = ~cellfun('isempty',varargin);
defaults(given_args) = varargin(given_args);
[reltol,quiet,eta,pcgmaxi,x,t] = deal(defaults{:});
f = -x;
% RESULT/HISTORY VARIABLES
pobjs = [] ; dobjs = [] ; sts = [] ; pitrs = []; pflgs = [];
pobj = Inf; dobj =-Inf; s = Inf; pitr = 0 ; pflg = 0 ;
ntiter = 0; lsiter = 0; zntiter = 0; zlsiter = 0;
normg = 0; prelres = 0; dx = zeros(n,1);
% diagxtx = diag(At*A);
diagxtx = 2*ones(n,1);
if (~quiet) disp(sprintf('\nSolving a problem of size (m=%d, n=%d), with lambda=%.5e',...
m,n,lambda)); end
if (~quiet) disp('-----------------------------------------------------------------------------');end
if (~quiet) disp(sprintf('%5s %9s %15s %15s %13s %11s',...
'iter','gap','primobj','dualobj','step len','pcg iters')); end
%------------------------------------------------------------
% MAIN LOOP
%------------------------------------------------------------
for ntiter = 0:MAX_NT_ITER
z = A*x-y;
%------------------------------------------------------------
% CALCULATE DUALITY GAP
%------------------------------------------------------------
nu = 2*z;
minAnu = min(At*nu);
if (minAnu < -lambda)
nu = nu*lambda/(-minAnu);
end
pobj = z'*z+lambda*sum(x,1);
dobj = max(-0.25*nu'*nu-nu'*y,dobj);
gap = pobj - dobj;
pobjs = [pobjs pobj]; dobjs = [dobjs dobj]; sts = [sts s];
pflgs = [pflgs pflg]; pitrs = [pitrs pitr];
%------------------------------------------------------------
% STOPPING CRITERION
%------------------------------------------------------------
if (~quiet) disp(sprintf('%4d %12.2e %15.5e %15.5e %11.1e %8d',...
ntiter, gap, pobj, dobj, s, pitr)); end
if (gap/abs(dobj) < reltol)
status = 'Solved';
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
if (~quiet) disp('Absolute tolerance reached.'); end
%disp(sprintf('total pcg iters = %d\n',sum(pitrs)));
return;
end
%------------------------------------------------------------
% UPDATE t
%------------------------------------------------------------
if (s >= 0.5)
t = max(min(n*MU/gap, MU*t), t);
end
%------------------------------------------------------------
% CALCULATE NEWTON STEP
%------------------------------------------------------------
d1 = (1/t)./(x.^2);
% calculate gradient
gradphi = [At*(z*2)+lambda-(1/t)./x];
% calculate vectors to be used in the preconditioner
prb = diagxtx+d1;
% set pcg tolerance (relative)
normg = norm(gradphi);
pcgtol = min(1e-1,eta*gap/min(1,normg));
if (ntiter ~= 0 && pitr == 0) pcgtol = pcgtol*0.1; end
if 1
[dx,pflg,prelres,pitr,presvec] = ...
pcg(@AXfunc_l1_ls,-gradphi,pcgtol,pcgmaxi,@Mfunc_l1_ls,...
[],dx,A,At,d1,1./prb);
end
%dx = (2*A'*A+diag(d1))\(-gradphi);
if (pflg == 1) pitr = pcgmaxi; end
%------------------------------------------------------------
% BACKTRACKING LINE SEARCH
%------------------------------------------------------------
phi = z'*z+lambda*sum(x)-sum(log(-f))/t;
s = 1.0;
gdx = gradphi'*dx;
for lsiter = 1:MAX_LS_ITER
newx = x+s*dx;
newf = -newx;
if (max(newf) < 0)
newz = A*newx-y;
newphi = newz'*newz+lambda*sum(newx)-sum(log(-newf))/t;
if (newphi-phi <= ALPHA*s*gdx)
break;
end
end
s = BETA*s;
end
if (lsiter == MAX_LS_ITER) break; end % exit by BLS
x = newx; f = newf;
end
%------------------------------------------------------------
% ABNORMAL TERMINATION (FALL THROUGH)
%------------------------------------------------------------
if (lsiter == MAX_LS_ITER)
% failed in backtracking linesearch.
if (~quiet) disp('MAX_LS_ITER exceeded in BLS'); end
status = 'Failed';
elseif (ntiter == MAX_NT_ITER)
% fail to find the solution within MAX_NT_ITER
if (~quiet) disp('MAX_NT_ITER exceeded.'); end
status = 'Failed';
end
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
return;
%------------------------------------------------------------
% COMPUTE AX (PCG)
%------------------------------------------------------------
function [y] = AXfunc_l1_ls(x,A,At,d1,p1)
y = (At*((A*x)*2))+d1.*x;
%------------------------------------------------------------
% COMPUTE P^{-1}X (PCG)
%------------------------------------------------------------
function [y] = Mfunc_l1_ls(x,A,At,d1,p1)
y = p1.*x;
|
github
|
yuanxy92/ConvexOptimization-master
|
l1_ls.m
|
.m
|
ConvexOptimization-master/3rd/l1_ls_matlab/l1_ls.m
| 8,414 |
utf_8
|
592cd5d633c7f3e474bcad9309e4ea07
|
function [x,status,history] = l1_ls(A,varargin)
%
% l1-Regularized Least Squares Problem Solver
%
% l1_ls solves problems of the following form:
%
% minimize ||A*x-y||^2 + lambda*sum|x_i|,
%
% where A and y are problem data and x is variable (described below).
%
% CALLING SEQUENCES
% [x,status,history] = l1_ls(A,y,lambda [,tar_gap[,quiet]])
% [x,status,history] = l1_ls(A,At,m,n,y,lambda, [,tar_gap,[,quiet]]))
%
% if A is a matrix, either sequence can be used.
% if A is an object (with overloaded operators), At, m, n must be
% provided.
%
% INPUT
% A : mxn matrix; input data. columns correspond to features.
%
% At : nxm matrix; transpose of A.
% m : number of examples (rows) of A
% n : number of features (column)s of A
%
% y : m vector; outcome.
% lambda : positive scalar; regularization parameter
%
% tar_gap : relative target duality gap (default: 1e-3)
% quiet : boolean; suppress printing message when true (default: false)
%
% (advanced arguments)
% eta : scalar; parameter for PCG termination (default: 1e-3)
% pcgmaxi : scalar; number of maximum PCG iterations (default: 5000)
%
% OUTPUT
% x : n vector; classifier
% status : string; 'Solved' or 'Failed'
%
% history : matrix of history data. columns represent (truncated) Newton
% iterations; rows represent the following:
% - 1st row) gap
% - 2nd row) primal objective
% - 3rd row) dual objective
% - 4th row) step size
% - 5th row) pcg iterations
% - 6th row) pcg status flag
%
% USAGE EXAMPLES
% [x,status] = l1_ls(A,y,lambda);
% [x,status] = l1_ls(A,At,m,n,y,lambda,0.001);
%
% AUTHOR Kwangmoo Koh <[email protected]>
% UPDATE Apr 8 2007
%
% COPYRIGHT 2008 Kwangmoo Koh, Seung-Jean Kim, and Stephen Boyd
%------------------------------------------------------------
% INITIALIZE
%------------------------------------------------------------
% IPM PARAMETERS
MU = 2; % updating parameter of t
MAX_NT_ITER = 400; % maximum IPM (Newton) iteration
% LINE SEARCH PARAMETERS
ALPHA = 0.01; % minimum fraction of decrease in the objective
BETA = 0.5; % stepsize decrease factor
MAX_LS_ITER = 100; % maximum backtracking line search iteration
% VARIABLE ARGUMENT HANDLING
% if the second argument is a matrix or an operator, the calling sequence is
% l1_ls(A,At,y,lambda,m,n [,tar_gap,[,quiet]]))
% if the second argument is a vector, the calling sequence is
% l1_ls(A,y,lambda [,tar_gap[,quiet]])
if ( (isobject(varargin{1}) || ~isvector(varargin{1})) && nargin >= 6)
At = varargin{1};
m = varargin{2};
n = varargin{3};
y = varargin{4};
lambda = varargin{5};
varargin = varargin(6:end);
elseif (nargin >= 3)
At = A';
[m,n] = size(A);
y = varargin{1};
lambda = varargin{2};
varargin = varargin(3:end);
else
if (~quiet) disp('Insufficient input arguments'); end
x = []; status = 'Failed'; history = [];
return;
end
% VARIABLE ARGUMENT HANDLING
t0 = min(max(1,1/lambda),2*n/1e-3);
defaults = {1e-3,false,1e-3,5000,zeros(n,1),ones(n,1),t0};
given_args = ~cellfun('isempty',varargin);
defaults(given_args) = varargin(given_args);
[reltol,quiet,eta,pcgmaxi,x,u,t] = deal(defaults{:});
f = [x-u;-x-u];
% RESULT/HISTORY VARIABLES
pobjs = [] ; dobjs = [] ; sts = [] ; pitrs = []; pflgs = [];
pobj = Inf; dobj =-Inf; s = Inf; pitr = 0 ; pflg = 0 ;
ntiter = 0; lsiter = 0; zntiter = 0; zlsiter = 0;
normg = 0; prelres = 0; dxu = zeros(2*n,1);
% diagxtx = diag(At*A);
diagxtx = 2*ones(n,1);
if (~quiet) disp(sprintf('\nSolving a problem of size (m=%d, n=%d), with lambda=%.5e',...
m,n,lambda)); end
if (~quiet) disp('-----------------------------------------------------------------------------');end
if (~quiet) disp(sprintf('%5s %9s %15s %15s %13s %11s',...
'iter','gap','primobj','dualobj','step len','pcg iters')); end
%------------------------------------------------------------
% MAIN LOOP
%------------------------------------------------------------
for ntiter = 0:MAX_NT_ITER
z = A*x-y;
%------------------------------------------------------------
% CALCULATE DUALITY GAP
%------------------------------------------------------------
nu = 2*z;
maxAnu = norm(At*nu,inf);
if (maxAnu > lambda)
nu = nu*lambda/maxAnu;
end
pobj = z'*z+lambda*norm(x,1);
dobj = max(-0.25*nu'*nu-nu'*y,dobj);
gap = pobj - dobj;
pobjs = [pobjs pobj]; dobjs = [dobjs dobj]; sts = [sts s];
pflgs = [pflgs pflg]; pitrs = [pitrs pitr];
%------------------------------------------------------------
% STOPPING CRITERION
%------------------------------------------------------------
if (~quiet) disp(sprintf('%4d %12.2e %15.5e %15.5e %11.1e %8d',...
ntiter, gap, pobj, dobj, s, pitr)); end
if (gap/dobj < reltol)
status = 'Solved';
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
if (~quiet) disp('Absolute tolerance reached.'); end
%disp(sprintf('total pcg iters = %d\n',sum(pitrs)));
return;
end
%------------------------------------------------------------
% UPDATE t
%------------------------------------------------------------
if (s >= 0.5)
t = max(min(2*n*MU/gap, MU*t), t);
end
%------------------------------------------------------------
% CALCULATE NEWTON STEP
%------------------------------------------------------------
q1 = 1./(u+x); q2 = 1./(u-x);
d1 = (q1.^2+q2.^2)/t; d2 = (q1.^2-q2.^2)/t;
% calculate gradient
gradphi = [At*(z*2)-(q1-q2)/t; lambda*ones(n,1)-(q1+q2)/t];
% calculate vectors to be used in the preconditioner
prb = diagxtx+d1;
prs = prb.*d1-(d2.^2);
% set pcg tolerance (relative)
normg = norm(gradphi);
pcgtol = min(1e-1,eta*gap/min(1,normg));
if (ntiter ~= 0 && pitr == 0) pcgtol = pcgtol*0.1; end
[dxu,pflg,prelres,pitr,presvec] = ...
pcg(@AXfunc_l1_ls,-gradphi,pcgtol,pcgmaxi,@Mfunc_l1_ls,...
[],dxu,A,At,d1,d2,d1./prs,d2./prs,prb./prs);
if (pflg == 1) pitr = pcgmaxi; end
dx = dxu(1:n);
du = dxu(n+1:end);
%------------------------------------------------------------
% BACKTRACKING LINE SEARCH
%------------------------------------------------------------
phi = z'*z+lambda*sum(u)-sum(log(-f))/t;
s = 1.0;
gdx = gradphi'*dxu;
for lsiter = 1:MAX_LS_ITER
newx = x+s*dx; newu = u+s*du;
newf = [newx-newu;-newx-newu];
if (max(newf) < 0)
newz = A*newx-y;
newphi = newz'*newz+lambda*sum(newu)-sum(log(-newf))/t;
if (newphi-phi <= ALPHA*s*gdx)
break;
end
end
s = BETA*s;
end
if (lsiter == MAX_LS_ITER) break; end % exit by BLS
x = newx; u = newu; f = newf;
end
%------------------------------------------------------------
% ABNORMAL TERMINATION (FALL THROUGH)
%------------------------------------------------------------
if (lsiter == MAX_LS_ITER)
% failed in backtracking linesearch.
if (~quiet) disp('MAX_LS_ITER exceeded in BLS'); end
status = 'Failed';
elseif (ntiter == MAX_NT_ITER)
% fail to find the solution within MAX_NT_ITER
if (~quiet) disp('MAX_NT_ITER exceeded.'); end
status = 'Failed';
end
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
return;
%------------------------------------------------------------
% COMPUTE AX (PCG)
%------------------------------------------------------------
function [y] = AXfunc_l1_ls(x,A,At,d1,d2,p1,p2,p3)
%
% y = hessphi*[x1;x2],
%
% where hessphi = [A'*A*2+D1 , D2;
% D2 , D1];
n = length(x)/2;
x1 = x(1:n);
x2 = x(n+1:end);
y = [(At*((A*x1)*2))+d1.*x1+d2.*x2; d2.*x1+d1.*x2];
%------------------------------------------------------------
% COMPUTE P^{-1}X (PCG)
%------------------------------------------------------------
function [y] = Mfunc_l1_ls(x,A,At,d1,d2,p1,p2,p3)
%
% y = P^{-1}*x,
%
n = length(x)/2;
x1 = x(1:n);
x2 = x(n+1:end);
y = [ p1.*x1-p2.*x2;...
-p2.*x1+p3.*x2];
|
github
|
yuanxy92/ConvexOptimization-master
|
l1_norm_ls_solver_pcg.m
|
.m
|
ConvexOptimization-master/homework4/l1_norm_ls_solver_pcg.m
| 8,430 |
utf_8
|
1c703e1d55264ccf9dfc48e4cce34520
|
function [x,status,history] = l1_norm_ls_solver_pcg(A,varargin)
%
% l1-Regularized Least Squares Problem Solver
%
% l1_ls solves problems of the following form:
%
% minimize ||A*x-y||^2 + lambda*sum|x_i|,
%
% where A and y are problem data and x is variable (described below).
%
% CALLING SEQUENCES
% [x,status,history] = l1_ls(A,y,lambda [,tar_gap[,quiet]])
% [x,status,history] = l1_ls(A,At,m,n,y,lambda, [,tar_gap,[,quiet]]))
%
% if A is a matrix, either sequence can be used.
% if A is an object (with overloaded operators), At, m, n must be
% provided.
%
% INPUT
% A : mxn matrix; input data. columns correspond to features.
%
% At : nxm matrix; transpose of A.
% m : number of examples (rows) of A
% n : number of features (column)s of A
%
% y : m vector; outcome.
% lambda : positive scalar; regularization parameter
%
% tar_gap : relative target duality gap (default: 1e-3)
% quiet : boolean; suppress printing message when true (default: false)
%
% (advanced arguments)
% eta : scalar; parameter for PCG termination (default: 1e-3)
% pcgmaxi : scalar; number of maximum PCG iterations (default: 5000)
%
% OUTPUT
% x : n vector; classifier
% status : string; 'Solved' or 'Failed'
%
% history : matrix of history data. columns represent (truncated) Newton
% iterations; rows represent the following:
% - 1st row) gap
% - 2nd row) primal objective
% - 3rd row) dual objective
% - 4th row) step size
% - 5th row) pcg iterations
% - 6th row) pcg status flag
%
% USAGE EXAMPLES
% [x,status] = l1_ls(A,y,lambda);
% [x,status] = l1_ls(A,At,m,n,y,lambda,0.001);
%
% AUTHOR Kwangmoo Koh <[email protected]>
% UPDATE Apr 8 2007
%
% COPYRIGHT 2008 Kwangmoo Koh, Seung-Jean Kim, and Stephen Boyd
%------------------------------------------------------------
% INITIALIZE
%------------------------------------------------------------
% IPM PARAMETERS
MU = 2; % updating parameter of t
MAX_NT_ITER = 400; % maximum IPM (Newton) iteration
% LINE SEARCH PARAMETERS
ALPHA = 0.01; % minimum fraction of decrease in the objective
BETA = 0.5; % stepsize decrease factor
MAX_LS_ITER = 100; % maximum backtracking line search iteration
% VARIABLE ARGUMENT HANDLING
% if the second argument is a matrix or an operator, the calling sequence is
% l1_ls(A,At,y,lambda,m,n [,tar_gap,[,quiet]]))
% if the second argument is a vector, the calling sequence is
% l1_ls(A,y,lambda [,tar_gap[,quiet]])
if ( (isobject(varargin{1}) || ~isvector(varargin{1})) && nargin >= 6)
At = varargin{1};
m = varargin{2};
n = varargin{3};
y = varargin{4};
lambda = varargin{5};
varargin = varargin(6:end);
elseif (nargin >= 3)
At = A';
[m,n] = size(A);
y = varargin{1};
lambda = varargin{2};
varargin = varargin(3:end);
else
if (~quiet) disp('Insufficient input arguments'); end
x = []; status = 'Failed'; history = [];
return;
end
% VARIABLE ARGUMENT HANDLING
t0 = min(max(1,1/lambda),2*n/1e-3);
defaults = {1e-3,false,1e-3,5000,zeros(n,1),ones(n,1),t0};
given_args = ~cellfun('isempty',varargin);
defaults(given_args) = varargin(given_args);
[reltol,quiet,eta,pcgmaxi,x,u,t] = deal(defaults{:});
f = [x-u;-x-u];
% RESULT/HISTORY VARIABLES
pobjs = [] ; dobjs = [] ; sts = [] ; pitrs = []; pflgs = [];
pobj = Inf; dobj =-Inf; s = Inf; pitr = 0 ; pflg = 0 ;
ntiter = 0; lsiter = 0; zntiter = 0; zlsiter = 0;
normg = 0; prelres = 0; dxu = zeros(2*n,1);
% diagxtx = diag(At*A);
diagxtx = 2*ones(n,1);
if (~quiet) disp(sprintf('\nSolving a problem of size (m=%d, n=%d), with lambda=%.5e',...
m,n,lambda)); end
if (~quiet) disp('-----------------------------------------------------------------------------');end
if (~quiet) disp(sprintf('%5s %9s %15s %15s %13s %11s',...
'iter','gap','primobj','dualobj','step len','pcg iters')); end
%------------------------------------------------------------
% MAIN LOOP
%------------------------------------------------------------
for ntiter = 0:MAX_NT_ITER
z = A*x-y;
%------------------------------------------------------------
% CALCULATE DUALITY GAP
%------------------------------------------------------------
nu = 2*z;
maxAnu = norm(At*nu,inf);
if (maxAnu > lambda)
nu = nu*lambda/maxAnu;
end
pobj = z'*z+lambda*norm(x,1);
dobj = max(-0.25*nu'*nu-nu'*y,dobj);
gap = pobj - dobj;
pobjs = [pobjs pobj]; dobjs = [dobjs dobj]; sts = [sts s];
pflgs = [pflgs pflg]; pitrs = [pitrs pitr];
%------------------------------------------------------------
% STOPPING CRITERION
%------------------------------------------------------------
if (~quiet) disp(sprintf('%4d %12.2e %15.5e %15.5e %11.1e %8d',...
ntiter, gap, pobj, dobj, s, pitr)); end
if (gap/dobj < reltol)
status = 'Solved';
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
if (~quiet) disp('Absolute tolerance reached.'); end
%disp(sprintf('total pcg iters = %d\n',sum(pitrs)));
return;
end
%------------------------------------------------------------
% UPDATE t
%------------------------------------------------------------
if (s >= 0.5)
t = max(min(2*n*MU/gap, MU*t), t);
end
%------------------------------------------------------------
% CALCULATE NEWTON STEP
%------------------------------------------------------------
q1 = 1./(u+x); q2 = 1./(u-x);
d1 = (q1.^2+q2.^2)/t; d2 = (q1.^2-q2.^2)/t;
% calculate gradient
gradphi = [At*(z*2)-(q1-q2)/t; lambda*ones(n,1)-(q1+q2)/t];
% calculate vectors to be used in the preconditioner
prb = diagxtx+d1;
prs = prb.*d1-(d2.^2);
% set pcg tolerance (relative)
normg = norm(gradphi);
pcgtol = min(1e-1,eta*gap/min(1,normg));
if (ntiter ~= 0 && pitr == 0) pcgtol = pcgtol*0.1; end
[dxu,pflg,prelres,pitr,presvec] = ...
pcg(@AXfunc_l1_ls,-gradphi,pcgtol,pcgmaxi,@Mfunc_l1_ls,...
[],dxu,A,At,d1,d2,d1./prs,d2./prs,prb./prs);
if (pflg == 1) pitr = pcgmaxi; end
dx = dxu(1:n);
du = dxu(n+1:end);
%------------------------------------------------------------
% BACKTRACKING LINE SEARCH
%------------------------------------------------------------
phi = z'*z+lambda*sum(u)-sum(log(-f))/t;
s = 1.0;
gdx = gradphi'*dxu;
for lsiter = 1:MAX_LS_ITER
newx = x+s*dx; newu = u+s*du;
newf = [newx-newu;-newx-newu];
if (max(newf) < 0)
newz = A*newx-y;
newphi = newz'*newz+lambda*sum(newu)-sum(log(-newf))/t;
if (newphi-phi <= ALPHA*s*gdx)
break;
end
end
s = BETA*s;
end
if (lsiter == MAX_LS_ITER) break; end % exit by BLS
x = newx; u = newu; f = newf;
end
%------------------------------------------------------------
% ABNORMAL TERMINATION (FALL THROUGH)
%------------------------------------------------------------
if (lsiter == MAX_LS_ITER)
% failed in backtracking linesearch.
if (~quiet) disp('MAX_LS_ITER exceeded in BLS'); end
status = 'Failed';
elseif (ntiter == MAX_NT_ITER)
% fail to find the solution within MAX_NT_ITER
if (~quiet) disp('MAX_NT_ITER exceeded.'); end
status = 'Failed';
end
history = [pobjs-dobjs; pobjs; dobjs; sts; pitrs; pflgs];
return;
%------------------------------------------------------------
% COMPUTE AX (PCG)
%------------------------------------------------------------
function [y] = AXfunc_l1_ls(x,A,At,d1,d2,p1,p2,p3)
%
% y = hessphi*[x1;x2],
%
% where hessphi = [A'*A*2+D1 , D2;
% D2 , D1];
n = length(x)/2;
x1 = x(1:n);
x2 = x(n+1:end);
y = [(At*((A*x1)*2))+d1.*x1+d2.*x2; d2.*x1+d1.*x2];
%------------------------------------------------------------
% COMPUTE P^{-1}X (PCG)
%------------------------------------------------------------
function [y] = Mfunc_l1_ls(x,A,At,d1,d2,p1,p2,p3)
%
% y = P^{-1}*x,
%
n = length(x)/2;
x1 = x(1:n);
x2 = x(n+1:end);
y = [ p1.*x1-p2.*x2;...
-p2.*x1+p3.*x2];
|
github
|
yuanxy92/ConvexOptimization-master
|
fast_deconv_bregman.m
|
.m
|
ConvexOptimization-master/MATLAB/blinddeconv/fast_deconv_bregman.m
| 3,048 |
utf_8
|
973e7fd7c8d796ae3710cba343daae82
|
function [g] = fast_deconv_bregman(f, k, lambda, alpha)
%
% fast solver for the non-blind deconvolution problem: min_g \lambda/2 |g \oplus k
% - f|^2. We use a splitting trick as
% follows: introduce a (vector) variable w, and rewrite the original
% problem as: min_{g,w,b} \lambda/2 |g \oplus k - g|^2 + \beta/2 |w -
% \nabla g - b|^2, and then we use alternations on g, w
% and b to update each one in turn. b is the Bregman variable. beta is
% fixed. An alternative is to use continuation but then we need to set a
% beta regime. Based on the NIPS 2009 paper of Krishnan and Fergus "Fast
% Image Deconvolution using Hyper-Laplacian Priors"
%
beta = 400;
initer_max = 1;
outiter_max = 20;
[m n] = size(f);
% initialize
g = f;
% make sure k is odd-sized
if ((mod(size(k, 1), 2) ~= 1) | (mod(size(k, 2), 2) ~= 1))
fprintf('Error - blur kernel k must be odd-sized.\n');
return;
end;
ks = floor((size(k, 1)-1)/2);
dx = [1 -1];
dy = dx';
dxt = fliplr(flipud(dx));
dyt = fliplr(flipud(dy));
[Ktf, KtK, DtD, Fdx, Fdy] = computeConstants(f, k, dx, dy);
gx = conv2(g, dx, 'valid');
gy = conv2(g, dy, 'valid');
fx = conv2(f, dx, 'valid');
fy = conv2(f, dy, 'valid');
ks = size(k, 1);
ks2 = floor(ks / 2);
% store some of the statistics
lcost = [];
pcost = [];
outiter = 0;
bx = zeros(size(gx));
by = zeros(size(gy));
wx = gx;
wy = gy;
totiter = 1;
gk = conv2(g, k, 'same');
lcost(totiter) = (lambda / 2) * norm(gk(:) - f(:))^2;
pcost(totiter) = sum((abs(gx(:)) .^ alpha));
pcost(totiter) = pcost(totiter) + sum((abs(gy(:)) .^ alpha));
for outiter = 1:outiter_max
fprintf('Outer iteration %d\n', outiter);
initer = 0;
for initer = 1:initer_max
totiter = totiter + 1;
if (alpha == 1)
tmpx = beta * (gx + bx);
betax = beta;
tmpx = tmpx ./ betax;
tmpy = beta * (gy + by);
betay = beta;
tmpy = tmpy ./ betay;
betay = betay;
wx = max(abs(tmpx) - 1 ./ betax, 0) .* sign(tmpx);
wy = max(abs(tmpy) - 1 ./ betay, 0) .* sign(tmpy);
else
wx = solve_image_bregman(gx + bx, beta, alpha);
wy = solve_image_bregman(gy + by, beta, alpha);
end;
bx = bx - wx + gx;
by = by - wy + gy;
wx1 = conv2(wx - bx, dxt, 'full');
wy1 = conv2(wy - by, dyt, 'full');
tmp = zeros(size(g));
gprev = g;
gxprev = gx;
gyprev = gy;
num = lambda * Ktf + beta * fft2(wx1 + wy1);
denom = lambda * KtK + beta * DtD;
Fg = num ./ denom;
g = real(ifft2(Fg));
gx = conv2(g, dx, 'valid');
gy = conv2(g, dy, 'valid');
gk = conv2(g, k, 'same');
lcost(totiter) = (lambda / 2) * norm(gk(:) - f(:))^2;
pcost(totiter) = sum((abs(gx(:)) .^ alpha));
pcost(totiter) = pcost(totiter) + sum((abs(gy(:)) .^ alpha));
end;
end;
function [Ktf, KtK, DtD, Fdx, Fdy] = computeConstants(f, k, dx, dy)
sizef = size(f);
otfk = psf2otf(k, sizef);
Ktf = conj(otfk) .* fft2(f);
KtK = abs(otfk) .^ 2;
Fdx = abs(psf2otf(dx, sizef)).^2;
Fdy = abs(psf2otf(dy, sizef)).^2;
DtD = Fdx + Fdy;
|
github
|
yuanxy92/ConvexOptimization-master
|
ms_blind_deconv.m
|
.m
|
ConvexOptimization-master/MATLAB/blinddeconv/ms_blind_deconv.m
| 5,929 |
utf_8
|
5c923da0f9819ccf3f8a120aed64b240
|
function [yorig, deblur, kernel, opts] = ms_blind_deconv(fn, opts)
%
% Do multi-scale blind deconvolution given input file name and options
% structure opts. Returns a double deblurred image along with estimated
% kernel. Following the kernel estimation, a non-blind deconvolution is run.
%
% Copyright (2011): Dilip Krishnan, Rob Fergus, New York University.
%
if (isempty(fn))
if (isempty(opts.blur))
fprintf('No image provided in fn or opts.blur!!!\n');
return;
else
y = opts.blur;
end;
else
y = im2double(imread(fn));
end;
% prescale the image if it's too big; kernel size is defined for the SCALED image
for k = 1:size(y, 3)
y1(:, :, k) = imresize(y(:, :, k), opts.prescale, 'bilinear');
end;
y = y1;
% save off for non-blind deconvolution
yorig = y;
% gamma correct
y = y.^opts.gamma_correct;
% use a window to estimate kernel
if (~isempty(opts.kernel_est_win))
w = opts.kernel_est_win;
if (size(y, 3) == 3)
y = rgb2gray(y([w(1):w(3)], [w(2):w(4)], :));
end;
else
if (size(y, 3) == 3)
y = rgb2gray(y);
end;
end;
b = zeros(opts.kernel_size);
bhs = floor(size(b, 1)/2);
% set kernel size for coarsest level - must be odd
minsize = max(3, 2*floor(((opts.kernel_size - 1)/16)) + 1);
fprintf('Kernel size at coarsest level is %d\n', minsize);
% derivative filters
dx = [-1 1; 0 0];
dy = [-1 0; 1 0];
% l2 norm of gradient images
l2norm = 6;
resize_step = sqrt(2);
% determine number of scales
num_scales = 1;
tmp = minsize;
while(tmp < opts.kernel_size)
ksize(num_scales) = tmp;
num_scales = num_scales + 1;
tmp = ceil(tmp * resize_step);
if (mod(tmp, 2) == 0)
tmp = tmp + 1;
end;
end;
ksize(num_scales) = opts.kernel_size;
% blind deconvolution - multiscale processing
for s = 1:num_scales
if (s == 1)
% at coarsest level, initialize kernel
ks{s} = init_kernel(ksize(1));
k1 = ksize(1);
k2 = k1; % always square kernel assumed
else
% upsample kernel from previous level to next finer level
k1 = ksize(s);
k2 = k1; % always square kernel assumed
% resize kernel from previous level
tmp = ks{s-1};
tmp(tmp<0) = 0;
tmp = tmp/sum(tmp(:));
ks{s} = imresize(tmp, [k1 k2], 'bilinear');
% bilinear interpolantion not guaranteed to sum to 1 - so renormalize
ks{s}(ks{s} < 0) = 0;
sumk = sum(ks{s}(:));
ks{s} = ks{s}./sumk;
end;
% image size at this level
r = floor(size(y, 1) * k1 / size(b, 1));
c = floor(size(y, 2) * k2 / size(b, 2));
if (s == num_scales)
r = size(y, 1);
c = size(y, 2);
end;
fprintf('Processing scale %d/%d; kernel size %dx%d; image size %dx%d\n', ...
s, num_scales, k1, k2, r, c);
% resize y according to the ratio of filter sizes
ys = imresize(y, [r c], 'bilinear');
yx = conv2(ys, dx, 'valid');
yy = conv2(ys, dy, 'valid');
c = min(size(yx, 2), size(yy, 2));
r = min(size(yx, 1), size(yy, 1));
g = [yx yy];
% normalize to have l2 norm of a certain size
tmp1 = g(:, 1:c);
tmp1 = tmp1*l2norm/norm(tmp1(:));
g(:, 1:c) = tmp1;
tmp1 = g(:, c+1:end);
tmp1 = tmp1*l2norm/norm(tmp1(:));
g(:, c+1:end) = tmp1;
if (s == 1)
ls{s} = g;
else
if (error_flag ~= 0)
ls{s} = g;
else
% upscale the estimated derivative image from previous level
c1 = (size(ls{s - 1}, 2)) / 2;
tmp1 = ls{s - 1}(:, 1:c1);
tmp1_up = imresize(tmp1, [r c], 'bilinear');
tmp2 = ls{s - 1}(:, c1 + 1 : end);
tmp2_up = imresize(tmp2, [r c], 'bilinear');
ls{s} = [tmp1_up tmp2_up];
end;
end;
tmp1 = ls{s}(:, 1:c);
tmp1 = tmp1*l2norm/norm(tmp1(:));
ls{s}(:, 1:c) = tmp1;
tmp1 = ls{s}(:, c+1:end);
tmp1 = tmp1*l2norm/norm(tmp1(:));
ls{s}(:, c+1:end) = tmp1;
% call kernel estimation for this scale
opts.lambda{s} = opts.min_lambda;
[ls{s} ks{s} error_flag] = ss_blind_deconv(g, ls{s}, ks{s}, opts.lambda{s}, ...
opts.delta, opts.x_in_iter, opts.x_out_iter, ...
opts.xk_iter, opts.k_reg_wt);
if (error_flag < 0)
ks{s}(:) = 0;
ks{s}(ceil(size(ks{s}, 1)/2), ceil(size(ks{s}, 2)/2)) = 1;
fprintf('Bad error - just set output to delta kernel and return\n');
end;
% center the kernel
c1 = (size(ls{s}, 2)) / 2;
tmp1 = ls{s}(:, 1:c1);
tmp2 = ls{s}(:, c1 + 1 : end);
[tmp1_shifted tmp2_shifted ks{s}] = center_kernel_separate(tmp1, tmp2, ks{s});
ls{s} = [tmp1_shifted tmp2_shifted];
% set elements below threshold to 0
if (s == num_scales)
kernel = ks{s};
kernel(kernel(:) < opts.k_thresh * max(kernel(:))) = 0;
kernel = kernel / sum(kernel(:));
end;
end;
padsize = bhs;
dx = [1 -1];
dy = dx';
if (opts.use_ycbcr)
if (size(yorig, 3) == 3)
ycbcr = rgb2ycbcr(yorig);
else
ycbcr = yorig;
end;
opts.nb_alpha = 1;
end;
if (opts.use_ycbcr == 1)
ypad = padarray(ycbcr(:,:,1), [padsize padsize], 'replicate', 'both');
for a = 1:4
ypad = edgetaper(ypad, kernel);
end;
tmp = fast_deconv_bregman(ypad, kernel, opts.nb_lambda, opts.nb_alpha);
deblur(:, :, 1) = tmp(bhs + 1 : end - bhs, bhs + 1 : end - bhs);
if (size(ycbcr, 3) == 3)
deblur(:, :, 2:3) = ycbcr(:, :, 2:3);
deblur = ycbcr2rgb(deblur);
end;
else
for j = 1:3
ypad = padarray(yorig(:, :, j), [1 1] * bhs, 'replicate', 'both');
for a = 1:4
ypad = edgetaper(ypad, kernel);
end;
tmp = fast_deconv_bregman(ypad, kernel, opts.nb_lambda, opts.nb_alpha);
deblur(:, :, j) = tmp(bhs + 1 : end - bhs, bhs + 1 : end - bhs);
end;
end;
figure; imagesc([uint8(255*yorig) uint8(255*deblur)]); title(['Blurred/' ...
'deblurred']);
figure; imagesc(kernel); colormap gray; title('Kernel');
function [k] = init_kernel(minsize)
k = zeros(minsize, minsize);
k((minsize - 1)/2, (minsize - 1)/2:(minsize - 1)/2+1) = 1/2;
|
github
|
yuanxy92/ConvexOptimization-master
|
solve_image_bregman.m
|
.m
|
ConvexOptimization-master/MATLAB/blinddeconv/solve_image_bregman.m
| 6,074 |
utf_8
|
53ce7248ff591aab751e8787cbd2cdb7
|
function [w] = solve_image_bregman(v, beta, alpha)
%
% solve the following component-wise separable problem
% min maskk .* |w|^\alpha + \frac{\beta}{2} (w - v).^2
%
% A LUT is used to solve the problem; when the function is first called
% for a new value of beta or alpha, a LUT is built for that beta/alpha
% combination and for a range of values of v. The LUT stays persistent
% between calls to solve_image. It will be recomputed the first time this
% function is called.
% range of input data and step size; increasing the range of decreasing
% the step size will increase accuracy but also increase the size of the
% LUT
range = 10;
step = 0.0001;
persistent lookup_v known_beta xx known_alpha
ind = find(known_beta==beta & known_alpha==alpha);
if isempty(known_beta | known_alpha)
xx = [-range:step:range];
end
if any(ind)
fprintf('Reusing lookup table for beta %.3g and alpha %.3g\n', beta, alpha);
%%% already computed
if (exist('pointOp') == 3)
% Use Eero Simoncelli's function to extrapolate
w = pointOp(double(v),lookup_v(ind,:), -range, step, 0);
else
w = interp1(xx', lookup_v(ind,:)', v(:), 'linear', 'extrap');
w = reshape(w, size(v,1), size(v,2));
end;
else
%%% now go and recompute xx for new value of beta and alpha
tmp = compute_w(xx, beta, alpha);
lookup_v = [lookup_v; tmp(:)'];
known_beta = [known_beta, beta];
known_alpha = [known_alpha, alpha];
%%% and lookup current v's in the new lookup table row.
if (exist('pointOp') == 3)
% Use Eero Simoncelli's function to extrapolate
w = pointOp(double(v),lookup_v(end,:), -range, step, 0);
else
w = interp1(xx', lookup_v(end,:)', v(:), 'linear', 'extrap');
w = reshape(w, size(v,1), size(v,2));
end;
fprintf('Recomputing lookup table for new value of beta %.3g and alpha %.3g\n', beta, alpha);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% call different functions to solve the minimization problem
% min |w|^\alpha + \frac{\beta}{2} (w - v).^2 for a fixed beta and alpha
%
function w = compute_w(v, beta, alpha)
if (abs(alpha - 1) < 1e-9)
% assume alpha = 1.0
w = compute_w1(v, beta);
return;
end;
if (abs(alpha - 2/3) < 1e-9)
% assume alpha = 2/3
w = compute_w23(v, beta);
return;
end;
if (abs(alpha - 1/2) < 1e-9)
% assume alpha = 1/2
w = compute_w12(v, beta);
return;
end;
% for any other value of alpha, plug in some other generic root-finder
% here, we use Newton-Raphson
w = newton_w(v, beta, alpha);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = compute_w23(v, beta)
% solve a quartic equation
% for alpha = 2/3
epsilon = 1e-6; %% tolerance on imag part of real root
k = 8/(27*beta^3);
m = ones(size(v))*k;
% Now use formula from
% http://en.wikipedia.org/wiki/Quartic_equation (Ferrari's method)
% running our coefficients through Mathmetica (quartic_solution.nb)
% optimized to use as few operations as possible...
%%% precompute certain terms
v2 = v .* v;
v3 = v2 .* v;
v4 = v3 .* v;
m2 = m .* m;
m3 = m2 .* m;
%% Compute alpha & beta
alpha = -1.125*v2;
beta2 = 0.25*v3;
%%% Compute p,q,r and u directly.
q = -0.125*(m.*v2);
r1 = -q/2 + sqrt(-m3/27 + (m2.*v4)/256);
u = exp(log(r1)/3);
y = 2*(-5/18*alpha + u + (m./(3*u)));
W = sqrt(alpha./3 + y);
%%% now form all 4 roots
root = zeros(size(v,1),size(v,2),4);
root(:,:,1) = 0.75.*v + 0.5.*(W + sqrt(-(alpha + y + beta2./W )));
root(:,:,2) = 0.75.*v + 0.5.*(W - sqrt(-(alpha + y + beta2./W )));
root(:,:,3) = 0.75.*v + 0.5.*(-W + sqrt(-(alpha + y - beta2./W )));
root(:,:,4) = 0.75.*v + 0.5.*(-W - sqrt(-(alpha + y - beta2./W )));
%%%%%% Now pick the correct root, including zero option.
%%% Clever fast approach that avoids lookups
v2 = repmat(v,[1 1 4]);
sv2 = sign(v2);
rsv2 = real(root).*sv2;
%%% condensed fast version
%%% take out imaginary roots above v/2 but below v
root_flag3 = sort(((abs(imag(root))<epsilon) & ((rsv2)>(abs(v2)/2)) & ((rsv2)<(abs(v2)))).*rsv2,3,'descend').*sv2;
%%% take best
w=root_flag3(:,:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = compute_w12(v, beta)
% solve a cubic equation
% for alpha = 1/2
epsilon = 1e-6; %% tolerance on imag part of real root
k = -0.25/beta^2;
m = ones(size(v))*k.*sign(v);
%%%%%%%%%%%%%%%%%%%%%%%%%%% Compute the roots (all 3)
t1 = (2/3)*v;
v2 = v .* v;
v3 = v2 .* v;
%%% slow (50% of time), not clear how to speed up...
t2 = exp(log(-27*m - 2*v3 + (3*sqrt(3))*sqrt(27*m.^2 + 4*m.*v3))/3);
t3 = v2./t2;
%%% find all 3 roots
root = zeros(size(v,1),size(v,2),3);
root(:,:,1) = t1 + (2^(1/3))/3*t3 + (t2/(3*2^(1/3)));
root(:,:,2) = t1 - ((1+i*sqrt(3))/(3*2^(2/3)))*t3 - ((1-i*sqrt(3))/(6*2^(1/3)))*t2;
root(:,:,3) = t1 - ((1-i*sqrt(3))/(3*2^(2/3)))*t3 - ((1+i*sqrt(3))/(6*2^(1/3)))*t2;
root(find(isnan(root) | isinf(root))) = 0; %%% catch 0/0 case
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Pick the right root
%%% Clever fast approach that avoids lookups
v2 = repmat(v,[1 1 3]);
sv2 = sign(v2);
rsv2 = real(root).*sv2;
root_flag3 = sort(((abs(imag(root))<epsilon) & ((rsv2)>(2*abs(v2)/3)) & ((rsv2)<(abs(v2)))).*rsv2,3,'descend').*sv2;
%%% take best
w=root_flag3(:,:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = compute_w1(v, beta)
% solve a simple max problem for alpha = 1
w = max(abs(v) - 1/beta, 0).*sign(v);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = newton_w(v, beta, alpha)
% for a general alpha, use Newton-Raphson; more accurate root-finders may
% be substituted here; we are finding the roots of the equation:
% \alpha*|w|^{\alpha - 1} + \beta*(v - w) = 0
iterations = 4;
x = v;
for a=1:iterations
fd = (alpha)*sign(x).*abs(x).^(alpha-1)+beta*(x-v);
fdd = alpha*(alpha-1)*abs(x).^(alpha-2)+beta;
x = x - fd./fdd;
end;
q = find(isnan(x));
x(q) = 0;
% check whether the zero solution is the better one
z = beta/2*v.^2;
f = abs(x).^alpha + beta/2*(x-v).^2;
w = (f<z).*x;
|
github
|
yuanxy92/ConvexOptimization-master
|
pcg_kernel_irls_conv.m
|
.m
|
ConvexOptimization-master/MATLAB/blinddeconv/pcg_kernel_irls_conv.m
| 2,194 |
utf_8
|
69320b59f1de28b4f4213c839c8e8eea
|
function k_out = pcg_kernel_irls_conv(k_init, X, Y, opts)
%
% Use Iterative Re-weighted Least Squares to solve l_1 regularized kernel
% update with sum to 1 and nonnegativity constraints. The problem that is
% being minimized is:
%
% min 1/2\|Xk - Y\|^2 + \lambda \|k\|_1
%
% Inputs:
% k_init = initial kernel, or scalar specifying size
% X = sharp image
% Y = blurry image
% opts = options (see below)
%
% Outputs:
% k_out = output kernel
%
% This version of the function uses spatial convolutions. Everything is maintained as 2D arrays
%
% Defaults
if nargin == 3
opts.lambda = 0;
% PCG parameters
opts.pcg_tol = 1e-8;
opts.pcg_its = 100;
fprintf('Input options not defined - really no reg/constraints on the kernel?\n');
end
lambda = opts.lambda;
pcg_tol = opts.pcg_tol;
pcg_its = opts.pcg_its;
if (length(k_init(:)) == 1)
k_init = zeros(k_init,k_init);
end;
% assume square kernel
ks = size(k_init,1);
ks2 = floor(ks/2);
% precompute RHS
for i = 1:length(X)
flipX{i} = fliplr(flipud(X{i}));
% precompute X^T Y term on RHS (e = ks^2 length vector of all 1's)
rhs{i} = conv2(flipX{i}, Y{i}, 'valid');
end;
tmp = zeros(size(rhs{1}));
for i = 1 : length(X)
tmp = tmp + rhs{i};
end;
rhs = tmp;
k_out = k_init;
% Set exponent for regularization
exp_a = 1;
% outer loop
for iter = 1 : 1
k_prev = k_out;
% compute diagonal weights for IRLS
weights_l1 = lambda .* (max(abs(k_prev), 0.0001) .^ (exp_a - 2));
k_out = local_cg(k_prev, X, flipX, ks,weights_l1, rhs, pcg_tol, pcg_its);
end;
% local implementation of CG to solve the reweighted least squares problem
function k = local_cg(k, X, flipX, ks, weights_l1, rhs, tol, max_its)
Ak = pcg_kernel_core_irls_conv(k, X, flipX, ks,weights_l1);
r = rhs - Ak;
for iter = 1:max_its
rho = (r(:)' * r(:));
if (iter > 1)
beta = rho / rho_1;
p = r + beta*p;
else
p = r;
end
Ap = pcg_kernel_core_irls_conv(p, X, flipX, ks, weights_l1);
q = Ap;
alpha = rho / (p(:)' * q(:) );
k = k + alpha * p;
r = r - alpha*q;
rho_1 = rho;
if (rho < tol)
break;
end;
end;
|
github
|
yuanxy92/ConvexOptimization-master
|
sparse_deblur.m
|
.m
|
ConvexOptimization-master/MATLAB/code/sparse_deblur.m
| 3,117 |
utf_8
|
749ef9a032978645f074cec67e368742
|
%% Motion Blurry Image Restoration using sparse image prior
% This code is written for ELEC5470 convex optimization project Fall 2017-2018
% @author: Shane Yuan
% @date: Dec 4, 2017
% I write this code basd on Jinshan Pan's open source code, which helps me
% a lot. Thanks to Jinshan Pan
%
function [Latent, k] = sparse_deblur(opts)
%% add path
addpath(genpath('image'));
addpath(genpath('utils'));
%% set parameter
opts.prescale = 1;
opts.xk_iter = 5; %% max iterations
% non-blind deblurring method, support
% L0: L0 sparse image prior, use optimization proposed by Li Xu
% http://www.cse.cuhk.edu.hk/~leojia/projects/l0deblur/
% L1: L1 sparse image prior, implemented by me
% L0_IRL1: L0 sparse image prior, implemented by me, use iterative
% reweighted L1 norm which discussed in class
if ~(strcmp(opts.blind_method, 'L0')||strcmp(opts.blind_method, 'L1') ...
||strcmp(opts.blind_method, 'L0_IRL1')||strcmp(opts.blind_method, 'L0_MSF'))
opts.blind_method = 'L0_IRL1';
end
% non-blind deblurring method, support TV-L2 and hyper-laplacian (only windows
% executable code is provided for hyper-laplacian method, thanks to Qi
% Shan, Jiaya Jia and Aseem Agarwala
% http://www.cse.cuhk.edu.hk/~leojia/programs/deconvolution/deconvolution.htm)
if ~(strcmp(opts.nonblind_method, 'TV-L2')||strcmp(opts.nonblind_method, 'hyper'))
opts.nonblind_method = 'hyper';
end
y = imread(opts.filename);
% make out dir
mkdir(opts.outdir);
if size(y,3) == 3
yg = im2double(rgb2gray(y));
else
yg = im2double(y);
end
y = im2double(y);
%% blind deblurring step
tic;
[kernel, interim_latent] = blind_deconv(yg, y, opts);
toc
%% non blind deblurring step
% write k into file
k = kernel ./ max(kernel(:));
imwrite(k, [opts.outdir, 'kernel.png']);
if strcmp(opts.nonblind_method, 'TV-L2')
% TV-L2 denoising method
Latent = ringing_artifacts_removal(y, kernel, opts.lambda_tv, opts.lambda_l0, opts.weight_ring);
if (strcmp(opts.outdir, '') ~= 0)
imwrite(Latent, [opts.outdir, 'deblurred.png']);
end
else if strcmp(opts.nonblind_method, 'hyper') % only windows executable code is provided
% hyper laplacian method
kernelname = [opts.outdir, 'kernel.png'];
blurname = 'temp.png';
imwrite(y, blurname);
sharpname = [opts.outdir, 'deblurred.png'];
command = sprintf('deconv.exe %s %s %s 3e-2 1 0.04 1', blurname, kernelname, sharpname);
system(command);
delete(blurname);
Latent = im2double(imread(sharpname));
if (strcmp(opts.outdir, '') ~= 0)
delete(sharpname);
end
else
fprintf('Only hyper and TV-L2 are support for non blind deblur!');
exit(-1);
end
end
if (opts.draw_inter == 1)
figure(2); imshow(Latent);
end
end
% imwrite(interim_latent, ['results\' filename(7:end-4) '_interim_result.png']);
|
github
|
yuanxy92/ConvexOptimization-master
|
deblurring_adm_aniso.m
|
.m
|
ConvexOptimization-master/MATLAB/code/deblurring_adm_aniso.m
| 2,406 |
utf_8
|
df3c7a21e133a0400474e324ac25aa1b
|
function [I] = deblurring_adm_aniso(B, k, lambda, alpha)
% Solving TV-\ell^2 deblurring problem via ADM/Split Bregman method
%
% This reference of this code is :Fast Image Deconvolution using Hyper-Laplacian Priors
% Original code is created by Dilip Krishnan
% Finally modified by Jinshan Pan 2011/12/25
% Note:
% In this model, aniso TV regularization method is adopted.
% Thus, we do not use the Lookup table method proposed by Dilip Krishnan and Rob Fergus
% Reference: Kernel Estimation from Salient Structure for Robust Motion
% Deblurring
%Last update: (2012/6/20)
beta = 1/lambda;
beta_rate = 2*sqrt(2);
%beta_max = 5*2^10;
beta_min = 0.001;
[m n] = size(B);
% initialize with input or passed in initialization
I = B;
% make sure k is a odd-sized
if ((mod(size(k, 1), 2) ~= 1) | (mod(size(k, 2), 2) ~= 1))
fprintf('Error - blur kernel k must be odd-sized.\n');
return;
end;
[Nomin1, Denom1, Denom2] = computeDenominator(B, k);
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
%% Main loop
while beta > beta_min
gamma = 1/(2*beta);
Denom = Denom1 + gamma*Denom2;
% subproblem for regularization term
if alpha==1
Wx = max(abs(Ix) - beta*lambda, 0).*sign(Ix);
Wy = max(abs(Iy) - beta*lambda, 0).*sign(Iy);
%%
else
Wx = solve_image(Ix, 1/(beta*lambda), alpha);
Wy = solve_image(Iy, 1/(beta*lambda), alpha);
end
Wxx = [Wx(:,n) - Wx(:, 1), -diff(Wx,1,2)];
Wxx = Wxx + [Wy(m,:) - Wy(1, :); -diff(Wy,1,1)];
Fyout = (Nomin1 + gamma*fft2(Wxx))./Denom;
I = real(ifft2(Fyout));
% update the gradient terms with new solution
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
beta = beta/2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Nomin1, Denom1, Denom2] = computeDenominator(y, k)
%
% computes denominator and part of the numerator for Equation (3) of the
% paper
%
% Inputs:
% y: blurry and noisy input
% k: convolution kernel
%
% Outputs:
% Nomin1 -- F(K)'*F(y)
% Denom1 -- |F(K)|.^2
% Denom2 -- |F(D^1)|.^2 + |F(D^2)|.^2
%
sizey = size(y);
otfk = psf2otf(k, sizey);
Nomin1 = conj(otfk).*fft2(y);
Denom1 = abs(otfk).^2;
% if higher-order filters are used, they must be added here too
Denom2 = abs(psf2otf([1,-1],sizey)).^2 + abs(psf2otf([1;-1],sizey)).^2;
|
github
|
yuanxy92/ConvexOptimization-master
|
SparseRestorationIRLS.m
|
.m
|
ConvexOptimization-master/MATLAB/code/SparseRestorationIRLS.m
| 5,712 |
utf_8
|
6ccd0743e5ae878824f45f1320a0ef2c
|
function S = SparseRestorationIRLS(Im, kernel, lambda, kappa, type)
%% Image restoration with L1 prior without FFT
% The objective function:
% S^* = argmin ||I*k - B||^2 + lambda |\nabla I|_0 or
% S^* = argmin ||I*k - B||^2 + lambda |\nabla I|_1
% This code is written for ELEC5470 convex optimization project Fall 2017-2018
% @author: Shane Yuan
% @date: Dec 4, 2017
% I write this code basd on Jinshan Pan's open source code. Thanks to
% Jinshan Pan
%
%% Input:
% @Im: Blurred image
% @kernel: blur kernel
% @lambda: weight for the L1 prior
% @kappa: Update ratio in the ADM
%% Output:
% @S: Latent image
%
% The Code is created based on the method described in the following paper
% [1] Jinshan Pan, Zhe Hu, Zhixun Su, and Ming-Hsuan Yang,
% Deblurring Text Images via L0-Regularized Intensity and Gradient
% Prior, CVPR, 2014.
% [2] Li Xu, Cewu Lu, Yi Xu, and Jiaya Jia. Image smoothing via l0 gradient minimization.
% ACM Trans. Graph., 30(6):174, 2011.
%
% Author: Jinshan Pan ([email protected])
% Date : 05/18/2014
if ~exist('kappa','var')
kappa = 2.0;
end
if (strcmp(type, 'L1'))
lambda = 7.5 * lambda;
end
% pad image
H = size(Im,1); W = size(Im,2);
Im = wrap_boundary_liu(Im, opt_fft_size([H W]+size(kernel)-1));
%
S = Im;
betamax = 1e5;
fx = [1, -1];
fy = [1; -1];
[N,M,D] = size(Im);
sizeI2D = [N,M];
% otfFx = psf2otf(fx,sizeI2D);
% otfFy = psf2otf(fy,sizeI2D);
% %
% KER = psf2otf(kernel,sizeI2D);
% Den_KER = abs(KER).^2;
% %
% Denormin2 = abs(otfFx).^2 + abs(otfFy ).^2;
% if D>1
% Denormin2 = repmat(Denormin2,[1,1,D]);
% KER = repmat(KER,[1,1,D]);
% Den_KER = repmat(Den_KER,[1,1,D]);
% end
% Normin1 = conj(KER).*fft2(S);
%
eps = 0.0001;
beta = 2*lambda;
while beta < betamax
% Denormin = Den_KER + beta * Denormin2;
h = [diff(S,1,2), S(:,1,:) - S(:,end,:)];
v = [diff(S,1,1); S(1,:,:) - S(end,:,:)];
% update g
if (strcmp(type, 'L0'))
if D==1
t = (h.^2+v.^2) < lambda / beta;
else
t = sum((h.^2+v.^2),3) < lambda / beta;
t = repmat(t,[1,1,D]);
end
h(t)=0; v(t)=0;
end
if (strcmp(type, 'L1'))
rho = lambda / beta;
for i = 1:size(h, 1)
for j = 1:size(h, 2)
gh1 = (2 * h(i, j) - rho) / 2;
gh2 = (2 * h(i, j) + rho) / 2;
if (gh1 > 0)
h(i, j) = gh1;
else if (gh2 < 0)
h(i, j) = gh2;
else
h(i, j) = 0;
end
end
gv1 = (2 * v(i, j) - rho) / 2;
gv2 = (2 * v(i, j) + rho) / 2;
if (gv1 > 0)
v(i, j) = gv1;
else if (gv2 < 0)
v(i, j) = gv2;
else
v(i, j) = 0;
end
end
end
end
end
if (strcmp(type, 'L0_IRL1'))
rho = lambda/beta;
for i = 1:size(h, 1)
for j = 1:size(h, 2)
gh1 = (2 * h(i, j) - 1 / (abs(h(i, j)) + eps) * rho) / 2;
gh2 = (2 * h(i, j) + 1 / (abs(h(i, j)) + eps) * rho) / 2;
if (gh1 > 0)
h(i, j) = gh1;
else if (gh2 < 0)
h(i, j) = gh2;
else
h(i, j) = 0;
end
end
gv1 = (2 * v(i, j) - 1 / (abs(v(i, j)) + eps) * rho) / 2;
gv2 = (2 * v(i, j) + 1 / (abs(v(i, j)) + eps) * rho) / 2;
if (gv1 > 0)
v(i, j) = gv1;
else if (gv2 < 0)
v(i, j) = gv2;
else
v(i, j) = 0;
end
end
end
end
end
% conjugate gradient descent
kernel = kernel ./ sum(kernel(:));
b = conv2(Im, kernel, 'same');
b = b + conv2(h, fx, 'same');
b = b + conv2(v, fy, 'same');
Ax = conv2(conv2(S, fliplr(flipud(kernel)), 'same'), kernel, 'same');
Ax = Ax + beta * conv2(conv2(S, fliplr(flipud(fx)), 'valid'), fx);
Ax = Ax + beta * conv2(conv2(S, fliplr(flipud(fy)), 'valid'), fy);
r = b - Ax;
S = conj_grad(S, r, kernel, beta);
beta = beta * kappa;
end
S = S(1:H, 1:W, :);
end
function S = conj_grad(S, r, kernel, beta_out)
fx = [1, -1];
fy = [1; -1];
for iter = 1:30
rho = (r(:)'*r(:));
if ( iter > 1 ), % direction vector
beta = rho / rho_1;
p = r + beta * p;
else
p = r;
end
Ap = conv2(conv2(S, fliplr(flipud(kernel)), 'same'), kernel, 'same');
Ap = Ap + beta_out * conv2(conv2(S, fliplr(flipud(fx)), 'valid'), fx);
Ap = Ap + beta_out * conv2(conv2(S, fliplr(flipud(fy)), 'valid'), fy);
q = Ap;
alpha = rho / (p(:)' * q(:) );
S = S + alpha * p; % update approximation vector
r = r - alpha*q; % compute residual
rho_1 = rho;
fprintf('residual: %f\n', sum(r(:)));
end
end
|
github
|
yuanxy92/ConvexOptimization-master
|
aligned_psnr.m
|
.m
|
ConvexOptimization-master/MATLAB/code/aligned_psnr.m
| 1,277 |
utf_8
|
e5c2fc5be4e03efc123052b8409accf0
|
%% calculate aligned PSNR of two images
% This code is written for ELEC5470 convex optimization project Fall 2017-2018
% @author: Shane Yuan
% @date: Dec 4, 2017
% I write this code basd on Jinshan Pan's open source code, which helps me
% a lot. Thanks to Jinshan Pan
%
function [psnr_result] = aligned_psnr(ground, image)
[rows, cols, m] = size(ground);
if m == 3
% Change the images to gray
ground = rgb2gray(ground);
end
[~, ~, m] = size(image);
if m == 3
% Change the images to gray
image = rgb2gray(image);
end
% Get cutted groundtruth
row_cutted = 10;
col_cutted = 10;
psnr_mat = zeros(2 * row_cutted, 2 * col_cutted);
ground_cutted = ground((1 + row_cutted):(rows - row_cutted), (1 + col_cutted):(cols - col_cutted));
% Calculate
rows_cutted = rows - row_cutted * 2;
cols_cutted = cols - col_cutted * 2;
for i = 1:1:(row_cutted * 2)
for j = 1:1:(col_cutted * 2)
image_cutted = image(i:(i + rows_cutted - 1), j:(j + cols_cutted - 1));
% % Calculate the mean square error
% e = double(ground_cutted) - double(image_cutted);
% [m, n] = size(e);
% mse = sum(sum(e.^2))/(m*n);
% % Calculate the PSNR
psnr_mat(i, j) = psnr(ground_cutted, image_cutted);
end
end
psnr_result = max(psnr_mat(:));
|
github
|
yuanxy92/ConvexOptimization-master
|
estimate_psf.m
|
.m
|
ConvexOptimization-master/MATLAB/code/estimate_psf.m
| 1,290 |
utf_8
|
f570f34e559fd6d11f20feb4f37963d9
|
function psf = estimate_psf(blurred_x, blurred_y, latent_x, latent_y, weight, psf_size)
%----------------------------------------------------------------------
% these values can be pre-computed at the beginning of each level
% blurred_f = fft2(blurred);
% dx_f = psf2otf([1 -1 0], size(blurred));
% dy_f = psf2otf([1;-1;0], size(blurred));
% blurred_xf = dx_f .* blurred_f; %% FFT (Bx)
% blurred_yf = dy_f .* blurred_f; %% FFT (By)
latent_xf = fft2(latent_x);
latent_yf = fft2(latent_y);
blurred_xf = fft2(blurred_x);
blurred_yf = fft2(blurred_y);
% compute b = sum_i w_i latent_i * blurred_i
b_f = conj(latent_xf) .* blurred_xf ...
+ conj(latent_yf) .* blurred_yf;
b = real(otf2psf(b_f, psf_size));
p.m = conj(latent_xf) .* latent_xf ...
+ conj(latent_yf) .* latent_yf;
%p.img_size = size(blurred);
p.img_size = size(blurred_xf);
p.psf_size = psf_size;
p.lambda = weight;
psf = ones(psf_size) / prod(psf_size);
psf = conjgrad(psf, b, 20, 1e-5, @compute_Ax, p);
psf(psf < max(psf(:))*0.05) = 0;
psf = psf / sum(psf(:));
end
function y = compute_Ax(x, p)
x_f = psf2otf(x, p.img_size);
y = otf2psf(p.m .* x_f, p.psf_size);
y = y + p.lambda * x;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
blind_deconv.m
|
.m
|
ConvexOptimization-master/MATLAB/code/blind_deconv.m
| 5,338 |
utf_8
|
7bb1cdb0addad885af945341306304dd
|
function [kernel, interim_latent] = blind_deconv(y, y_color, opts)
%% multiscale blind deblurring code
% This code is written for ELEC5470 convex optimization project Fall 2017-2018
% @author: Shane Yuan
% @date: Dec 4, 2017
% I write this code basd on Jinshan Pan's open source code. Thanks to
% Jinshan Pan
%% Input:
% @y: input blurred image (grayscale);
% @lambda_grad: the weight for the L0/L1 regularization on gradient
% @opts: options
%% Output:
% @kernel: the estimated blur kernel
% @interim_latent: intermediate latent image
%
% The Code is created based on the method described in the following paper
% [1] Jinshan Pan, Deqing Sun, Hanspteter Pfister, and Ming-Hsuan Yang,
% Blind Image Deblurring Using Dark Channel Prior, CVPR, 2016.
% [2] Jinshan Pan, Zhe Hu, Zhixun Su, and Ming-Hsuan Yang,
% Deblurring Text Images via L0-Regularized Intensity and Gradient
% Prior, CVPR, 2014.
% gamma correct
if opts.gamma_correct~=1
y = y .^ opts.gamma_correct;
y_color = y_color .^ opts.gamma_correct;
end
b = zeros(opts.kernel_size);
%%
ret = sqrt(0.5);
%%
maxitr = max(floor(log(5/min(opts.kernel_size))/log(ret)),0);
num_scales = maxitr + 1;
fprintf('Maximum iteration level is %d\n', num_scales);
%%
retv = ret .^ [0 : maxitr];
k1list = ceil(opts.kernel_size * retv);
k1list = k1list+(mod(k1list, 2) == 0);
k2list =ceil(opts.kernel_size * retv);
k2list = k2list+(mod(k2list, 2) == 0);
% derivative filters
dx = [-1 1; 0 0];
dy = [-1 0; 1 0];
% blind deconvolution - multiscale processing
for s = num_scales : (-1) : 1
if (s == num_scales)
%%
% at coarsest level, initialize kernel
ks = init_kernel(k1list(s));
k1 = k1list(s);
k2 = k1; % always square kernel assumed
else
% upsample kernel from previous level to next finer level
k1 = k1list(s);
k2 = k1; % always square kernel assumed
% resize kernel from previous level
ks = resizeKer(ks,1/ret,k1list(s),k2list(s));
end;
%
cret = retv(s);
ys = downSmpImC(y, cret);
y_colors = zeros(size(ys, 1), size(ys, 2), 3);
for c = 1:3
y_colors(:, :, c) = downSmpImC(y_color(:, :, c), cret);
end
fprintf('Processing scale %d/%d; kernel size %dx%d; image size %dx%d\n', ...
s, num_scales, k1, k2, size(ys,1), size(ys,2));
% optimization in this scale
[ks, interim_latent, opts] = blind_deconv_main(ys, y_colors, ks,...
opts);
% center the kernel
ks = adjust_psf_center(ks);
ks(ks(:)<0) = 0;
sumk = sum(ks(:));
ks = ks./sumk;
% denoise kernel
if (s == 1)
kernel = ks;
if opts.k_thresh > 0
kernel(kernel(:) < max(kernel(:))/opts.k_thresh) = 0;
else
kernel(kernel(:) < 0) = 0;
end
kernel = kernel / sum(kernel(:));
end
% output intermediate
if opts.output_intermediate == 1
imwrite(interim_latent, [opts.outdir, sprintf('inter_image_%2d.png', s)]);
kw = ks ./ max(ks(:));
imwrite(kw, [opts.outdir, sprintf('inter_kernel_%2d.png', s)]);
end
end
end
%% kernel init funciton
function [k] = init_kernel(minsize)
k = zeros(minsize, minsize);
k((minsize - 1)/2, (minsize - 1)/2:(minsize - 1)/2+1) = 1/2;
end
%% image downsample function
function sI=downSmpImC(I,ret)
% refer to Levin's code
if (ret==1)
sI=I;
return
end
sig=1/pi*ret;
g0=[-50:50]*2*pi;
sf=exp(-0.5*g0.^2*sig^2);
sf=sf/sum(sf);
csf=cumsum(sf);
csf=min(csf,csf(end:-1:1));
ii=find(csf>0.05);
sf=sf(ii);
sum(sf);
I=conv2(sf,sf',I,'valid');
[gx,gy]=meshgrid([1:1/ret:size(I,2)],[1:1/ret:size(I,1)]);
sI=interp2(I,gx,gy,'bilinear');
end
%% kernel resize function
function k=resizeKer(k,ret,k1,k2)
% levin's code
k=imresize(k,ret);
k=max(k,0);
k=fixsize(k,k1,k2);
if max(k(:))>0
k=k/sum(k(:));
end
end
function nf = fixsize(f,nk1,nk2)
[k1,k2]=size(f);
while((k1 ~= nk1) || (k2 ~= nk2))
if (k1>nk1)
s=sum(f,2);
if (s(1)<s(end))
f=f(2:end,:);
else
f=f(1:end-1,:);
end
end
if (k1<nk1)
s=sum(f,2);
if (s(1)<s(end))
tf=zeros(k1+1,size(f,2));
tf(1:k1,:)=f;
f=tf;
else
tf=zeros(k1+1,size(f,2));
tf(2:k1+1,:)=f;
f=tf;
end
end
if (k2>nk2)
s=sum(f,1);
if (s(1)<s(end))
f=f(:,2:end);
else
f=f(:,1:end-1);
end
end
if (k2<nk2)
s=sum(f,1);
if (s(1)<s(end))
tf=zeros(size(f,1),k2+1);
tf(:,1:k2)=f;
f=tf;
else
tf=zeros(size(f,1),k2+1);
tf(:,2:k2+1)=f;
f=tf;
end
end
[k1,k2]=size(f);
end
nf=f;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
wrap_boundary_liu.m
|
.m
|
ConvexOptimization-master/MATLAB/code/utils/wrap_boundary_liu.m
| 3,568 |
utf_8
|
778eb4d6eeeb26991f536cb17154be69
|
function ret = wrap_boundary_liu(img, img_size)
% wrap_boundary_liu.m
%
% pad image boundaries such that image boundaries are circularly smooth
%
% written by Sunghyun Cho ([email protected])
%
% This is a variant of the method below:
% Reducing boundary artifacts in image deconvolution
% Renting Liu, Jiaya Jia
% ICIP 2008
%
[H, W, Ch] = size(img);
H_w = img_size(1) - H;
W_w = img_size(2) - W;
ret = zeros(img_size(1), img_size(2), Ch);
for ch = 1:Ch
alpha = 1;
HG = img(:,:,ch);
r_A = zeros(alpha*2+H_w, W);
r_A(1:alpha, :) = HG(end-alpha+1:end, :);
r_A(end-alpha+1:end, :) = HG(1:alpha, :);
a = ((1:H_w)-1)/(H_w-1);
r_A(alpha+1:end-alpha, 1) = (1-a)*r_A(alpha,1) + a*r_A(end-alpha+1,1);
r_A(alpha+1:end-alpha, end) = (1-a)*r_A(alpha,end) + a*r_A(end-alpha+1,end);
A2 = solve_min_laplacian(r_A(alpha:end-alpha+1,:));
r_A(alpha:end-alpha+1,:) = A2;
A = r_A;
r_B = zeros(H, alpha*2+W_w);
r_B(:, 1:alpha) = HG(:, end-alpha+1:end);
r_B(:, end-alpha+1:end) = HG(:, 1:alpha);
a = ((1:W_w)-1)/(W_w-1);
r_B(1, alpha+1:end-alpha) = (1-a)*r_B(1,alpha) + a*r_B(1,end-alpha+1);
r_B(end, alpha+1:end-alpha) = (1-a)*r_B(end,alpha) + a*r_B(end,end-alpha+1);
B2 = solve_min_laplacian(r_B(:, alpha:end-alpha+1));
r_B(:,alpha:end-alpha+1,:) = B2;
B = r_B;
r_C = zeros(alpha*2+H_w, alpha*2+W_w);
r_C(1:alpha, :) = B(end-alpha+1:end, :);
r_C(end-alpha+1:end, :) = B(1:alpha, :);
r_C(:, 1:alpha) = A(:, end-alpha+1:end);
r_C(:, end-alpha+1:end) = A(:, 1:alpha);
C2 = solve_min_laplacian(r_C(alpha:end-alpha+1, alpha:end-alpha+1));
r_C(alpha:end-alpha+1, alpha:end-alpha+1) = C2;
C = r_C;
A = A(alpha:end-alpha-1, :);
B = B(:, alpha+1:end-alpha);
C = C(alpha+1:end-alpha, alpha+1:end-alpha);
ret(:,:,ch) = [img(:,:,ch) B; A C];
end
end
function [img_direct] = solve_min_laplacian(boundary_image)
% function [img_direct] = poisson_solver_function(gx,gy,boundary_image)
% Inputs; Gx and Gy -> Gradients
% Boundary Image -> Boundary image intensities
% Gx Gy and boundary image should be of same size
[H,W] = size(boundary_image);
% Laplacian
f = zeros(H,W); clear j k
% boundary image contains image intensities at boundaries
boundary_image(2:end-1, 2:end-1) = 0;
j = 2:H-1; k = 2:W-1; f_bp = zeros(H,W);
f_bp(j,k) = -4*boundary_image(j,k) + boundary_image(j,k+1) + ...
boundary_image(j,k-1) + boundary_image(j-1,k) + boundary_image(j+1,k);
clear j k
%f1 = f - reshape(f_bp,H,W); % subtract boundary points contribution
f1 = f - f_bp; % subtract boundary points contribution
clear f_bp f
% DST Sine Transform algo starts here
f2 = f1(2:end-1,2:end-1); clear f1
% compute sine tranform
tt = dst(f2); f2sin = dst(tt')'; clear f2
% compute Eigen Values
[x,y] = meshgrid(1:W-2, 1:H-2);
denom = (2*cos(pi*x/(W-1))-2) + (2*cos(pi*y/(H-1)) - 2);
% divide
f3 = f2sin./denom; clear f2sin x y
% compute Inverse Sine Transform
tt = idst(f3); clear f3; img_tt = idst(tt')'; clear tt
% put solution in inner points; outer points obtained from boundary image
img_direct = boundary_image;
img_direct(2:end-1,2:end-1) = 0;
img_direct(2:end-1,2:end-1) = img_tt;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
adjust_psf_center.m
|
.m
|
ConvexOptimization-master/MATLAB/code/utils/adjust_psf_center.m
| 1,453 |
utf_8
|
ffd7dc5a8dc7589030f98a822f6b7c9a
|
function psf = adjust_psf_center(psf)
[X Y] = meshgrid(1:size(psf,2), 1:size(psf,1));
xc1 = sum2(psf .* X);
yc1 = sum2(psf .* Y);
xc2 = (size(psf,2)+1) / 2;
yc2 = (size(psf,1)+1) / 2;
xshift = round(xc2 - xc1);
yshift = round(yc2 - yc1);
psf = warpimage(psf, [1 0 -xshift; 0 1 -yshift]);
function val = sum2(arr)
val = sum(arr(:));
%%
% M should be an inverse transform!
function warped = warpimage(img, M)
if size(img,3) == 3
warped(:,:,1) = warpProjective2(img(:,:,1), M);
warped(:,:,2) = warpProjective2(img(:,:,2), M);
warped(:,:,3) = warpProjective2(img(:,:,3), M);
warped(isnan(warped))=0;
else
warped = warpProjective2(img, M);
warped(isnan(warped))=0;
end
%%
function result = warpProjective2(im,A)
%
% function result = warpProjective2(im,A)
%
% im: input image
% A: 2x3 affine transform matrix or a 3x3 matrix with [0 0 1]
% for the last row.
% if a transformed point is outside of the volume, NaN is used
%
% result: output image, same size as im
%
if (size(A,1)>2)
A=A(1:2,:);
end
% Compute coordinates corresponding to input
% and transformed coordinates for result
[x,y]=meshgrid(1:size(im,2),1:size(im,1));
coords=[x(:)'; y(:)'];
homogeneousCoords=[coords; ones(1,prod(size(im)))];
warpedCoords=A*homogeneousCoords;
xprime=warpedCoords(1,:);%./warpedCoords(3,:);
yprime=warpedCoords(2,:);%./warpedCoords(3,:);
result = interp2(x,y,im,xprime,yprime, 'linear');
result = reshape(result,size(im));
return;
|
github
|
yuanxy92/ConvexOptimization-master
|
deblurring_adm_aniso.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/deblurring_adm_aniso.m
| 2,406 |
utf_8
|
df3c7a21e133a0400474e324ac25aa1b
|
function [I] = deblurring_adm_aniso(B, k, lambda, alpha)
% Solving TV-\ell^2 deblurring problem via ADM/Split Bregman method
%
% This reference of this code is :Fast Image Deconvolution using Hyper-Laplacian Priors
% Original code is created by Dilip Krishnan
% Finally modified by Jinshan Pan 2011/12/25
% Note:
% In this model, aniso TV regularization method is adopted.
% Thus, we do not use the Lookup table method proposed by Dilip Krishnan and Rob Fergus
% Reference: Kernel Estimation from Salient Structure for Robust Motion
% Deblurring
%Last update: (2012/6/20)
beta = 1/lambda;
beta_rate = 2*sqrt(2);
%beta_max = 5*2^10;
beta_min = 0.001;
[m n] = size(B);
% initialize with input or passed in initialization
I = B;
% make sure k is a odd-sized
if ((mod(size(k, 1), 2) ~= 1) | (mod(size(k, 2), 2) ~= 1))
fprintf('Error - blur kernel k must be odd-sized.\n');
return;
end;
[Nomin1, Denom1, Denom2] = computeDenominator(B, k);
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
%% Main loop
while beta > beta_min
gamma = 1/(2*beta);
Denom = Denom1 + gamma*Denom2;
% subproblem for regularization term
if alpha==1
Wx = max(abs(Ix) - beta*lambda, 0).*sign(Ix);
Wy = max(abs(Iy) - beta*lambda, 0).*sign(Iy);
%%
else
Wx = solve_image(Ix, 1/(beta*lambda), alpha);
Wy = solve_image(Iy, 1/(beta*lambda), alpha);
end
Wxx = [Wx(:,n) - Wx(:, 1), -diff(Wx,1,2)];
Wxx = Wxx + [Wy(m,:) - Wy(1, :); -diff(Wy,1,1)];
Fyout = (Nomin1 + gamma*fft2(Wxx))./Denom;
I = real(ifft2(Fyout));
% update the gradient terms with new solution
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
beta = beta/2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Nomin1, Denom1, Denom2] = computeDenominator(y, k)
%
% computes denominator and part of the numerator for Equation (3) of the
% paper
%
% Inputs:
% y: blurry and noisy input
% k: convolution kernel
%
% Outputs:
% Nomin1 -- F(K)'*F(y)
% Denom1 -- |F(K)|.^2
% Denom2 -- |F(D^1)|.^2 + |F(D^2)|.^2
%
sizey = size(y);
otfk = psf2otf(k, sizey);
Nomin1 = conj(otfk).*fft2(y);
Denom1 = abs(otfk).^2;
% if higher-order filters are used, they must be added here too
Denom2 = abs(psf2otf([1,-1],sizey)).^2 + abs(psf2otf([1;-1],sizey)).^2;
|
github
|
yuanxy92/ConvexOptimization-master
|
estimate_psf.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/estimate_psf.m
| 1,290 |
utf_8
|
f570f34e559fd6d11f20feb4f37963d9
|
function psf = estimate_psf(blurred_x, blurred_y, latent_x, latent_y, weight, psf_size)
%----------------------------------------------------------------------
% these values can be pre-computed at the beginning of each level
% blurred_f = fft2(blurred);
% dx_f = psf2otf([1 -1 0], size(blurred));
% dy_f = psf2otf([1;-1;0], size(blurred));
% blurred_xf = dx_f .* blurred_f; %% FFT (Bx)
% blurred_yf = dy_f .* blurred_f; %% FFT (By)
latent_xf = fft2(latent_x);
latent_yf = fft2(latent_y);
blurred_xf = fft2(blurred_x);
blurred_yf = fft2(blurred_y);
% compute b = sum_i w_i latent_i * blurred_i
b_f = conj(latent_xf) .* blurred_xf ...
+ conj(latent_yf) .* blurred_yf;
b = real(otf2psf(b_f, psf_size));
p.m = conj(latent_xf) .* latent_xf ...
+ conj(latent_yf) .* latent_yf;
%p.img_size = size(blurred);
p.img_size = size(blurred_xf);
p.psf_size = psf_size;
p.lambda = weight;
psf = ones(psf_size) / prod(psf_size);
psf = conjgrad(psf, b, 20, 1e-5, @compute_Ax, p);
psf(psf < max(psf(:))*0.05) = 0;
psf = psf / sum(psf(:));
end
function y = compute_Ax(x, p)
x_f = psf2otf(x, p.img_size);
y = otf2psf(p.m .* x_f, p.psf_size);
y = y + p.lambda * x;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
blind_deconv.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/blind_deconv.m
| 4,951 |
utf_8
|
b9995e1e5c0666707be466fdb39c522a
|
function [kernel, interim_latent] = blind_deconv(y, lambda_dark, lambda_grad, opts)
%
% Do multi-scale blind deconvolution
%
%% Input:
% @y : input blurred image (grayscale);
% @lambda_dark: the weight for the L0 regularization on intensity
% @lambda_grad: the weight for the L0 regularization on gradient
% @opts: see the description in the file "demo_text_deblurring.m"
%% Output:
% @kernel: the estimated blur kernel
% @interim_latent: intermediate latent image
%
% The Code is created based on the method described in the following paper
% [1] Jinshan Pan, Deqing Sun, Hanspteter Pfister, and Ming-Hsuan Yang,
% Blind Image Deblurring Using Dark Channel Prior, CVPR, 2016.
% [2] Jinshan Pan, Zhe Hu, Zhixun Su, and Ming-Hsuan Yang,
% Deblurring Text Images via L0-Regularized Intensity and Gradient
% Prior, CVPR, 2014.
%
% Author: Jinshan Pan ([email protected])
% Date : 03/22/2016
% gamma correct
if opts.gamma_correct~=1
y = y.^opts.gamma_correct;
end
b = zeros(opts.kernel_size);
% set kernel size for coarsest level - must be odd
%minsize = max(3, 2*floor(((opts.kernel_size - 1)/16)) + 1);
%fprintf('Kernel size at coarsest level is %d\n', maxitr);
%%
ret = sqrt(0.5);
%%
maxitr=max(floor(log(5/min(opts.kernel_size))/log(ret)),0);
num_scales = maxitr + 1;
fprintf('Maximum iteration level is %d\n', num_scales);
%%
retv=ret.^[0:maxitr];
k1list=ceil(opts.kernel_size*retv);
k1list=k1list+(mod(k1list,2)==0);
k2list=ceil(opts.kernel_size*retv);
k2list=k2list+(mod(k2list,2)==0);
% derivative filters
dx = [-1 1; 0 0];
dy = [-1 0; 1 0];
% blind deconvolution - multiscale processing
for s = num_scales:-1:1
if (s == num_scales)
%%
% at coarsest level, initialize kernel
ks = init_kernel(k1list(s));
k1 = k1list(s);
k2 = k1; % always square kernel assumed
else
% upsample kernel from previous level to next finer level
k1 = k1list(s);
k2 = k1; % always square kernel assumed
% resize kernel from previous level
ks = resizeKer(ks,1/ret,k1list(s),k2list(s));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
cret=retv(s);
ys=downSmpImC(y,cret);
fprintf('Processing scale %d/%d; kernel size %dx%d; image size %dx%d\n', ...
s, num_scales, k1, k2, size(ys,1), size(ys,2));
%-----------------------------------------------------------%
%% Useless operation
if (s == num_scales)
[~, ~, threshold]= threshold_pxpy_v1(ys,max(size(ks)));
%% Initialize the parameter: ???
% if threshold<lambda_grad/10&&threshold~=0;
% lambda_grad = threshold;
% %lambda_dark = threshold_image_v1(ys);
% lambda_dark = lambda_grad;
% end
end
%-----------------------------------------------------------%
[ks, lambda_dark, lambda_grad, interim_latent] = blind_deconv_main(ys, ks, lambda_dark,...
lambda_grad, threshold, opts);
%% center the kernel
ks = adjust_psf_center(ks);
ks(ks(:)<0) = 0;
sumk = sum(ks(:));
ks = ks./sumk;
%% set elements below threshold to 0
if (s == 1)
kernel = ks;
if opts.k_thresh>0
kernel(kernel(:) < max(kernel(:))/opts.k_thresh) = 0;
else
kernel(kernel(:) < 0) = 0;
end
kernel = kernel / sum(kernel(:));
end;
end;
%% end kernel estimation
end
%% Sub-function
function [k] = init_kernel(minsize)
k = zeros(minsize, minsize);
k((minsize - 1)/2, (minsize - 1)/2:(minsize - 1)/2+1) = 1/2;
end
%%
function sI=downSmpImC(I,ret)
%% refer to Levin's code
if (ret==1)
sI=I;
return
end
%%%%%%%%%%%%%%%%%%%
sig=1/pi*ret;
g0=[-50:50]*2*pi;
sf=exp(-0.5*g0.^2*sig^2);
sf=sf/sum(sf);
csf=cumsum(sf);
csf=min(csf,csf(end:-1:1));
ii=find(csf>0.05);
sf=sf(ii);
sum(sf);
I=conv2(sf,sf',I,'valid');
[gx,gy]=meshgrid([1:1/ret:size(I,2)],[1:1/ret:size(I,1)]);
sI=interp2(I,gx,gy,'bilinear');
end
%%
function k=resizeKer(k,ret,k1,k2)
%%
% levin's code
k=imresize(k,ret);
k=max(k,0);
k=fixsize(k,k1,k2);
if max(k(:))>0
k=k/sum(k(:));
end
end
%%
function nf=fixsize(f,nk1,nk2)
[k1,k2]=size(f);
while((k1~=nk1)|(k2~=nk2))
if (k1>nk1)
s=sum(f,2);
if (s(1)<s(end))
f=f(2:end,:);
else
f=f(1:end-1,:);
end
end
if (k1<nk1)
s=sum(f,2);
if (s(1)<s(end))
tf=zeros(k1+1,size(f,2));
tf(1:k1,:)=f;
f=tf;
else
tf=zeros(k1+1,size(f,2));
tf(2:k1+1,:)=f;
f=tf;
end
end
if (k2>nk2)
s=sum(f,1);
if (s(1)<s(end))
f=f(:,2:end);
else
f=f(:,1:end-1);
end
end
if (k2<nk2)
s=sum(f,1);
if (s(1)<s(end))
tf=zeros(size(f,1),k2+1);
tf(:,1:k2)=f;
f=tf;
else
tf=zeros(size(f,1),k2+1);
tf(:,2:k2+1)=f;
f=tf;
end
end
[k1,k2]=size(f);
end
nf=f;
end
%%
|
github
|
yuanxy92/ConvexOptimization-master
|
wrap_boundary_liu.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/cho_code/wrap_boundary_liu.m
| 3,568 |
utf_8
|
778eb4d6eeeb26991f536cb17154be69
|
function ret = wrap_boundary_liu(img, img_size)
% wrap_boundary_liu.m
%
% pad image boundaries such that image boundaries are circularly smooth
%
% written by Sunghyun Cho ([email protected])
%
% This is a variant of the method below:
% Reducing boundary artifacts in image deconvolution
% Renting Liu, Jiaya Jia
% ICIP 2008
%
[H, W, Ch] = size(img);
H_w = img_size(1) - H;
W_w = img_size(2) - W;
ret = zeros(img_size(1), img_size(2), Ch);
for ch = 1:Ch
alpha = 1;
HG = img(:,:,ch);
r_A = zeros(alpha*2+H_w, W);
r_A(1:alpha, :) = HG(end-alpha+1:end, :);
r_A(end-alpha+1:end, :) = HG(1:alpha, :);
a = ((1:H_w)-1)/(H_w-1);
r_A(alpha+1:end-alpha, 1) = (1-a)*r_A(alpha,1) + a*r_A(end-alpha+1,1);
r_A(alpha+1:end-alpha, end) = (1-a)*r_A(alpha,end) + a*r_A(end-alpha+1,end);
A2 = solve_min_laplacian(r_A(alpha:end-alpha+1,:));
r_A(alpha:end-alpha+1,:) = A2;
A = r_A;
r_B = zeros(H, alpha*2+W_w);
r_B(:, 1:alpha) = HG(:, end-alpha+1:end);
r_B(:, end-alpha+1:end) = HG(:, 1:alpha);
a = ((1:W_w)-1)/(W_w-1);
r_B(1, alpha+1:end-alpha) = (1-a)*r_B(1,alpha) + a*r_B(1,end-alpha+1);
r_B(end, alpha+1:end-alpha) = (1-a)*r_B(end,alpha) + a*r_B(end,end-alpha+1);
B2 = solve_min_laplacian(r_B(:, alpha:end-alpha+1));
r_B(:,alpha:end-alpha+1,:) = B2;
B = r_B;
r_C = zeros(alpha*2+H_w, alpha*2+W_w);
r_C(1:alpha, :) = B(end-alpha+1:end, :);
r_C(end-alpha+1:end, :) = B(1:alpha, :);
r_C(:, 1:alpha) = A(:, end-alpha+1:end);
r_C(:, end-alpha+1:end) = A(:, 1:alpha);
C2 = solve_min_laplacian(r_C(alpha:end-alpha+1, alpha:end-alpha+1));
r_C(alpha:end-alpha+1, alpha:end-alpha+1) = C2;
C = r_C;
A = A(alpha:end-alpha-1, :);
B = B(:, alpha+1:end-alpha);
C = C(alpha+1:end-alpha, alpha+1:end-alpha);
ret(:,:,ch) = [img(:,:,ch) B; A C];
end
end
function [img_direct] = solve_min_laplacian(boundary_image)
% function [img_direct] = poisson_solver_function(gx,gy,boundary_image)
% Inputs; Gx and Gy -> Gradients
% Boundary Image -> Boundary image intensities
% Gx Gy and boundary image should be of same size
[H,W] = size(boundary_image);
% Laplacian
f = zeros(H,W); clear j k
% boundary image contains image intensities at boundaries
boundary_image(2:end-1, 2:end-1) = 0;
j = 2:H-1; k = 2:W-1; f_bp = zeros(H,W);
f_bp(j,k) = -4*boundary_image(j,k) + boundary_image(j,k+1) + ...
boundary_image(j,k-1) + boundary_image(j-1,k) + boundary_image(j+1,k);
clear j k
%f1 = f - reshape(f_bp,H,W); % subtract boundary points contribution
f1 = f - f_bp; % subtract boundary points contribution
clear f_bp f
% DST Sine Transform algo starts here
f2 = f1(2:end-1,2:end-1); clear f1
% compute sine tranform
tt = dst(f2); f2sin = dst(tt')'; clear f2
% compute Eigen Values
[x,y] = meshgrid(1:W-2, 1:H-2);
denom = (2*cos(pi*x/(W-1))-2) + (2*cos(pi*y/(H-1)) - 2);
% divide
f3 = f2sin./denom; clear f2sin x y
% compute Inverse Sine Transform
tt = idst(f3); clear f3; img_tt = idst(tt')'; clear tt
% put solution in inner points; outer points obtained from boundary image
img_direct = boundary_image;
img_direct(2:end-1,2:end-1) = 0;
img_direct(2:end-1,2:end-1) = img_tt;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
adjust_psf_center.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/cho_code/adjust_psf_center.m
| 1,453 |
utf_8
|
ffd7dc5a8dc7589030f98a822f6b7c9a
|
function psf = adjust_psf_center(psf)
[X Y] = meshgrid(1:size(psf,2), 1:size(psf,1));
xc1 = sum2(psf .* X);
yc1 = sum2(psf .* Y);
xc2 = (size(psf,2)+1) / 2;
yc2 = (size(psf,1)+1) / 2;
xshift = round(xc2 - xc1);
yshift = round(yc2 - yc1);
psf = warpimage(psf, [1 0 -xshift; 0 1 -yshift]);
function val = sum2(arr)
val = sum(arr(:));
%%
% M should be an inverse transform!
function warped = warpimage(img, M)
if size(img,3) == 3
warped(:,:,1) = warpProjective2(img(:,:,1), M);
warped(:,:,2) = warpProjective2(img(:,:,2), M);
warped(:,:,3) = warpProjective2(img(:,:,3), M);
warped(isnan(warped))=0;
else
warped = warpProjective2(img, M);
warped(isnan(warped))=0;
end
%%
function result = warpProjective2(im,A)
%
% function result = warpProjective2(im,A)
%
% im: input image
% A: 2x3 affine transform matrix or a 3x3 matrix with [0 0 1]
% for the last row.
% if a transformed point is outside of the volume, NaN is used
%
% result: output image, same size as im
%
if (size(A,1)>2)
A=A(1:2,:);
end
% Compute coordinates corresponding to input
% and transformed coordinates for result
[x,y]=meshgrid(1:size(im,2),1:size(im,1));
coords=[x(:)'; y(:)'];
homogeneousCoords=[coords; ones(1,prod(size(im)))];
warpedCoords=A*homogeneousCoords;
xprime=warpedCoords(1,:);%./warpedCoords(3,:);
yprime=warpedCoords(2,:);%./warpedCoords(3,:);
result = interp2(x,y,im,xprime,yprime, 'linear');
result = reshape(result,size(im));
return;
|
github
|
yuanxy92/ConvexOptimization-master
|
padImage.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/whyte_code/padImage.m
| 906 |
utf_8
|
cbc0cf68a7e2e260cfccc8d64309d87f
|
% imPadded = padImage(im, padsize, padval)
% padsize = [top, bottom, left, right]
% padval = valid arguments for padval to padarray. e.g. 'replicate', or 0
%
% for negative padsize, undoes the padding
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function imPadded = padImage(im, padsize, padval)
if nargin < 3, padval = 0; end
if any(padsize < 0)
padsize = -padsize;
imPadded = im(padsize(1)+1:end-padsize(2), padsize(3)+1:end-padsize(4), :);
else
imPadded = padarray( ...
padarray(im, [padsize(1) padsize(3)],padval,'pre'), ...
[padsize(2) padsize(4)],padval,'post');
end
|
github
|
yuanxy92/ConvexOptimization-master
|
calculatePadding.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/whyte_code/calculatePadding.m
| 2,718 |
utf_8
|
620880ec6310f544654fe052967f1fe8
|
% pad = calculatePadding(image_size,non_uniform = 0,kernel)
% pad = calculatePadding(image_size,non_uniform = 1,theta_list,Kinternal)
% where pad = [top, bottom, left, right]
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function [pad_replicate,Kinternal] = calculatePadding(image_size,non_uniform,theta_list,Kinternal)
h_sharp = image_size(1);
w_sharp = image_size(2);
if non_uniform
% Calculate padding
im_corners = [1, 1, w_sharp, w_sharp;...
1, h_sharp, h_sharp, 1;...
1, 1, 1, 1];
pad_replicate_t = 0; % top of image
pad_replicate_b = 0; % bottom of image
pad_replicate_l = 0; % left of image
pad_replicate_r = 0; % right of image
% for each non-zero in the kernel...
for i=1:size(theta_list,2)
% back proect corners of blurry image to see how far out we need to pad
% H = Ksharp*expm(crossmatrix(-theta_list(:,i)))*inv(Kblurry);
H = Kinternal*expm(crossmatrix(-theta_list(:,i)))*inv(Kinternal);
projected_corners_sharp = hnormalise(H*im_corners);
offsets = abs(projected_corners_sharp - im_corners);
if offsets(1,1) > pad_replicate_l, pad_replicate_l = ceil(offsets(1,1)); end
if offsets(1,2) > pad_replicate_l, pad_replicate_l = ceil(offsets(1,2)); end
if offsets(1,3) > pad_replicate_r, pad_replicate_r = ceil(offsets(1,3)); end
if offsets(1,4) > pad_replicate_r, pad_replicate_r = ceil(offsets(1,4)); end
if offsets(2,1) > pad_replicate_t, pad_replicate_t = ceil(offsets(2,1)); end
if offsets(2,2) > pad_replicate_b, pad_replicate_b = ceil(offsets(2,2)); end
if offsets(2,3) > pad_replicate_t, pad_replicate_t = ceil(offsets(2,3)); end
if offsets(2,4) > pad_replicate_b, pad_replicate_b = ceil(offsets(2,4)); end
end
% Adjust calibration matrices to take account padding
Kinternal = htranslate([pad_replicate_l ; pad_replicate_t]) * Kinternal;
else
kernel = theta_list;
pad_replicate_t = ceil((size(kernel,1)-1)/2);
pad_replicate_b = floor((size(kernel,1)-1)/2);
pad_replicate_l = ceil((size(kernel,2)-1)/2);
pad_replicate_r = floor((size(kernel,2)-1)/2);
Kinternal = [];
end
w_sharp = w_sharp + pad_replicate_l + pad_replicate_r;
h_sharp = h_sharp + pad_replicate_t + pad_replicate_b;
% top, bottom, left, right
pad_replicate = [pad_replicate_t, pad_replicate_b, pad_replicate_l, pad_replicate_r];
|
github
|
yuanxy92/ConvexOptimization-master
|
deconvRL.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/whyte_code/deconvRL.m
| 7,302 |
utf_8
|
1bf68715ed3c044f344431243ff2b907
|
% i_rl = deconvRL(imblur, kernel, non_uniform, ...)
% for uniform blur, with non_uniform = 0
%
% i_rl = deconvRL(imblur, kernel, non_uniform, theta_list, Kblurry, ...)
% for non-uniform blur, with non_uniform = 1
%
% Additional arguments, in any order:
% ... , 'forward_saturation', ... use forward model for saturation
% ... , 'prevent_ringing', ... split and re-combine updates to reduce ringing
% ... , 'sat_thresh', T, ... clipping level for forward model of saturation (default is 1.0)
% ... , 'sat_smooth', a, ... smoothness parameter for forward model (default is 50)
% ... , 'num_iters', n, ... number of iterations (default is 50)
% ... , 'init', im_init, ... initial estimate of deblurred image (default is blurry image)
% ... , 'mask', mask, ... binary mask of blurry pixels to use -- 1=use, 0=discard -- (default is all blurry pixels, ie. 1 everywhere)
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function i_rl = deconvRL(imblur,kernel,non_uniform,varargin)
if nargin < 3, non_uniform = 0; end
% Discard small kernel elements for speed
kernel(kernel < max(kernel(:))/100) = 0;
kernel = kernel / sum(kernel(:));
% Parse varargin
if non_uniform
theta_list = varargin{1};
Kblurry = varargin{2};
varargin = varargin(3:end);
% Remove the zero elements of kernel
use_rotations = kernel(:) ~= 0;
kernel = kernel(use_rotations);
theta_list = theta_list(:,use_rotations);
end
params = parseArgs(varargin);
% Get image size
[h,w,channels] = size(imblur);
% Calculate padding based on blur kernel size
if non_uniform
[pad, Kblurry] = calculatePadding([h,w],non_uniform,theta_list,Kblurry);
else
pad = calculatePadding([h,w],non_uniform,kernel);
end
% Pad blurry image by replication to handle edge effects
imblur = padImage(imblur, pad, 'replicate');
% Get new image size
[h,w,channels] = size(imblur);
% Define blur functions depending on blur type
if non_uniform
Ksharp = Kblurry;
blurfn = @(im) apply_blur_kernel_mex(double(im),[h,w],Ksharp,Kblurry,-theta_list,kernel,0,non_uniform);
conjfn = @(im) apply_blur_kernel_mex(double(im),[h,w],Kblurry,Ksharp, theta_list,kernel,0,non_uniform);
dilatefn = @(im) min(apply_blur_kernel_mex(double(im),[h,w],Ksharp,Kblurry,-theta_list,ones(size(kernel)),0,non_uniform), 1);
else
% blurfn = @(im) imfilter(im,kernel,'conv');
% conjfn = @(im) imfilter(im,kernel,'corr');
% dilatefn = @(im) min(imfilter(im,double(kernel~=0),'conv'), 1);
kfft = psf2otf(kernel,[h w]);
k1fft = psf2otf(double(kernel~=0),[h w]);
blurfn = @(im) ifft2(bsxfun(@times,fft2(im),kfft),'symmetric');
conjfn = @(im) ifft2(bsxfun(@times,fft2(im),conj(kfft)),'symmetric');
dilatefn = @(im) min(ifft2(bsxfun(@times,fft2(im),k1fft),'symmetric'), 1);
end
% Mask of "good" blurry pixels
mask = zeros(h,w,channels);
mask(pad(1)+1:h-pad(2),pad(3)+1:w-pad(4),:) = params.mask;
% Initialise sharp image
if isfield(params,'init')
i_rl = padImage(double(params.init),pad,'replicate');
else
i_rl = imblur;
end
fprintf('%d iterations: ',params.num_iters);
% Some fixed filters for dilation and smoothing
dilate_radius = 3;
dilate_filter = bsxfun(@plus,(-dilate_radius:dilate_radius).^2,(-dilate_radius:dilate_radius)'.^2) <= eps+dilate_radius.^2;
smooth_filter = fspecial('gaussian',[21 21],3);
% Main algorithm loop
for iter = 1:params.num_iters
% Apply the linear forward model first (ie. compute A*f)
val_linear = max(blurfn(i_rl),0);
% Apply non-linear response if required
if params.forward_saturation
[val_nonlin,grad_nonlin] = saturate(val_linear,params.sat_thresh,params.sat_smooth);
else
val_nonlin = val_linear;
grad_nonlin = 1;
end
% Compute the raw error ratio for the current estimate of the sharp image
error_ratio = imblur ./ max(val_nonlin,eps);
error_ratio_masked_nonlin = (error_ratio - 1).*mask.*grad_nonlin;
if params.prevent_ringing
% Find hard-to-estimate pixels in sharp image (set S in paper)
S_mask = double(imdilate(i_rl >= 0.9, dilate_filter));
% Find the blurry pixels NOT influenced by pixels in S (set V in paper)
V_mask = 1 - dilatefn(S_mask);
% Apply conjugate blur function (ie. multiply by A')
update_ratio_U = conjfn(error_ratio_masked_nonlin.*V_mask) + 1; % update U using only data from V
update_ratio_S = conjfn(error_ratio_masked_nonlin) + 1; % update S using all data
% Blur the mask of hard-to-estimate pixels for recombining without artefacts
weights = imfilter(S_mask, smooth_filter);
% Combine updates for the two sets into a single update
% update_ratio = update_ratio_S.*weights + update_ratio_U.*(1-weights);
update_ratio = update_ratio_U + (update_ratio_S - update_ratio_U).*weights;
else
% Apply conjugate blur function (ie. multiply by A')
update_ratio = conjfn(error_ratio_masked_nonlin) + 1;
end
% Avoid negative updates, which cause trouble
update_ratio = max(update_ratio,0);
if any(isnan(update_ratio(:))), error('NaNs in update ratio'); end
% Apply update ratio
i_rl = update_ratio .* i_rl;
fprintf('%d ',iter);
end
fprintf('\n');
% Remove padding on output image
i_rl = padImage(i_rl, -pad);
end
% =====================================================================================
function params = parseArgs(args,params)
if nargin < 2
params = struct('num_iters',50,'forward_saturation',false,'prevent_ringing',false,'sat_thresh',1,'sat_smooth',50,'mask',1);
end
if ~isempty(args)
switch args{1}
case 'num_iters'
params.num_iters = args{2};
args = args(3:end);
case 'sat_thresh'
params.sat_thresh = args{2};
args = args(3:end);
case 'sat_smooth'
params.sat_smooth = args{2};
args = args(3:end);
case 'forward_saturation'
params.forward_saturation = true;
args = args(2:end);
case 'prevent_ringing'
params.prevent_ringing = true;
args = args(2:end);
case 'init'
params.init = args{2};
args = args(3:end);
case 'mask'
params.mask = args{2};
args = args(3:end);
otherwise
error('Invalid argument');
end
% Recursively parse remaining arguments
params = parseArgs(args,params);
end
end
% ============================================================================
function [val,grad] = saturate(x,t,a)
if a==inf
[val,grad] = sharpsaturate(x, t);
else
% Adapted from: C. Chen and O. L. Mangasarian. ``A Class of Smoothing Functions
% for Nonlinear and Mixed Complementarity Problems''.
% Computational Optimization and Applications, 1996.
one_p_exp = 1 + exp(-a*(t-x));
val = x - 1/a * log(one_p_exp);
grad = 1 ./ one_p_exp;
end
end
% ============================================================================
function [val,grad] = sharpsaturate(x,t)
val = x;
grad = ones(size(x));
mask = x>t;
val(mask) = t;
grad(mask) = 0;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
crossmatrix.m
|
.m
|
ConvexOptimization-master/MATLAB/cvpr16_deblurring_code_v1/whyte_code/crossmatrix.m
| 417 |
utf_8
|
cac6f7c9c7414f240720e5a918c7c776
|
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function vx = crossmatrix(v)
vx = [ 0, -v(3), v(2);...
v(3), 0, -v(1);...
-v(2), v(1), 0];
|
github
|
yuanxy92/ConvexOptimization-master
|
deblurring_adm_aniso.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/deblurring_adm_aniso.m
| 2,406 |
utf_8
|
df3c7a21e133a0400474e324ac25aa1b
|
function [I] = deblurring_adm_aniso(B, k, lambda, alpha)
% Solving TV-\ell^2 deblurring problem via ADM/Split Bregman method
%
% This reference of this code is :Fast Image Deconvolution using Hyper-Laplacian Priors
% Original code is created by Dilip Krishnan
% Finally modified by Jinshan Pan 2011/12/25
% Note:
% In this model, aniso TV regularization method is adopted.
% Thus, we do not use the Lookup table method proposed by Dilip Krishnan and Rob Fergus
% Reference: Kernel Estimation from Salient Structure for Robust Motion
% Deblurring
%Last update: (2012/6/20)
beta = 1/lambda;
beta_rate = 2*sqrt(2);
%beta_max = 5*2^10;
beta_min = 0.001;
[m n] = size(B);
% initialize with input or passed in initialization
I = B;
% make sure k is a odd-sized
if ((mod(size(k, 1), 2) ~= 1) | (mod(size(k, 2), 2) ~= 1))
fprintf('Error - blur kernel k must be odd-sized.\n');
return;
end;
[Nomin1, Denom1, Denom2] = computeDenominator(B, k);
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
%% Main loop
while beta > beta_min
gamma = 1/(2*beta);
Denom = Denom1 + gamma*Denom2;
% subproblem for regularization term
if alpha==1
Wx = max(abs(Ix) - beta*lambda, 0).*sign(Ix);
Wy = max(abs(Iy) - beta*lambda, 0).*sign(Iy);
%%
else
Wx = solve_image(Ix, 1/(beta*lambda), alpha);
Wy = solve_image(Iy, 1/(beta*lambda), alpha);
end
Wxx = [Wx(:,n) - Wx(:, 1), -diff(Wx,1,2)];
Wxx = Wxx + [Wy(m,:) - Wy(1, :); -diff(Wy,1,1)];
Fyout = (Nomin1 + gamma*fft2(Wxx))./Denom;
I = real(ifft2(Fyout));
% update the gradient terms with new solution
Ix = [diff(I, 1, 2), I(:,1) - I(:,n)];
Iy = [diff(I, 1, 1); I(1,:) - I(m,:)];
beta = beta/2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Nomin1, Denom1, Denom2] = computeDenominator(y, k)
%
% computes denominator and part of the numerator for Equation (3) of the
% paper
%
% Inputs:
% y: blurry and noisy input
% k: convolution kernel
%
% Outputs:
% Nomin1 -- F(K)'*F(y)
% Denom1 -- |F(K)|.^2
% Denom2 -- |F(D^1)|.^2 + |F(D^2)|.^2
%
sizey = size(y);
otfk = psf2otf(k, sizey);
Nomin1 = conj(otfk).*fft2(y);
Denom1 = abs(otfk).^2;
% if higher-order filters are used, they must be added here too
Denom2 = abs(psf2otf([1,-1],sizey)).^2 + abs(psf2otf([1;-1],sizey)).^2;
|
github
|
yuanxy92/ConvexOptimization-master
|
estimate_psf.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/estimate_psf.m
| 1,290 |
utf_8
|
f570f34e559fd6d11f20feb4f37963d9
|
function psf = estimate_psf(blurred_x, blurred_y, latent_x, latent_y, weight, psf_size)
%----------------------------------------------------------------------
% these values can be pre-computed at the beginning of each level
% blurred_f = fft2(blurred);
% dx_f = psf2otf([1 -1 0], size(blurred));
% dy_f = psf2otf([1;-1;0], size(blurred));
% blurred_xf = dx_f .* blurred_f; %% FFT (Bx)
% blurred_yf = dy_f .* blurred_f; %% FFT (By)
latent_xf = fft2(latent_x);
latent_yf = fft2(latent_y);
blurred_xf = fft2(blurred_x);
blurred_yf = fft2(blurred_y);
% compute b = sum_i w_i latent_i * blurred_i
b_f = conj(latent_xf) .* blurred_xf ...
+ conj(latent_yf) .* blurred_yf;
b = real(otf2psf(b_f, psf_size));
p.m = conj(latent_xf) .* latent_xf ...
+ conj(latent_yf) .* latent_yf;
%p.img_size = size(blurred);
p.img_size = size(blurred_xf);
p.psf_size = psf_size;
p.lambda = weight;
psf = ones(psf_size) / prod(psf_size);
psf = conjgrad(psf, b, 20, 1e-5, @compute_Ax, p);
psf(psf < max(psf(:))*0.05) = 0;
psf = psf / sum(psf(:));
end
function y = compute_Ax(x, p)
x_f = psf2otf(x, p.img_size);
y = otf2psf(p.m .* x_f, p.psf_size);
y = y + p.lambda * x;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
blind_deconv.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/blind_deconv.m
| 4,802 |
utf_8
|
3f6f793caaf4b9bb62ab9c91970af2ea
|
function [kernel, interim_latent] = blind_deconv(y, lambda_pixel, lambda_grad, opts)
%
% Do multi-scale blind deconvolution
%
%% Input:
% @y : input blurred image (grayscale);
% @lambda_pixel: the weight for the L0 regularization on intensity
% @lambda_grad: the weight for the L0 regularization on gradient
% @opts: see the description in the file "demo_text_deblurring.m"
%% Output:
% @kernel: the estimated blur kernel
% @interim_latent: intermediate latent image
%
% The Code is created based on the method described in the following paper
% Jinshan Pan, Zhe Hu, Zhixun Su, and Ming-Hsuan Yang,
% Deblurring Text Images via L0-Regularized Intensity and Gradient
% Prior, CVPR, 2014.
% Author: Jinshan Pan ([email protected])
% Date : 05/18/2014
% gamma correct
if opts.gamma_correct~=1
y = y.^opts.gamma_correct;
end
b = zeros(opts.kernel_size);
% set kernel size for coarsest level - must be odd
%minsize = max(3, 2*floor(((opts.kernel_size - 1)/16)) + 1);
%fprintf('Kernel size at coarsest level is %d\n', maxitr);
%%
ret = sqrt(0.5);
%%
maxitr=max(floor(log(5/min(opts.kernel_size))/log(ret)),0);
num_scales = maxitr + 1;
fprintf('Maximum iteration level is %d\n', num_scales);
%%
retv=ret.^[0:maxitr];
k1list=ceil(opts.kernel_size*retv);
k1list=k1list+(mod(k1list,2)==0);
k2list=ceil(opts.kernel_size*retv);
k2list=k2list+(mod(k2list,2)==0);
% derivative filters
dx = [-1 1; 0 0];
dy = [-1 0; 1 0];
% blind deconvolution - multiscale processing
for s = num_scales:-1:1
if (s == num_scales)
%%
% at coarsest level, initialize kernel
ks = init_kernel(k1list(s));
k1 = k1list(s);
k2 = k1; % always square kernel assumed
else
% upsample kernel from previous level to next finer level
k1 = k1list(s);
k2 = k1; % always square kernel assumed
% resize kernel from previous level
ks = resizeKer(ks,1/ret,k1list(s),k2list(s));
end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%
cret=retv(s);
ys=downSmpImC(y,cret);
fprintf('Processing scale %d/%d; kernel size %dx%d; image size %dx%d\n', ...
s, num_scales, k1, k2, size(ys,1), size(ys,2));
%-----------------------------------------------------------%
%% Useless operation
if (s == num_scales)
[~, ~, threshold]= threshold_pxpy_v1(ys,max(size(ks)));
%% Initialize the parameter: ???
if threshold<lambda_grad/10&&threshold~=0;
lambda_grad = threshold;
%lambda_pixel = threshold_image_v1(ys);
lambda_pixel = lambda_grad;
end
end
%-----------------------------------------------------------%
[ks, lambda_pixel, lambda_grad, interim_latent] = blind_deconv_main(ys, ks, lambda_pixel,...
lambda_grad, threshold, opts);
%% center the kernel
ks = adjust_psf_center(ks);
ks(ks(:)<0) = 0;
sumk = sum(ks(:));
ks = ks./sumk;
%% set elements below threshold to 0
if (s == 1)
kernel = ks;
if opts.k_thresh>0
kernel(kernel(:) < max(kernel(:))/opts.k_thresh) = 0;
else
kernel(kernel(:) < 0) = 0;
end
kernel = kernel / sum(kernel(:));
end;
end;
%% end kernel estimation
end
%% Sub-function
function [k] = init_kernel(minsize)
k = zeros(minsize, minsize);
k((minsize - 1)/2, (minsize - 1)/2:(minsize - 1)/2+1) = 1/2;
end
%%
function sI=downSmpImC(I,ret)
%% refer to Levin's code
if (ret==1)
sI=I;
return
end
%%%%%%%%%%%%%%%%%%%
sig=1/pi*ret;
g0=[-50:50]*2*pi;
sf=exp(-0.5*g0.^2*sig^2);
sf=sf/sum(sf);
csf=cumsum(sf);
csf=min(csf,csf(end:-1:1));
ii=find(csf>0.05);
sf=sf(ii);
sum(sf);
I=conv2(sf,sf',I,'valid');
[gx,gy]=meshgrid([1:1/ret:size(I,2)],[1:1/ret:size(I,1)]);
sI=interp2(I,gx,gy,'bilinear');
end
%%
function k=resizeKer(k,ret,k1,k2)
%%
% levin's code
k=imresize(k,ret);
k=max(k,0);
k=fixsize(k,k1,k2);
if max(k(:))>0
k=k/sum(k(:));
end
end
%%
function nf=fixsize(f,nk1,nk2)
[k1,k2]=size(f);
while((k1~=nk1)|(k2~=nk2))
if (k1>nk1)
s=sum(f,2);
if (s(1)<s(end))
f=f(2:end,:);
else
f=f(1:end-1,:);
end
end
if (k1<nk1)
s=sum(f,2);
if (s(1)<s(end))
tf=zeros(k1+1,size(f,2));
tf(1:k1,:)=f;
f=tf;
else
tf=zeros(k1+1,size(f,2));
tf(2:k1+1,:)=f;
f=tf;
end
end
if (k2>nk2)
s=sum(f,1);
if (s(1)<s(end))
f=f(:,2:end);
else
f=f(:,1:end-1);
end
end
if (k2<nk2)
s=sum(f,1);
if (s(1)<s(end))
tf=zeros(size(f,1),k2+1);
tf(:,1:k2)=f;
f=tf;
else
tf=zeros(size(f,1),k2+1);
tf(:,2:k2+1)=f;
f=tf;
end
end
[k1,k2]=size(f);
end
nf=f;
end
%%
|
github
|
yuanxy92/ConvexOptimization-master
|
wrap_boundary_liu.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/cho_code/wrap_boundary_liu.m
| 3,568 |
utf_8
|
778eb4d6eeeb26991f536cb17154be69
|
function ret = wrap_boundary_liu(img, img_size)
% wrap_boundary_liu.m
%
% pad image boundaries such that image boundaries are circularly smooth
%
% written by Sunghyun Cho ([email protected])
%
% This is a variant of the method below:
% Reducing boundary artifacts in image deconvolution
% Renting Liu, Jiaya Jia
% ICIP 2008
%
[H, W, Ch] = size(img);
H_w = img_size(1) - H;
W_w = img_size(2) - W;
ret = zeros(img_size(1), img_size(2), Ch);
for ch = 1:Ch
alpha = 1;
HG = img(:,:,ch);
r_A = zeros(alpha*2+H_w, W);
r_A(1:alpha, :) = HG(end-alpha+1:end, :);
r_A(end-alpha+1:end, :) = HG(1:alpha, :);
a = ((1:H_w)-1)/(H_w-1);
r_A(alpha+1:end-alpha, 1) = (1-a)*r_A(alpha,1) + a*r_A(end-alpha+1,1);
r_A(alpha+1:end-alpha, end) = (1-a)*r_A(alpha,end) + a*r_A(end-alpha+1,end);
A2 = solve_min_laplacian(r_A(alpha:end-alpha+1,:));
r_A(alpha:end-alpha+1,:) = A2;
A = r_A;
r_B = zeros(H, alpha*2+W_w);
r_B(:, 1:alpha) = HG(:, end-alpha+1:end);
r_B(:, end-alpha+1:end) = HG(:, 1:alpha);
a = ((1:W_w)-1)/(W_w-1);
r_B(1, alpha+1:end-alpha) = (1-a)*r_B(1,alpha) + a*r_B(1,end-alpha+1);
r_B(end, alpha+1:end-alpha) = (1-a)*r_B(end,alpha) + a*r_B(end,end-alpha+1);
B2 = solve_min_laplacian(r_B(:, alpha:end-alpha+1));
r_B(:,alpha:end-alpha+1,:) = B2;
B = r_B;
r_C = zeros(alpha*2+H_w, alpha*2+W_w);
r_C(1:alpha, :) = B(end-alpha+1:end, :);
r_C(end-alpha+1:end, :) = B(1:alpha, :);
r_C(:, 1:alpha) = A(:, end-alpha+1:end);
r_C(:, end-alpha+1:end) = A(:, 1:alpha);
C2 = solve_min_laplacian(r_C(alpha:end-alpha+1, alpha:end-alpha+1));
r_C(alpha:end-alpha+1, alpha:end-alpha+1) = C2;
C = r_C;
A = A(alpha:end-alpha-1, :);
B = B(:, alpha+1:end-alpha);
C = C(alpha+1:end-alpha, alpha+1:end-alpha);
ret(:,:,ch) = [img(:,:,ch) B; A C];
end
end
function [img_direct] = solve_min_laplacian(boundary_image)
% function [img_direct] = poisson_solver_function(gx,gy,boundary_image)
% Inputs; Gx and Gy -> Gradients
% Boundary Image -> Boundary image intensities
% Gx Gy and boundary image should be of same size
[H,W] = size(boundary_image);
% Laplacian
f = zeros(H,W); clear j k
% boundary image contains image intensities at boundaries
boundary_image(2:end-1, 2:end-1) = 0;
j = 2:H-1; k = 2:W-1; f_bp = zeros(H,W);
f_bp(j,k) = -4*boundary_image(j,k) + boundary_image(j,k+1) + ...
boundary_image(j,k-1) + boundary_image(j-1,k) + boundary_image(j+1,k);
clear j k
%f1 = f - reshape(f_bp,H,W); % subtract boundary points contribution
f1 = f - f_bp; % subtract boundary points contribution
clear f_bp f
% DST Sine Transform algo starts here
f2 = f1(2:end-1,2:end-1); clear f1
% compute sine tranform
tt = dst(f2); f2sin = dst(tt')'; clear f2
% compute Eigen Values
[x,y] = meshgrid(1:W-2, 1:H-2);
denom = (2*cos(pi*x/(W-1))-2) + (2*cos(pi*y/(H-1)) - 2);
% divide
f3 = f2sin./denom; clear f2sin x y
% compute Inverse Sine Transform
tt = idst(f3); clear f3; img_tt = idst(tt')'; clear tt
% put solution in inner points; outer points obtained from boundary image
img_direct = boundary_image;
img_direct(2:end-1,2:end-1) = 0;
img_direct(2:end-1,2:end-1) = img_tt;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
adjust_psf_center.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/cho_code/adjust_psf_center.m
| 1,453 |
utf_8
|
ffd7dc5a8dc7589030f98a822f6b7c9a
|
function psf = adjust_psf_center(psf)
[X Y] = meshgrid(1:size(psf,2), 1:size(psf,1));
xc1 = sum2(psf .* X);
yc1 = sum2(psf .* Y);
xc2 = (size(psf,2)+1) / 2;
yc2 = (size(psf,1)+1) / 2;
xshift = round(xc2 - xc1);
yshift = round(yc2 - yc1);
psf = warpimage(psf, [1 0 -xshift; 0 1 -yshift]);
function val = sum2(arr)
val = sum(arr(:));
%%
% M should be an inverse transform!
function warped = warpimage(img, M)
if size(img,3) == 3
warped(:,:,1) = warpProjective2(img(:,:,1), M);
warped(:,:,2) = warpProjective2(img(:,:,2), M);
warped(:,:,3) = warpProjective2(img(:,:,3), M);
warped(isnan(warped))=0;
else
warped = warpProjective2(img, M);
warped(isnan(warped))=0;
end
%%
function result = warpProjective2(im,A)
%
% function result = warpProjective2(im,A)
%
% im: input image
% A: 2x3 affine transform matrix or a 3x3 matrix with [0 0 1]
% for the last row.
% if a transformed point is outside of the volume, NaN is used
%
% result: output image, same size as im
%
if (size(A,1)>2)
A=A(1:2,:);
end
% Compute coordinates corresponding to input
% and transformed coordinates for result
[x,y]=meshgrid(1:size(im,2),1:size(im,1));
coords=[x(:)'; y(:)'];
homogeneousCoords=[coords; ones(1,prod(size(im)))];
warpedCoords=A*homogeneousCoords;
xprime=warpedCoords(1,:);%./warpedCoords(3,:);
yprime=warpedCoords(2,:);%./warpedCoords(3,:);
result = interp2(x,y,im,xprime,yprime, 'linear');
result = reshape(result,size(im));
return;
|
github
|
yuanxy92/ConvexOptimization-master
|
padImage.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/whyte_code/padImage.m
| 906 |
utf_8
|
cbc0cf68a7e2e260cfccc8d64309d87f
|
% imPadded = padImage(im, padsize, padval)
% padsize = [top, bottom, left, right]
% padval = valid arguments for padval to padarray. e.g. 'replicate', or 0
%
% for negative padsize, undoes the padding
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function imPadded = padImage(im, padsize, padval)
if nargin < 3, padval = 0; end
if any(padsize < 0)
padsize = -padsize;
imPadded = im(padsize(1)+1:end-padsize(2), padsize(3)+1:end-padsize(4), :);
else
imPadded = padarray( ...
padarray(im, [padsize(1) padsize(3)],padval,'pre'), ...
[padsize(2) padsize(4)],padval,'post');
end
|
github
|
yuanxy92/ConvexOptimization-master
|
calculatePadding.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/whyte_code/calculatePadding.m
| 2,718 |
utf_8
|
620880ec6310f544654fe052967f1fe8
|
% pad = calculatePadding(image_size,non_uniform = 0,kernel)
% pad = calculatePadding(image_size,non_uniform = 1,theta_list,Kinternal)
% where pad = [top, bottom, left, right]
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function [pad_replicate,Kinternal] = calculatePadding(image_size,non_uniform,theta_list,Kinternal)
h_sharp = image_size(1);
w_sharp = image_size(2);
if non_uniform
% Calculate padding
im_corners = [1, 1, w_sharp, w_sharp;...
1, h_sharp, h_sharp, 1;...
1, 1, 1, 1];
pad_replicate_t = 0; % top of image
pad_replicate_b = 0; % bottom of image
pad_replicate_l = 0; % left of image
pad_replicate_r = 0; % right of image
% for each non-zero in the kernel...
for i=1:size(theta_list,2)
% back proect corners of blurry image to see how far out we need to pad
% H = Ksharp*expm(crossmatrix(-theta_list(:,i)))*inv(Kblurry);
H = Kinternal*expm(crossmatrix(-theta_list(:,i)))*inv(Kinternal);
projected_corners_sharp = hnormalise(H*im_corners);
offsets = abs(projected_corners_sharp - im_corners);
if offsets(1,1) > pad_replicate_l, pad_replicate_l = ceil(offsets(1,1)); end
if offsets(1,2) > pad_replicate_l, pad_replicate_l = ceil(offsets(1,2)); end
if offsets(1,3) > pad_replicate_r, pad_replicate_r = ceil(offsets(1,3)); end
if offsets(1,4) > pad_replicate_r, pad_replicate_r = ceil(offsets(1,4)); end
if offsets(2,1) > pad_replicate_t, pad_replicate_t = ceil(offsets(2,1)); end
if offsets(2,2) > pad_replicate_b, pad_replicate_b = ceil(offsets(2,2)); end
if offsets(2,3) > pad_replicate_t, pad_replicate_t = ceil(offsets(2,3)); end
if offsets(2,4) > pad_replicate_b, pad_replicate_b = ceil(offsets(2,4)); end
end
% Adjust calibration matrices to take account padding
Kinternal = htranslate([pad_replicate_l ; pad_replicate_t]) * Kinternal;
else
kernel = theta_list;
pad_replicate_t = ceil((size(kernel,1)-1)/2);
pad_replicate_b = floor((size(kernel,1)-1)/2);
pad_replicate_l = ceil((size(kernel,2)-1)/2);
pad_replicate_r = floor((size(kernel,2)-1)/2);
Kinternal = [];
end
w_sharp = w_sharp + pad_replicate_l + pad_replicate_r;
h_sharp = h_sharp + pad_replicate_t + pad_replicate_b;
% top, bottom, left, right
pad_replicate = [pad_replicate_t, pad_replicate_b, pad_replicate_l, pad_replicate_r];
|
github
|
yuanxy92/ConvexOptimization-master
|
deconvRL.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/whyte_code/deconvRL.m
| 7,302 |
utf_8
|
1bf68715ed3c044f344431243ff2b907
|
% i_rl = deconvRL(imblur, kernel, non_uniform, ...)
% for uniform blur, with non_uniform = 0
%
% i_rl = deconvRL(imblur, kernel, non_uniform, theta_list, Kblurry, ...)
% for non-uniform blur, with non_uniform = 1
%
% Additional arguments, in any order:
% ... , 'forward_saturation', ... use forward model for saturation
% ... , 'prevent_ringing', ... split and re-combine updates to reduce ringing
% ... , 'sat_thresh', T, ... clipping level for forward model of saturation (default is 1.0)
% ... , 'sat_smooth', a, ... smoothness parameter for forward model (default is 50)
% ... , 'num_iters', n, ... number of iterations (default is 50)
% ... , 'init', im_init, ... initial estimate of deblurred image (default is blurry image)
% ... , 'mask', mask, ... binary mask of blurry pixels to use -- 1=use, 0=discard -- (default is all blurry pixels, ie. 1 everywhere)
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function i_rl = deconvRL(imblur,kernel,non_uniform,varargin)
if nargin < 3, non_uniform = 0; end
% Discard small kernel elements for speed
kernel(kernel < max(kernel(:))/100) = 0;
kernel = kernel / sum(kernel(:));
% Parse varargin
if non_uniform
theta_list = varargin{1};
Kblurry = varargin{2};
varargin = varargin(3:end);
% Remove the zero elements of kernel
use_rotations = kernel(:) ~= 0;
kernel = kernel(use_rotations);
theta_list = theta_list(:,use_rotations);
end
params = parseArgs(varargin);
% Get image size
[h,w,channels] = size(imblur);
% Calculate padding based on blur kernel size
if non_uniform
[pad, Kblurry] = calculatePadding([h,w],non_uniform,theta_list,Kblurry);
else
pad = calculatePadding([h,w],non_uniform,kernel);
end
% Pad blurry image by replication to handle edge effects
imblur = padImage(imblur, pad, 'replicate');
% Get new image size
[h,w,channels] = size(imblur);
% Define blur functions depending on blur type
if non_uniform
Ksharp = Kblurry;
blurfn = @(im) apply_blur_kernel_mex(double(im),[h,w],Ksharp,Kblurry,-theta_list,kernel,0,non_uniform);
conjfn = @(im) apply_blur_kernel_mex(double(im),[h,w],Kblurry,Ksharp, theta_list,kernel,0,non_uniform);
dilatefn = @(im) min(apply_blur_kernel_mex(double(im),[h,w],Ksharp,Kblurry,-theta_list,ones(size(kernel)),0,non_uniform), 1);
else
% blurfn = @(im) imfilter(im,kernel,'conv');
% conjfn = @(im) imfilter(im,kernel,'corr');
% dilatefn = @(im) min(imfilter(im,double(kernel~=0),'conv'), 1);
kfft = psf2otf(kernel,[h w]);
k1fft = psf2otf(double(kernel~=0),[h w]);
blurfn = @(im) ifft2(bsxfun(@times,fft2(im),kfft),'symmetric');
conjfn = @(im) ifft2(bsxfun(@times,fft2(im),conj(kfft)),'symmetric');
dilatefn = @(im) min(ifft2(bsxfun(@times,fft2(im),k1fft),'symmetric'), 1);
end
% Mask of "good" blurry pixels
mask = zeros(h,w,channels);
mask(pad(1)+1:h-pad(2),pad(3)+1:w-pad(4),:) = params.mask;
% Initialise sharp image
if isfield(params,'init')
i_rl = padImage(double(params.init),pad,'replicate');
else
i_rl = imblur;
end
fprintf('%d iterations: ',params.num_iters);
% Some fixed filters for dilation and smoothing
dilate_radius = 3;
dilate_filter = bsxfun(@plus,(-dilate_radius:dilate_radius).^2,(-dilate_radius:dilate_radius)'.^2) <= eps+dilate_radius.^2;
smooth_filter = fspecial('gaussian',[21 21],3);
% Main algorithm loop
for iter = 1:params.num_iters
% Apply the linear forward model first (ie. compute A*f)
val_linear = max(blurfn(i_rl),0);
% Apply non-linear response if required
if params.forward_saturation
[val_nonlin,grad_nonlin] = saturate(val_linear,params.sat_thresh,params.sat_smooth);
else
val_nonlin = val_linear;
grad_nonlin = 1;
end
% Compute the raw error ratio for the current estimate of the sharp image
error_ratio = imblur ./ max(val_nonlin,eps);
error_ratio_masked_nonlin = (error_ratio - 1).*mask.*grad_nonlin;
if params.prevent_ringing
% Find hard-to-estimate pixels in sharp image (set S in paper)
S_mask = double(imdilate(i_rl >= 0.9, dilate_filter));
% Find the blurry pixels NOT influenced by pixels in S (set V in paper)
V_mask = 1 - dilatefn(S_mask);
% Apply conjugate blur function (ie. multiply by A')
update_ratio_U = conjfn(error_ratio_masked_nonlin.*V_mask) + 1; % update U using only data from V
update_ratio_S = conjfn(error_ratio_masked_nonlin) + 1; % update S using all data
% Blur the mask of hard-to-estimate pixels for recombining without artefacts
weights = imfilter(S_mask, smooth_filter);
% Combine updates for the two sets into a single update
% update_ratio = update_ratio_S.*weights + update_ratio_U.*(1-weights);
update_ratio = update_ratio_U + (update_ratio_S - update_ratio_U).*weights;
else
% Apply conjugate blur function (ie. multiply by A')
update_ratio = conjfn(error_ratio_masked_nonlin) + 1;
end
% Avoid negative updates, which cause trouble
update_ratio = max(update_ratio,0);
if any(isnan(update_ratio(:))), error('NaNs in update ratio'); end
% Apply update ratio
i_rl = update_ratio .* i_rl;
fprintf('%d ',iter);
end
fprintf('\n');
% Remove padding on output image
i_rl = padImage(i_rl, -pad);
end
% =====================================================================================
function params = parseArgs(args,params)
if nargin < 2
params = struct('num_iters',50,'forward_saturation',false,'prevent_ringing',false,'sat_thresh',1,'sat_smooth',50,'mask',1);
end
if ~isempty(args)
switch args{1}
case 'num_iters'
params.num_iters = args{2};
args = args(3:end);
case 'sat_thresh'
params.sat_thresh = args{2};
args = args(3:end);
case 'sat_smooth'
params.sat_smooth = args{2};
args = args(3:end);
case 'forward_saturation'
params.forward_saturation = true;
args = args(2:end);
case 'prevent_ringing'
params.prevent_ringing = true;
args = args(2:end);
case 'init'
params.init = args{2};
args = args(3:end);
case 'mask'
params.mask = args{2};
args = args(3:end);
otherwise
error('Invalid argument');
end
% Recursively parse remaining arguments
params = parseArgs(args,params);
end
end
% ============================================================================
function [val,grad] = saturate(x,t,a)
if a==inf
[val,grad] = sharpsaturate(x, t);
else
% Adapted from: C. Chen and O. L. Mangasarian. ``A Class of Smoothing Functions
% for Nonlinear and Mixed Complementarity Problems''.
% Computational Optimization and Applications, 1996.
one_p_exp = 1 + exp(-a*(t-x));
val = x - 1/a * log(one_p_exp);
grad = 1 ./ one_p_exp;
end
end
% ============================================================================
function [val,grad] = sharpsaturate(x,t)
val = x;
grad = ones(size(x));
mask = x>t;
val(mask) = t;
grad(mask) = 0;
end
|
github
|
yuanxy92/ConvexOptimization-master
|
crossmatrix.m
|
.m
|
ConvexOptimization-master/MATLAB/text_deblurring_code/whyte_code/crossmatrix.m
| 417 |
utf_8
|
cac6f7c9c7414f240720e5a918c7c776
|
% Author: Oliver Whyte <[email protected]>
% Date: November 2011
% Copyright: 2011, Oliver Whyte
% Reference: O. Whyte, J. Sivic and A. Zisserman. "Deblurring Shaken and Partially Saturated Images". In Proc. CPCV Workshop at ICCV, 2011.
% URL: http://www.di.ens.fr/willow/research/saturation/
function vx = crossmatrix(v)
vx = [ 0, -v(3), v(2);...
v(3), 0, -v(1);...
-v(2), v(1), 0];
|
github
|
nqanh/affordance-net-master
|
voc_eval.m
|
.m
|
affordance-net-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
|
nqanh/affordance-net-master
|
classification_demo.m
|
.m
|
affordance-net-master/caffe-affordance-net/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
|
lipan00123/InHclustering-master
|
missclassf.m
|
.m
|
InHclustering-master/motionsegmentation/missclassf.m
| 252 |
utf_8
|
7cb914bb3bf5de5f05e90eb0e3d2887b
|
function [err,assignment]=missclassf(estlabel,label)
c = max(label);
cost = zeros(c,c);
for i = 1:c,
for j = 1:c,
cost(i,j)=sum(estlabel(find(label==i))~=j);
end
end
[assignment,err] = munkres(cost);
end
|
github
|
lipan00123/InHclustering-master
|
munkres.m
|
.m
|
InHclustering-master/motionsegmentation/munkres.m
| 7,171 |
utf_8
|
b44ad4f1a20fc5d03db019c44a65bac3
|
function [assignment,cost] = munkres(costMat)
% MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem.
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices,
% ASSIGN assigned to each row and the minimum COST based on the assignment
% problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%
% Partial assignment: This code can identify a partial assignment is a full
% assignment is not feasible. For a partial assignment, there are some
% zero elements in the returning assignment vector, which indicate
% un-assigned tasks. The cost returned only contains the cost of partially
% assigned tasks.
% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.
% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
disp(assignment); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc % about 2 seconds
%}
% Example 3: rectangular assignment with inf costs
%{
A=rand(10,7);
A(A>0.7)=Inf;
[a,b]=munkres(A);
%}
% Example 4: an example of partial assignment
%{
A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5];
[a,b]=munkres(A)
%}
% a = [1 0 3]
% b = 1.5
% Reference:
% "Munkres' Assignment Algorithm, Modified for Rectangular Matrices",
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
% version 2.3 by Yi Cao at Cranfield University on 11th September 2011
assignment = zeros(1,size(costMat,1));
cost = 0;
validMat = costMat == costMat & costMat < Inf;
bigM = 10^(ceil(log10(sum(costMat(validMat))))+1);
costMat(~validMat) = bigM;
% costMat(costMat~=costMat)=Inf;
% validMat = costMat<Inf;
validCol = any(validMat,1);
validRow = any(validMat,2);
nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
return
end
maxv=10*max(costMat(validMat));
dMat = zeros(n) + maxv;
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);
%*************************************************
% Munkres' Assignment Algorithm starts here
%*************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Subtract the row minimum from each row.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minR = min(dMat,[],2);
minC = min(bsxfun(@minus, dMat, minR));
%**************************************************************************
% STEP 2: Find a zero of dMat. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
zP = dMat == bsxfun(@plus, minC, minR);
starZ = zeros(n,1);
while any(zP(:))
[r,c]=find(zP,1);
starZ(r)=c;
zP(r,:)=false;
zP(:,c)=false;
end
while 1
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
if all(starZ>0)
break
end
coverColumn = false(1,n);
coverColumn(starZ(starZ>0))=true;
coverRow = false(n,1);
primeZ = zeros(n,1);
[rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn)));
while 1
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
cR = find(~coverRow);
cC = find(~coverColumn);
rIdx = cR(rIdx);
cIdx = cC(cIdx);
Step = 6;
while ~isempty(cIdx)
uZr = rIdx(1);
uZc = cIdx(1);
primeZ(uZr) = uZc;
stz = starZ(uZr);
if ~stz
Step = 5;
break;
end
coverRow(uZr) = true;
coverColumn(stz) = false;
z = rIdx==uZr;
rIdx(z) = [];
cIdx(z) = [];
cR = find(~coverRow);
z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz);
rIdx = [rIdx(:);cR(z)];
cIdx = [cIdx(:);stz(ones(sum(z),1))];
end
if Step == 6
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
[minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn));
minC(~coverColumn) = minC(~coverColumn) + minval;
minR(coverRow) = minR(coverRow) - minval;
else
break
end
end
%**************************************************************************
% STEP 5:
% Construct a series of alternating primed and starred zeros as
% follows:
% Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
while rowZ1>0
starZ(rowZ1)=0;
uZc = primeZ(rowZ1);
uZr = rowZ1;
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
end
end
% Cost of assignment
rowIdx = find(validRow);
colIdx = find(validCol);
starZ = starZ(1:nRows);
vIdx = starZ <= nCols;
assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx));
pass = assignment(assignment>0);
pass(~diag(validMat(assignment>0,pass))) = 0;
assignment(assignment>0) = pass;
cost = trace(costMat(assignment>0,assignment(assignment>0)));
function [minval,rIdx,cIdx]=outerplus(M,x,y)
ny=size(M,2);
minval=inf;
for c=1:ny
M(:,c)=M(:,c)-(x+y(c));
minval = min(minval,min(M(:,c)));
end
[rIdx,cIdx]=find(M==minval);
|
github
|
lijunzh/fd_elastic-master
|
guiSurvey.m
|
.m
|
fd_elastic-master/gui/guiSurvey.m
| 64,340 |
utf_8
|
eef780e9025802e1419a3e9d0b8ca138
|
function varargout = guiSurvey(varargin)
% GUISURVEY MATLAB code for guiSurvey.fig
% GUISURVEY, by itself, creates a new GUISURVEY or raises the existing
% singleton*.
%
% H = GUISURVEY returns the handle to a new GUISURVEY or the handle to
% the existing singleton*.
%
% GUISURVEY('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUISURVEY.M with the given input arguments.
%
% GUISURVEY('Property','Value',...) creates a new GUISURVEY or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before guiSurvey_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to guiSurvey_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help guiSurvey
% Last Modified by GUIDE v2.5 27-Apr-2015 22:52:24
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @guiSurvey_OpeningFcn, ...
'gui_OutputFcn', @guiSurvey_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
% only add the directory into path when it is not in the path to load GUI
% faster
pathCell = regexp(path, pathsep, 'split');
if ~any(strcmpi('../src', pathCell))
addpath(genpath('../src'));
end
% --- Executes just before guiSurvey is made visible.
function guiSurvey_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 guiSurvey (see VARARGIN)
% Choose default command line output for guiSurvey
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes guiSurvey wait for user response (see UIRESUME)
% uiwait(handles.figureMain);
% --- Outputs from this function are returned to the command line.
function varargout = guiSurvey_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;
% --------------------------------------------------
% begin of self-defined functions
% set up objects after loading velocity model for either P-wave or S-wave
function loadVModel(v, handles)
Ndims = ndims(v);
vmin = min(v(:));
vmax = max(v(:));
%% prepare objects
% enable objects
set(handles.edit_dx, 'Enable', 'on');
set(handles.edit_dz, 'Enable', 'on');
set(handles.edit_dt, 'Enable', 'on');
set(handles.edit_nt, 'Enable', 'on');
set(handles.edit_boundary, 'Enable', 'on');
set(handles.pmenu_approxOrder, 'Enable', 'on');
set(handles.edit_centerFreq, 'Enable', 'on');
set(handles.pmenu_sweepAll, 'Enable', 'on');
set(handles.edit_sx, 'Enable', 'on');
set(handles.edit_sz, 'Enable', 'on');
set(handles.pmenu_receiveAll, 'Enable', 'on');
set(handles.btn_shot, 'Enable', 'on');
% disable objects
set(handles.edit_dy, 'Enable', 'off');
set(handles.edit_sy, 'Enable', 'off');
set(handles.edit_rx, 'Enable', 'off');
set(handles.edit_ry, 'Enable', 'off');
set(handles.edit_rz, 'Enable', 'off');
%% set finite difference setting values
dx = 10;
dz = 10;
dt = 0.5*(min([dx, dz])/vmax/sqrt(2)); % times 0.5 to reduce the possibility of instability
[nz, nx, ~] = size(v);
nt = round((sqrt((dx*nx)^2 + (dz*nz)^2)*2/vmin/dt + 1));
x = (1:nx) * dx;
z = (1:nz) * dz;
nBoundary = 20;
nDiffOrder = 3;
f = 20;
sx = round(nx / 2);
sz = 1;
str_rx = sprintf('1:%d', nx);
str_rz = sprintf('%d', 1);
%% set default values in edit texts
set(handles.edit_dx, 'String', num2str(dx));
set(handles.edit_dz, 'String', num2str(dz));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nx, 'String', num2str(nx));
set(handles.edit_nz, 'String', num2str(nz));
set(handles.edit_nt, 'String', num2str(nt));
set(handles.edit_boundary, 'String', num2str(nBoundary));
set(handles.pmenu_approxOrder, 'Value', nDiffOrder);
set(handles.edit_centerFreq, 'String', num2str(f));
set(handles.pmenu_sweepAll, 'Value', 2); % default is no
set(handles.edit_sx, 'String', num2str(sx));
set(handles.edit_sy, 'String', '');
set(handles.edit_sz, 'String', num2str(sz));
set(handles.pmenu_receiveAll, 'Value', 1); % default is yes
set(handles.edit_rx, 'String', str_rx);
set(handles.edit_ry, 'String', '');
set(handles.edit_rz, 'String', str_rz);
% 3D case
if (Ndims > 2)
% enable edit texts for y-axis
set(handles.edit_dy, 'Enable', 'on');
set(handles.edit_sy, 'Enable', 'on');
% set finite difference setting values
dy = 10;
dt = 0.5*(min([dx, dy, dz])/vmax/sqrt(3));
[~, ~, ny] = size(v);
nt = round((sqrt((dx*nx)^2 + (dy*ny)^2 + (dz*nz)^2)*2/vmin/dt + 1));
y = (1:ny) * dy;
sy = round(ny / 2);
str_ry = sprintf('1:%d', ny);
% set values in edit texts for y-axis
set(handles.edit_dy, 'String', num2str(dy));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_ny, 'String', num2str(ny));
set(handles.edit_nt, 'String', num2str(nt));
set(handles.edit_sy, 'String', num2str(sy));
set(handles.edit_ry, 'String', str_ry);
end
%% plot velocity model
if (Ndims <= 2) % 2D case
imagesc(x, z, v, 'Parent', handles.axes_velocityModel);
xlabel(handles.axes_velocityModel, 'Distance (m)'); ylabel(handles.axes_velocityModel, 'Depth (m)');
title(handles.axes_velocityModel, 'Velocity Model');
colormap(handles.axes_velocityModel, seismic);
else % 3D case
slice(handles.axes_velocityModel, x, y, z, permute(v, [3, 2, 1]), ...
round(linspace(x(2), x(end-1), 5)), ...
round(linspace(y(2), y(end-1), 5)), ...
round(linspace(z(2), z(end-1), 10)));
xlabel(handles.axes_velocityModel, 'X - Easting (m)');
ylabel(handles.axes_velocityModel, 'Y - Northing (m)');
zlabel(handles.axes_velocityModel, 'Z - Depth (m)');
title(handles.axes_velocityModel, 'Velocity Model');
set(handles.axes_velocityModel, 'ZDir', 'reverse');
shading(handles.axes_velocityModel, 'interp');
colormap(handles.axes_velocityModel, seismic);
end
% clear other axes & set them invisible
cla(handles.axes_sourceTime, 'reset');
cla(handles.axes_out1, 'reset');
cla(handles.axes_out2, 'reset');
cla(handles.axes_out3, 'reset');
cla(handles.axes_out4, 'reset');
cla(handles.axes_out5, 'reset');
cla(handles.axes_out6, 'reset');
set(handles.axes_sourceTime, 'Visible', 'off');
set(handles.axes_out1, 'Visible', 'off');
set(handles.axes_out2, 'Visible', 'off');
set(handles.axes_out3, 'Visible', 'off');
set(handles.axes_out4, 'Visible', 'off');
set(handles.axes_out5, 'Visible', 'off');
set(handles.axes_out6, 'Visible', 'off');
% end of self-defined functions
% --------------------------------------------------
% --------------------------------------------------------------------
function menu_file_Callback(hObject, eventdata, handles)
% hObject handle to menu_file (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menu_loadPWaveVModel_Callback(hObject, eventdata, handles)
% hObject handle to menu_loadPWaveVModel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% load P-wave velocity model
[file, path] = uigetfile('*.mat', 'Select a velocity model for P-wave');
if (~any([file, path])) % user pressed cancel button
return;
end
load(fullfile(path, file));
if (~exist('velocityModel', 'var'))
errordlg('This is not a valid velocity model!', 'File Error');
return;
end
vp = velocityModel;
% dimension check
data = guidata(hObject);
if (isfield(data, 'vs'))
if (ndims(vp) ~= ndims(data.vs))
errordlg('Dimension of P-wave and S-wave velocity models are not the same!', 'Model Error');
return;
end
if (any(size(vp) ~= size(data.vs)))
errordlg('Dimension of P-wave and S-wave velocity models are not the same!', 'Model Error');
return;
end
end
%% load velocity model
loadVModel(vp, handles);
loadPFlag = true;
%% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = sprintf('Loaded P-wave Velocity Model: %s', fullfile(path, file));
set(handles.edit_status, 'String', str_status);
%% share variables among callback functions
data = guidata(hObject);
data.loadPFlag = loadPFlag;
data.vp = vp;
guidata(hObject, data); % hObject can be any object contained in the figure, including push button, edit text, popup menu, etc.
% --------------------------------------------------------------------
function menu_loadSWaveVModel_Callback(hObject, eventdata, handles)
% hObject handle to menu_loadSWaveVModel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% load S-wave velocity model
[file, path] = uigetfile('*.mat', 'Select a velocity model for S-wave');
if (~any([file, path])) % user pressed cancel button
return;
end
load(fullfile(path, file));
if (~exist('velocityModel', 'var'))
errordlg('This is not a valid velocity model!', 'File Error');
return;
end
vs = velocityModel;
data = guidata(hObject);
if (isfield(data, 'vp'))
if (ndims(vs) ~= ndims(data.vp))
errordlg('Dimension of P-wave and S-wave velocity models are not the same!', 'Model Error');
return;
end
if (any(size(vs) ~= size(data.vp)))
errordlg('Dimension of P-wave and S-wave velocity models are not the same!', 'Model Error');
return;
end
end
%% load velocity model
loadVModel(vs, handles);
loadSFlag = true;
%% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = sprintf('Loaded S-wave Velocity Model: %s', fullfile(path, file));
set(handles.edit_status, 'String', str_status);
%% share variables among callback functions
data = guidata(hObject);
data.loadSFlag = loadSFlag;
data.vs = vs;
guidata(hObject, data);
% --------------------------------------------------------------------
function menu_clearVModel_Callback(hObject, eventdata, handles)
% hObject handle to menu_clearVModel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% clear object contents
set(handles.edit_dx, 'String', '');
set(handles.edit_dy, 'String', '');
set(handles.edit_dz, 'String', '');
set(handles.edit_dt, 'String', '');
set(handles.edit_nx, 'String', '');
set(handles.edit_ny, 'String', '');
set(handles.edit_nz, 'String', '');
set(handles.edit_nt, 'String', '');
set(handles.edit_boundary, 'String', '');
set(handles.pmenu_approxOrder, 'Value', 1);
set(handles.edit_centerFreq, 'String', '');
set(handles.pmenu_sweepAll, 'Value', 2); % default is no
set(handles.edit_sx, 'String', '');
set(handles.edit_sy, 'String', '');
set(handles.edit_sz, 'String', '');
set(handles.pmenu_receiveAll, 'Value', 1); % default is yes
set(handles.edit_rx, 'String', '');
set(handles.edit_ry, 'String', '');
set(handles.edit_rz, 'String', '');
set(handles.edit_status, 'String', '');
%% disable objects
set(handles.edit_dx, 'Enable', 'off');
set(handles.edit_dy, 'Enable', 'off');
set(handles.edit_dz, 'Enable', 'off');
set(handles.edit_dt, 'Enable', 'off');
set(handles.edit_nx, 'Enable', 'off');
set(handles.edit_ny, 'Enable', 'off');
set(handles.edit_nz, 'Enable', 'off');
set(handles.edit_nt, 'Enable', 'off');
set(handles.edit_boundary, 'Enable', 'off');
set(handles.pmenu_approxOrder, 'Enable', 'off');
set(handles.edit_centerFreq, 'Enable', 'off');
set(handles.pmenu_sweepAll, 'Enable', 'off');
set(handles.edit_sx, 'Enable', 'off');
set(handles.edit_sy, 'Enable', 'off');
set(handles.edit_sz, 'Enable', 'off');
set(handles.pmenu_receiveAll, 'Enable', 'off');
set(handles.edit_rx, 'Enable', 'off');
set(handles.edit_ry, 'Enable', 'off');
set(handles.edit_rz, 'Enable', 'off');
% set(handles.edit_status, 'Enable', 'off');
set(handles.btn_shot, 'Enable', 'off');
set(handles.btn_stop, 'Enable', 'off');
set(handles.btn_saveData, 'Enable', 'off');
%% clear other axes & set them invisible
cla(handles.axes_velocityModel, 'reset');
cla(handles.axes_sourceTime, 'reset');
cla(handles.axes_out1, 'reset');
cla(handles.axes_out2, 'reset');
cla(handles.axes_out3, 'reset');
cla(handles.axes_out4, 'reset');
cla(handles.axes_out5, 'reset');
cla(handles.axes_out6, 'reset');
set(handles.axes_velocityModel, 'Visible', 'off');
set(handles.axes_sourceTime, 'Visible', 'off');
set(handles.axes_out1, 'Visible', 'off');
set(handles.axes_out2, 'Visible', 'off');
set(handles.axes_out3, 'Visible', 'off');
set(handles.axes_out4, 'Visible', 'off');
set(handles.axes_out5, 'Visible', 'off');
set(handles.axes_out6, 'Visible', 'off');
%% share variables among callback functions
data = guidata(hObject);
if (isfield(data, 'vp'))
data = rmfield(data, 'vp');
end
if (isfield(data, 'vs'))
data = rmfield(data, 'vs');
end
if (isfield(data, 'loadPFlag'))
data = rmfield(data, 'loadPFlag');
end
if (isfield(data, 'vp'))
data = rmfield(data, 'vp');
end
if (isfield(data, 'loadSFlag'))
data = rmfield(data, 'loadSFlag');
end
if (isfield(data, 'vs'))
data = rmfield(data, 'vs');
end
if (isfield(data, 'stopFlag'))
data = rmfield(data, 'stopFlag');
end
if (isfield(data, 'dataP'))
data = rmfield(data, 'dataP');
end
if (isfield(data, 'dataVxp'))
data = rmfield(data, 'dataVxp');
end
if (isfield(data, 'dataVyp'))
data = rmfield(data, 'dataVyp');
end
if (isfield(data, 'dataVzp'))
data = rmfield(data, 'dataVzp');
end
if (isfield(data, 'dataVxs'))
data = rmfield(data, 'dataVxs');
end
if (isfield(data, 'dataVys'))
data = rmfield(data, 'dataVys');
end
if (isfield(data, 'dataVzs'))
data = rmfield(data, 'dataVzs');
end
guidata(hObject, data); % hObject can be any object contained in the figure, including push button, edit text, popup menu, etc.
% --- Executes on button press in btn_shot.
function btn_shot_Callback(hObject, eventdata, handles)
% hObject handle to btn_shot (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% enable / disable objects
set(handles.btn_shot, 'Enable', 'off');
set(handles.btn_stop, 'Enable', 'on');
set(handles.btn_saveData, 'Enable', 'off');
%% share variables among callback functions
data = guidata(hObject);
data.stopFlag = false;
if (isfield(data, 'loadPFlag'))
data.loadPFlag = false;
end
if (isfield(data, 'loadSFlag'))
data.loadSFlag = false;
end
guidata(hObject, data);
%% load parameter
data = guidata(hObject);
if (isfield(data, 'vp'))
% P-wave velocity model has been loaded
vp = data.vp;
if (isfield(data, 'vs'))
% both P-wave and S-wave velocity model have been loaded
vs = data.vs;
end
else
% only S-wave velocity model has been loaded, treat as only P-wave
% velocity model has been loaded
warndlg('Only S-wave velocity model has been loaded, treat as only P-wave velocity model has been loaded!', 'Warning');
vp = data.vs;
end
Ndims = ndims(vp);
[nz, nx, ~] = size(vp);
dx = str2double(get(handles.edit_dx, 'String'));
dz = str2double(get(handles.edit_dz, 'String'));
dt = str2double(get(handles.edit_dt, 'String'));
nt = str2double(get(handles.edit_nt, 'String'));
x = (1:nx) * dx;
z = (1:nz) * dz;
t = (0:nt-1) * dt;
nBoundary = str2double(get(handles.edit_boundary, 'String'));
nDiffOrder = get(handles.pmenu_approxOrder, 'Value');
f = str2double(get(handles.edit_centerFreq, 'String'));
sx = eval(sprintf('[%s]', get(handles.edit_sx, 'String')));
sz = eval(sprintf('[%s]', get(handles.edit_sz, 'String')));
[szMesh, sxMesh] = meshgrid(sz, sx);
sMesh = [szMesh(:), sxMesh(:)];
nShots = size(sMesh, 1);
rx = eval(sprintf('[%s]', get(handles.edit_rx, 'String')));
rz = eval(sprintf('[%s]', get(handles.edit_rz, 'String')));
% 3D case
if (Ndims > 2)
[~, ~, ny] = size(vp);
dy = str2double(get(handles.edit_dy, 'String'));
y = (1:ny) * dy;
sy = eval(sprintf('[%s]', get(handles.edit_sy, 'String')));
[szMesh, sxMesh, syMesh] = meshgrid(sz, sx, sy);
sMesh = [szMesh(:), sxMesh(:), syMesh(:)];
nShots = size(sMesh, 1);
ry = eval(sprintf('[%s]', get(handles.edit_ry, 'String')));
end
%% check the condition of stability
if (Ndims <= 2)
if (dt > min([dx, dz])/(norm(dCoef(nDiffOrder, 's'), 1) * sqrt(2) * max(vp(:))))
errordlg('The temporal discretization does not satisfy the Courant-Friedrichs-Lewy sampling criterion to ensure the stability of the finite difference method!');
end
else
if (dt > min([dx, dy, dz])/(norm(dCoef(nDiffOrder, 's'), 1) * sqrt(3) * max(vp(:))))
errordlg('The temporal discretization does not satisfy the Courant-Friedrichs-Lewy sampling criterion to ensure the stability of the finite difference method!');
end
end
%% add region around model for applying absorbing boundary conditions
VP = extBoundary(vp, nBoundary, Ndims);
if (exist('vs', 'var'))
if (Ndims <= 2)
VS = extBoundary(vs, nBoundary, 2);
else
VS = extBoundary(vs, nBoundary, 3);
end
end
%% shot through all source positions
for ixs = 1:nShots
%% locating current source
cur_sz = sMesh(ixs, 1);
cur_sx = sMesh(ixs, 2);
%% generate shot source field and shot record using FDTD
sourceTime = zeros([size(VP), nt]);
wave1dTime = ricker(f, nt, dt);
if (Ndims <= 2) % 2D case
% plot velocity model and shot position
imagesc(x, z, vp, 'Parent', handles.axes_velocityModel);
xlabel(handles.axes_velocityModel, 'Distance (m)'); ylabel(handles.axes_velocityModel, 'Depth (m)');
title(handles.axes_velocityModel, 'Velocity Model');
colormap(handles.axes_velocityModel, seismic);
hold(handles.axes_velocityModel, 'on');
plot(handles.axes_velocityModel, cur_sx * dx, cur_sz * dz, 'w*');
hold(handles.axes_velocityModel, 'off');
% shot
sourceTime(cur_sz, cur_sx+nBoundary, :) = reshape(wave1dTime, 1, 1, nt);
if (exist('vs', 'var'))
% elastic wave shot
[snapshotVzp, snapshotVxp, snapshotVzs, snapshotVxs] = fwdTimeSpmlFor2dEw(VP, VS, sourceTime, nDiffOrder, nBoundary, dz, dx, dt);
% share variables among callback functions
data = guidata(hObject);
if (isfield(data, 'dataVyp'))
data = rmfield(data, 'dataVyp');
end
if (isfield(data, 'dataVys'))
data = rmfield(data, 'dataVys');
end
data.dataVzp = squeeze(snapshotVzp(1, rx+nBoundary, :)).';
data.dataVxp = squeeze(snapshotVxp(1, rx+nBoundary, :)).';
data.dataVzs = squeeze(snapshotVzs(1, rx+nBoundary, :)).';
data.dataVxs = squeeze(snapshotVxs(1, rx+nBoundary, :)).';
guidata(hObject, data);
else
% acoustic wave shot
[dataP, snapshotTrue] = fwdTimeCpmlFor2dAw(VP, sourceTime, nDiffOrder, nBoundary, dz, dx, dt);
% share variables among callback functions
data = guidata(hObject);
data.dataP = dataP(rx+nBoundary, :).';
guidata(hObject, data);
end
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = sprintf('Shot at x = %dm, z = %dm', cur_sx * dx, cur_sz * dz);
set(handles.edit_status, 'String', str_status);
else % 3D case
slice(handles.axes_velocityModel, x, y, z, permute(vp, [3, 2, 1]), ...
round(linspace(x(2), x(end-1), 5)), ...
round(linspace(y(2), y(end-1), 5)), ...
round(linspace(z(2), z(end-1), 10)));
xlabel(handles.axes_velocityModel, 'X - Easting (m)');
ylabel(handles.axes_velocityModel, 'Y - Northing (m)');
zlabel(handles.axes_velocityModel, 'Z - Depth (m)');
title(handles.axes_velocityModel, 'Velocity Model');
set(handles.axes_velocityModel, 'ZDir', 'reverse');
shading(handles.axes_velocityModel, 'interp');
colormap(handles.axes_velocityModel, seismic);
cur_sy = sMesh(ixs, 3);
hold(handles.axes_velocityModel, 'on');
plot3(handles.axes_velocityModel, cur_sx * dx, cur_sy * dy, cur_sz * dz, 'w*');
hold(handles.axes_velocityModel, 'off');
% shot
sourceTime(cur_sz, cur_sx+nBoundary, cur_sy+nBoundary, :) = reshape(wave1dTime, 1, 1, 1, nt);
if (exist('vs', 'var'))
% elastic wave shot
[snapshotVzp, snapshotVxp, snapshotVyp, snapshotVzs, snapshotVxs, snapshotVys] = fwdTimeSpmlFor3dEw(VP, VS, sourceTime, sourceTime, sourceTime, nDiffOrder, nBoundary, dz, dx, dy, dt);
% share variables among callback functions
data = guidata(hObject);
data.dataVzp = permute(squeeze(snapshotVzp(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
data.dataVxp = permute(squeeze(snapshotVxp(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
data.dataVyp = permute(squeeze(snapshotVyp(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
data.dataVzs = permute(squeeze(snapshotVzs(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
data.dataVxs = permute(squeeze(snapshotVxs(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
data.dataVys = permute(squeeze(snapshotVys(1, rx+nBoundary, ry+nBoundary, :)), [3, 1, 2]);
guidata(hObject, data);
else
% acoustic wave shot
[dataP, snapshotTrue] = fwdTimeCpmlFor3dAw(VP, sourceTime, nDiffOrder, nBoundary, dz, dx, dy, dt);
% share variables among callback functions
data = guidata(hObject);
data.dataP = permute(dataP(rx+nBoundary, ry+nBoundary, :), [3, 1, 2]);
guidata(hObject, data);
end
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = sprintf('Shot at x = %dm, y = %dm, z = %dm', cur_sx * dx, cur_sy * dy, cur_sz * dz);
set(handles.edit_status, 'String', str_status);
slice_x = median(x);
slice_y = median(y);
slice_z = median(z);
end
%% plot figures into axes
for it = 1:nt
% stop plotting when hObject becomes invalid (due to its deletion)
if (~ishandle(hObject))
return;
end
data = guidata(hObject);
% stop plotting when stop button has been pushed
if (data.stopFlag)
return;
end
% stop plotting when another new velocity model has been loaded
if ( (~isfield(data, 'loadSFlag') && data.loadPFlag) ...
|| (~isfield(data, 'loadPFlag') && data.loadSFlag) ...
|| (isfield(data, 'loadPFlag') && isfield(data, 'loadSFlag') && (data.loadPFlag || data.loadSFlag)) )
return;
end
% plot source function in time domain
plot(handles.axes_sourceTime, t, wave1dTime); hold(handles.axes_sourceTime, 'on');
plot(handles.axes_sourceTime, t(it), wave1dTime(it), 'r*'); hold(handles.axes_sourceTime, 'off');
xlim(handles.axes_sourceTime, [t(1), t(end)]);
xlabel(handles.axes_sourceTime, 'Time (s)'); ylabel(handles.axes_sourceTime, 'Amplitude');
colormap(handles.axes_sourceTime, seismic);
if (Ndims <= 2) % 2D case
% source function title
title(handles.axes_sourceTime, sprintf('Shot at x = %dm', cur_sx * dx));
if (exist('vs', 'var'))
% display elastic wavefields
imagesc(x, z, snapshotVxp(1:end-nBoundary, nBoundary+1:end-nBoundary, it), 'Parent', handles.axes_out1);
xlabel(handles.axes_out1, 'Distance (m)'); ylabel(handles.axes_out1, 'Depth (m)');
title(handles.axes_out1, sprintf('P-wave (x-axis component) t = %.3fs', t(it)));
caxis(handles.axes_out1, [-2e-5, 1e-4]);
imagesc(x, z, snapshotVzp(1:end-nBoundary, nBoundary+1:end-nBoundary, it), 'Parent', handles.axes_out2);
xlabel(handles.axes_out2, 'Distance (m)'); ylabel(handles.axes_out2, 'Depth (m)');
title(handles.axes_out2, sprintf('P-wave (z-axis component) t = %.3fs', t(it)));
caxis(handles.axes_out2, [-2e-5, 1e-4]);
imagesc(x, z, snapshotVxs(1:end-nBoundary, nBoundary+1:end-nBoundary, it), 'Parent', handles.axes_out4);
xlabel(handles.axes_out4, 'Distance (m)'); ylabel(handles.axes_out4, 'Depth (m)');
title(handles.axes_out4, sprintf('S-wave (x-axis component) t = %.3fs', t(it)));
caxis(handles.axes_out4, [-2e-5, 1e-4]);
imagesc(x, z, snapshotVzs(1:end-nBoundary, nBoundary+1:end-nBoundary, it), 'Parent', handles.axes_out5);
xlabel(handles.axes_out5, 'Distance (m)'); ylabel(handles.axes_out5, 'Depth (m)');
title(handles.axes_out5, sprintf('S-wave (z-axis component) t = %.3fs', t(it)));
caxis(handles.axes_out5, [-2e-5, 1e-4]);
else
% display acoustic wavefields
% plot received data traces
dataDisplay = zeros(nt, nx);
dataDisplay(1:it, rx) = dataP(rx+nBoundary, 1:it).';
imagesc(x, t, dataDisplay, 'Parent', handles.axes_out1);
xlabel(handles.axes_out1, 'Distance (m)'); ylabel(handles.axes_out1, 'Time (s)');
title(handles.axes_out1, 'Shot Record');
caxis(handles.axes_out1, [-0.1 0.1]);
% plot wave propagation snapshots
imagesc(x, z, snapshotTrue(1:end-nBoundary, nBoundary+1:end-nBoundary, it), 'Parent', handles.axes_out2);
xlabel(handles.axes_out2, 'Distance (m)'); ylabel(handles.axes_out2, 'Depth (m)');
title(handles.axes_out2, sprintf('Wave Propagation t = %.3fs', t(it)));
caxis(handles.axes_out2, [-0.15, 1]);
end
else % 3D case
% source function title
title(handles.axes_sourceTime, sprintf('Shot at x = %dm, y = %dm', cur_sx * dx, cur_sy * dy));
if (exist('vs', 'var'))
% display elastic wavefields
slice(handles.axes_out1, x, y, z, permute(snapshotVzp(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out1, 'X - Easting (m)');
ylabel(handles.axes_out1, 'Y - Northing (m)');
zlabel(handles.axes_out1, 'Z - Depth (m)');
title(handles.axes_out1, sprintf('P-wave (z-axis component), t = %.3fs', t(it)));
set(handles.axes_out1, 'ZDir', 'reverse');
shading(handles.axes_out1, 'interp');
caxis(handles.axes_out1, [-2e-5, 1e-4]);
slice(handles.axes_out2, x, y, z, permute(snapshotVxp(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out2, 'X - Easting (m)');
ylabel(handles.axes_out2, 'Y - Northing (m)');
zlabel(handles.axes_out2, 'Z - Depth (m)');
title(handles.axes_out2, sprintf('P-wave (x-axis component), t = %.3fs', t(it)));
set(handles.axes_out2, 'ZDir', 'reverse');
shading(handles.axes_out2, 'interp');
caxis(handles.axes_out2, [-2e-5, 1e-4]);
slice(handles.axes_out3, x, y, z, permute(snapshotVyp(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out3, 'X - Easting (m)');
ylabel(handles.axes_out3, 'Y - Northing (m)');
zlabel(handles.axes_out3, 'Z - Depth (m)');
title(handles.axes_out3, sprintf('P-wave (y-axis component), t = %.3fs', t(it)));
set(handles.axes_out3, 'ZDir', 'reverse');
shading(handles.axes_out3, 'interp');
caxis(handles.axes_out3, [-2e-5, 1e-4]);
slice(handles.axes_out4, x, y, z, permute(snapshotVzs(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out4, 'X - Easting (m)');
ylabel(handles.axes_out4, 'Y - Northing (m)');
zlabel(handles.axes_out4, 'Z - Depth (m)');
title(handles.axes_out4, sprintf('S-wave (z-axis component), t = %.3fs', t(it)));
set(handles.axes_out4, 'ZDir', 'reverse');
shading(handles.axes_out4, 'interp');
caxis(handles.axes_out4, [-2e-5, 1e-4]);
slice(handles.axes_out5, x, y, z, permute(snapshotVxs(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out5, 'X - Easting (m)');
ylabel(handles.axes_out5, 'Y - Northing (m)');
zlabel(handles.axes_out5, 'Z - Depth (m)');
title(handles.axes_out5, sprintf('S-wave (x-axis component), t = %.3fs', t(it)));
set(handles.axes_out5, 'ZDir', 'reverse');
shading(handles.axes_out5, 'interp');
caxis(handles.axes_out5, [-2e-5, 1e-4]);
slice(handles.axes_out6, x, y, z, permute(snapshotVys(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out6, 'X - Easting (m)');
ylabel(handles.axes_out6, 'Y - Northing (m)');
zlabel(handles.axes_out6, 'Z - Depth (m)');
title(handles.axes_out6, sprintf('S-wave (y-axis component), t = %.3fs', t(it)));
set(handles.axes_out6, 'ZDir', 'reverse');
shading(handles.axes_out6, 'interp');
caxis(handles.axes_out6, [-2e-5, 1e-4]);
else
% display acoustic wavefields
% plot received data traces
dataDisplay = zeros(nx, ny, nt);
dataDisplay(rx, ry, 1:it) = dataP(rx+nBoundary, ry+nBoundary, 1:it);
slice(handles.axes_out1, x, y, t, permute(dataDisplay, [2, 1, 3]), ...
round(linspace(x(2), x(end-1), 5)), ...
round(linspace(y(2), y(end-1), 5)), ...
t);
xlabel(handles.axes_out1, 'X - Easting (m)');
ylabel(handles.axes_out1, 'Y - Northing (m)');
zlabel(handles.axes_out1, 'Time (s)');
title(handles.axes_out1, 'Shot Record');
set(handles.axes_out1, 'ZDir', 'reverse');
shading(handles.axes_out1, 'interp');
caxis(handles.axes_out1, [-0.1 0.1]);
% plot wave propagation snapshots
slice(handles.axes_out2, x, y, z, permute(snapshotTrue(1:end-nBoundary, nBoundary+1:end-nBoundary, nBoundary+1:end-nBoundary, it), [3, 2, 1]), ...
slice_x, slice_y, slice_z);
xlabel(handles.axes_out2, 'X - Easting (m)');
ylabel(handles.axes_out2, 'Y - Northing (m)');
zlabel(handles.axes_out2, 'Z - Depth (m)');
title(handles.axes_out2, sprintf('Wave Propagation t = %.3fs', t(it)));
set(handles.axes_out2, 'ZDir', 'reverse');
shading(handles.axes_out2, 'interp');
caxis(handles.axes_out2, [-0.15, 1]);
end
end
drawnow;
end
end
%% enable / disable objects
set(handles.btn_shot, 'Enable', 'on');
set(handles.btn_stop, 'Enable', 'off');
set(handles.btn_saveData, 'Enable', 'on'); % data has already been ready after plotting
% --- Executes on button press in btn_stop.
function btn_stop_Callback(hObject, eventdata, handles)
% hObject handle to btn_stop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%% enable / disable objects
set(handles.btn_shot, 'Enable', 'on');
set(handles.btn_stop, 'Enable', 'off');
set(handles.btn_saveData, 'Enable', 'on'); % data has already been ready when the stop button can be pushed
%% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = 'Stopped';
set(handles.edit_status, 'String', str_status);
%% share variables among callback functions
data = guidata(hObject);
data.stopFlag = true;
guidata(hObject, data);
% --- Executes on button press in btn_savedata.
function btn_saveData_Callback(hObject, eventdata, handles)
% hObject handle to btn_savedata (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data = guidata(hObject);
Ndims = ndims(data.vp);
if (Ndims <= 2) % 2D case
if (isfield(data, 'vs')) % elastic wave
% save X-axis particle velocity data
[file, path] = uiputfile('*.mat', 'Save X-axis 2D particle velocity data as');
dataVx = data.dataVxp + data.dataVxs;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataVx', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['X-axis 2D particle velocity data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
% save Z-axis particle velocity data
[file, path] = uiputfile('*.mat', 'Save Z-axis 2D particle velocity data as');
dataVz = data.dataVzp + data.dataVzs;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataVz', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['Z-axis 2D particle velocity data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
else % acoustic wave
% save acoustic pressure data
[file, path] = uiputfile('*.mat', 'Save 2D acoustic pressure data as');
dataP = data.dataP;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataP', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['2D Acoustic pressure data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
end
else % 3D case
if (isfield(data, 'vs')) % elastic wave
% save X-axis particle velocity data
[file, path] = uiputfile('*.mat', 'Save X-axis 3D particle velocity data as');
dataVx = data.dataVxp + data.dataVxs;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataVx', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['X-axis 3D particle velocity data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
% save Y-axis particle velocity data
[file, path] = uiputfile('*.mat', 'Save Y-axis 3D particle velocity data as');
dataVy = data.dataVyp + data.dataVys;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataVy', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['Y-axis 3D particle velocity data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
% save Z-axis particle velocity data
[file, path] = uiputfile('*.mat', 'Save Z-axis 3D particle velocity data as');
dataVz = data.dataVzp + data.dataVzs;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataVz', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['Z-axis 3D particle velocity data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
else % acoustic wave
% save acoustic pressure data
[file, path] = uiputfile('*.mat', 'Save 3D acoustic pressure data as');
dataP = data.dataP;
if (~(isequal(file, 0) || isequal(path, 0))) % user does not press the cancel button
save(fullfile(path, file), 'dataP', '-v7.3');
% update status
str_status = get(handles.edit_status, 'String');
str_status{end+1} = ['3D Acoustic pressure data has been saved in ', fullfile(path, file)];
set(handles.edit_status, 'String', str_status);
end
end
end
function edit_dx_Callback(hObject, eventdata, handles)
% hObject handle to edit_dx (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 edit_dx as text
% str2double(get(hObject,'String')) returns contents of edit_dx as a double
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
Ndims = ndims(vp);
vpmin = min(vp(:));
vpmax = max(vp(:));
dx = str2double(get(handles.edit_dx, 'String'));
dz = str2double(get(handles.edit_dz, 'String'));
dt = 0.5*(min([dx, dz])/vpmax/sqrt(2));
[nz, nx, ~] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nt, 'String', num2str(nt));
% 3D case
if (Ndims > 2)
dy = str2double(get(handles.edit_dy, 'String'));
dt = 0.5*(min([dx, dy, dz])/vpmax/sqrt(3));
[~, ~, ny] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dy*ny)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nt, 'String', num2str(nt));
end
% --- Executes during object creation, after setting all properties.
function edit_dx_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_dx (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 edit_dy_Callback(hObject, eventdata, handles)
% hObject handle to edit_dy (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 edit_dy as text
% str2double(get(hObject,'String')) returns contents of edit_dy as a double
% only happen in 3D case
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
vpmin = min(vp(:));
vpmax = max(vp(:));
dx = str2double(get(handles.edit_dx, 'String'));
dy = str2double(get(handles.edit_dy, 'String'));
dz = str2double(get(handles.edit_dz, 'String'));
dt = 0.5*(min([dx, dy, dz])/vpmax/sqrt(3));
[nz, nx, ny] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dy*ny)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nt, 'String', num2str(nt));
% --- Executes during object creation, after setting all properties.
function edit_dy_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_dy (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 edit_dz_Callback(hObject, eventdata, handles)
% hObject handle to edit_dz (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 edit_dz as text
% str2double(get(hObject,'String')) returns contents of edit_dz as a double
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
Ndims = ndims(vp);
vpmin = min(vp(:));
vpmax = max(vp(:));
dx = str2double(get(handles.edit_dx, 'String'));
dz = str2double(get(handles.edit_dz, 'String'));
dt = 0.5*(min([dx, dz])/vpmax/sqrt(2));
[nz, nx, ~] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nt, 'String', num2str(nt));
% 3D case
if (Ndims > 2)
dy = str2double(get(handles.edit_dy, 'String'));
dt = 0.5*(min([dx, dy, dz])/vpmax/sqrt(3));
[~, ~, ny] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dy*ny)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_dt, 'String', num2str(dt));
set(handles.edit_nt, 'String', num2str(nt));
end
% --- Executes during object creation, after setting all properties.
function edit_dz_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_dz (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 edit_dt_Callback(hObject, eventdata, handles)
% hObject handle to edit_dt (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 edit_dt as text
% str2double(get(hObject,'String')) returns contents of edit_dt as a double
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
Ndims = ndims(vp);
vpmin = min(vp(:));
vpmax = max(vp(:));
dx = str2double(get(handles.edit_dx, 'String'));
dz = str2double(get(handles.edit_dz, 'String'));
dt = str2double(get(handles.edit_dt, 'String'));
[nz, nx, ~] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_nt, 'String', num2str(nt));
% 3D case
if (Ndims > 2)
dy = str2double(get(handles.edit_dy, 'String'));
dt = str2double(get(handles.edit_dt, 'String'));
[~, ~, ny] = size(vp);
nt = round((sqrt((dx*nx)^2 + (dy*ny)^2 + (dz*nz)^2)*2/vpmin/dt + 1));
set(handles.edit_nt, 'String', num2str(nt));
end
% --- Executes during object creation, after setting all properties.
function edit_dt_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_dt (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 edit_nx_Callback(hObject, eventdata, handles)
% hObject handle to edit_nx (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 edit_nx as text
% str2double(get(hObject,'String')) returns contents of edit_nx as a double
% --- Executes during object creation, after setting all properties.
function edit_nx_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_nx (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 edit_ny_Callback(hObject, eventdata, handles)
% hObject handle to edit_ny (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 edit_ny as text
% str2double(get(hObject,'String')) returns contents of edit_ny as a double
% --- Executes during object creation, after setting all properties.
function edit_ny_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_ny (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 edit_nz_Callback(hObject, eventdata, handles)
% hObject handle to edit_nz (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 edit_nz as text
% str2double(get(hObject,'String')) returns contents of edit_nz as a double
% --- Executes during object creation, after setting all properties.
function edit_nz_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_nz (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 edit_nt_Callback(hObject, eventdata, handles)
% hObject handle to edit_nt (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 edit_nt as text
% str2double(get(hObject,'String')) returns contents of edit_nt as a double
% --- Executes during object creation, after setting all properties.
function edit_nt_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_nt (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 menuHelp_Callback(hObject, eventdata, handles)
% hObject handle to menuHelp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menuHelpAbout_Callback(hObject, eventdata, handles)
% hObject handle to menuHelpAbout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
guiAbout;
function edit_boundary_Callback(hObject, eventdata, handles)
% hObject handle to edit_boundary (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 edit_boundary as text
% str2double(get(hObject,'String')) returns contents of edit_boundary as a double
% --- Executes during object creation, after setting all properties.
function edit_boundary_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_boundary (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 pmenu_approxOrder.
function pmenu_approxOrder_Callback(hObject, eventdata, handles)
% hObject handle to pmenu_approxOrder (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns pmenu_approxOrder contents as cell array
% contents{get(hObject,'Value')} returns selected item from pmenu_approxOrder
% --- Executes during object creation, after setting all properties.
function pmenu_approxOrder_CreateFcn(hObject, eventdata, handles)
% hObject handle to pmenu_approxOrder (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 edit_centerFreq_Callback(hObject, eventdata, handles)
% hObject handle to edit_centerFreq (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 edit_centerFreq as text
% str2double(get(hObject,'String')) returns contents of edit_centerFreq as a double
% --- Executes during object creation, after setting all properties.
function edit_centerFreq_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_centerFreq (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 edit_sx_Callback(hObject, eventdata, handles)
% hObject handle to edit_sx (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 edit_sx as text
% str2double(get(hObject,'String')) returns contents of edit_sx as a double
% --- Executes during object creation, after setting all properties.
function edit_sx_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sx (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 edit_sy_Callback(hObject, eventdata, handles)
% hObject handle to edit_sy (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 edit_sy as text
% str2double(get(hObject,'String')) returns contents of edit_sy as a double
% --- Executes during object creation, after setting all properties.
function edit_sy_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sy (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 edit_sz_Callback(hObject, eventdata, handles)
% hObject handle to edit_sz (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 edit_sz as text
% str2double(get(hObject,'String')) returns contents of edit_sz as a double
% --- Executes during object creation, after setting all properties.
function edit_sz_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sz (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 pmenu_sweepAll.
function pmenu_sweepAll_Callback(hObject, eventdata, handles)
% hObject handle to pmenu_sweepAll (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns pmenu_sweepAll contents as cell array
% contents{get(hObject,'Value')} returns selected item from pmenu_sweepAll
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
Ndims = ndims(vp);
[nz, nx, ~] = size(vp);
isSweepAll = get(hObject, 'Value');
if (isSweepAll == 1) % Yes
str_sx = sprintf('1:%d', nx);
set(handles.edit_sx, 'String', str_sx);
set(handles.edit_sx, 'Enable', 'off');
set(handles.edit_sz, 'Enable', 'off');
end
if (isSweepAll == 2) % No
set(handles.edit_sx, 'Enable', 'on');
set(handles.edit_sz, 'Enable', 'on');
end
% 3D case
if (Ndims > 2)
[~, ~, ny] = size(vp);
if (isSweepAll == 1) % Yes
str_sy = sprintf('1:%d', ny);
set(handles.edit_sy, 'String', str_sy);
set(handles.edit_sy, 'Enable', 'off');
end
if (isSweepAll == 2) % No
set(handles.edit_sy, 'Enable', 'on');
end
end
% --- Executes during object creation, after setting all properties.
function pmenu_sweepAll_CreateFcn(hObject, eventdata, handles)
% hObject handle to pmenu_sweepAll (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 selection change in pmenu_receiveAll.
function pmenu_receiveAll_Callback(hObject, eventdata, handles)
% hObject handle to pmenu_receiveAll (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns pmenu_receiveAll contents as cell array
% contents{get(hObject,'Value')} returns selected item from pmenu_receiveAll
data = guidata(hObject);
if (isfield(data, 'vp'))
vp = data.vp;
if (isfield(data, 'vs'))
vs = data.vs;
end
else % i.e., isfield(data, 'vs') == true
% only S-wave velocity model has been loaded, treat it as P-wave
% velocity model
vp = data.vs;
end
Ndims = ndims(vp);
isReceiveAll = get(hObject, 'Value');
if (isReceiveAll == 1) % Yes
set(handles.edit_rx, 'Enable', 'off');
end
if (isReceiveAll == 2) % No
set(handles.edit_rx, 'Enable', 'on');
end
% 3D case
if (Ndims > 2)
[~, ~, ny] = size(vp);
if (isReceiveAll == 1) % Yes
set(handles.edit_ry, 'Enable', 'off');
end
if (isReceiveAll == 2) % No
set(handles.edit_ry, 'Enable', 'on');
str_ry = sprintf('1:%d', ny);
set(handles.edit_ry, 'String', str_ry);
end
end
% --- Executes during object creation, after setting all properties.
function pmenu_receiveAll_CreateFcn(hObject, eventdata, handles)
% hObject handle to pmenu_receiveAll (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 edit_rx_Callback(hObject, eventdata, handles)
% hObject handle to edit_rx (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 edit_rx as text
% str2double(get(hObject,'String')) returns contents of edit_rx as a double
% --- Executes during object creation, after setting all properties.
function edit_rx_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_rx (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 edit_ry_Callback(hObject, eventdata, handles)
% hObject handle to edit_ry (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 edit_ry as text
% str2double(get(hObject,'String')) returns contents of edit_ry as a double
% --- Executes during object creation, after setting all properties.
function edit_ry_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_ry (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 edit_rz_Callback(hObject, eventdata, handles)
% hObject handle to edit_rz (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 edit_rz as text
% str2double(get(hObject,'String')) returns contents of edit_rz as a double
% --- Executes during object creation, after setting all properties.
function edit_rz_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_rz (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 when user attempts to close figureMain.
function figureMain_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figureMain (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
delete(hObject);
function edit_status_Callback(hObject, eventdata, handles)
% hObject handle to edit_status (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 edit_status as text
% str2double(get(hObject,'String')) returns contents of edit_status as a double
% --- Executes during object creation, after setting all properties.
function edit_status_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_status (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
|
github
|
lijunzh/fd_elastic-master
|
guiAbout.m
|
.m
|
fd_elastic-master/gui/guiAbout.m
| 3,151 |
utf_8
|
bb20ce2f08ae9a9280a307509fe67ae0
|
function varargout = guiAbout(varargin)
% GUIABOUT MATLAB code for guiAbout.fig
% GUIABOUT, by itself, creates a new GUIABOUT or raises the existing
% singleton*.
%
% H = GUIABOUT returns the handle to a new GUIABOUT or the handle to
% the existing singleton*.
%
% GUIABOUT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUIABOUT.M with the given input arguments.
%
% GUIABOUT('Property','Value',...) creates a new GUIABOUT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before guiAbout_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to guiAbout_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help guiAbout
% Last Modified by GUIDE v2.5 09-Nov-2014 00:18:26
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @guiAbout_OpeningFcn, ...
'gui_OutputFcn', @guiAbout_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 guiAbout is made visible.
function guiAbout_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 guiAbout (see VARARGIN)
% Choose default command line output for guiAbout
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% display logos
imshow('logo_csip.jpg', 'Parent', handles.axes_logo1);
imshow('logo_cegp.jpg', 'Parent', handles.axes_logo2);
% UIWAIT makes guiAbout wait for user response (see UIRESUME)
% uiwait(handles.figureMain);
% --- Outputs from this function are returned to the command line.
function varargout = guiAbout_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in btnOK.
function btnOK_Callback(hObject, eventdata, handles)
% hObject handle to btnOK (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(handles.figureMain);
|
github
|
lijunzh/fd_elastic-master
|
plotTrace.m
|
.m
|
fd_elastic-master/src/plotTrace.m
| 2,573 |
utf_8
|
b553ce3346283fa24804133d6d91d982
|
function plotTrace(data)
% PLOTTRACE plot seismic data traces
%
%
% This matlab source file is free for use in academic research.
% All rights reserved.
%
% Written by Lingchen Zhu ([email protected])
% Center for Signal and Information Processing, Center for Energy & Geo Processing
% Georgia Institute of Technology
[nSamples, nTraces] = size(data);
if (nSamples * nTraces == 0)
fprintf('No traces to plot\n');
return;
end
if (nSamples <= 1)
fprintf('Only one sample per trace. Data set is not going to plot.\n');
return;
end
times = (1:nSamples).';
location = 1:nTraces;
deflection = 1.25;
%% scale data
dx = (max(location)-min(location)) / (nTraces-1);
trace_max = max(abs(data));
scale = dx * deflection / (max(trace_max) + eps);
data = scale * data;
%% a figure window in portrait mode
hFig = figure;
set(hFig, 'Position', [288, 80, 900, 810], 'PaperPosition', [0.8, 0.5, 6.5, 8.0], ...
'PaperOrientation', 'portrait', 'Color', 'w', 'InvertHardcopy', 'off');
figure(hFig)
set(gca, 'Position', [0.14, 0.085, 0.75, 0.79]);
set(hFig, 'Color', 'w');
axis([min(location)-deflection, max(location) + deflection, 1, nSamples]); hold on;
hCurAx = get(gcf, 'CurrentAxes');
set(hCurAx, 'ydir','reverse')
set(hCurAx, 'XAxisLocation','top');
%% plot data
ue_seismic_plot(times, data, location);
xlabel('Trace Number'); ylabel('Samples');
set(gca, 'XTick', location, 'XTickLabel', location);
grid on;
set(hCurAx, 'gridlinestyle', '-', 'box', 'on', 'xgrid', 'off');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Function plot seismic traces at horizontal locations controlled by location
function ue_seismic_plot(times, trace, location)
peak_fill = 'k';
trough_fill = '';
for ii = 1:size(trace, 2)
y = trace(:, ii);
chg = find(y(1:end-1).*y(2:end) < 0);
x_zero = abs(y(chg) ./ (y(chg+1)-y(chg))) + times(chg);
[x_data, idx] = sort([times(1); times; x_zero; times(end)]);
y_data = [0; y; zeros(length(x_zero)+1, 1)];
y_data = y_data(idx);
h1 = fill(y_data(y_data >= 0) + location(ii), x_data(y_data >= 0), peak_fill);
set(h1, 'EdgeColor', 'none');
if ~isempty(trough_fill);
h1 = fill(y_data(y_data <= 0) + location(ii), x_data(y_data <= 0), trough_fill);
set(h1, 'EdgeColor', 'none');
end
plot([location(ii), location(ii)], [times(2), times(end)], 'w-')
line(y_data(2:end-1) + location(ii), x_data(2:end-1), 'Color', 'k', ...
'EraseMode', 'none', 'LineWidth', 0.5);
end
|
github
|
lijunzh/fd_elastic-master
|
createSampler.m
|
.m
|
fd_elastic-master/src/createSampler.m
| 1,662 |
utf_8
|
0c0ef6672c2fefa3f2dadab892a78123
|
% createSampler
% create sampler matrix for each branch in parallel structured sampler
% Author: Lingchen Zhu
% Creation Date: 11/07/2013
function Phi = createSampler(N, M, method, repeat, seed)
if (nargin < 4)
repeat = false;
end
if (nargin < 5)
seed = 0;
end
if (repeat)
rng(seed);
end
switch lower(method)
case 'rand'
Phi = sqrt(1/M) * randn(M, N);
case 'uniform'
Phi = zeros(M, N);
R = floor(N / M);
Phi(:, 1:R:N) = eye(M, M);
case {'rdemod', 'aic'}
R = N / M;
vec = binornd(1, 0.5, [1, N]);
vec(vec == 0) = -1;
D = diag(vec);
if (mod(N, M)) % R is not integer, maybe need more debugging
[N0, M0] = rat(R);
H0 = zeros(M0, N0);
jjtmp = 1;
for ii = 1:M0
Rtmp = R;
if (ii > 1)
H0(ii, jjtmp) = 1 - H0(ii-1, jjtmp);
else
H0(ii, jjtmp) = 1;
end
Rtmp = Rtmp - H0(ii, jjtmp);
for jj = jjtmp+1:N0
if (Rtmp > 1)
H0(ii, jj) = 1;
elseif (Rtmp > 0)
H0(ii, jj) = Rtmp;
else
jjtmp = jj-1;
break;
end
Rtmp = Rtmp - H0(ii, jj);
end
end
H = kron(eye(M/M0, N/N0), H0);
else % R is an integer
H = kron(eye(M, M), ones(1, R));
end
Phi = H * D;
otherwise
error('Unknown compressive sensing based sampler');
end
|
github
|
lijunzh/fd_elastic-master
|
wiggle.m
|
.m
|
fd_elastic-master/src/wiggle.m
| 17,037 |
utf_8
|
f32a3676d5f7f98124d16c4873f0a96a
|
%WIGGLE Display data as wiggles.
% WIGGLE(C) displays matrix C as wiggles plus filled lobes, which is a
% common display for seismic data or any oscillatory data. A WIGGLE
% display is similar to WATERFALL, except that the Z heights are
% projected onto the horizontal plane, meaning that a WIGGLE display is
% actually a 2D display.
%
% WIGGLE(C) plots each column of C as curves vertically. How much the
% deviation is from the jth vertical is given by ith row. It C(i,j) is
% positive then the curve bends to the right, otherwise it bends to the
% left. Best visual effect is achieved when each column has no DC
% component, i.e., when its sum is zero, or at least close to it.
%
% WIGGLE(X,Y,C), where X and Y are vectors, rescale the axes to match X
% and Y values. When WIGGLE has one or three input, its usage is very
% similar to IMAGE or IMAGESC, except for WIGGLE's properties, described
% below.
%
% WIGGLE(...,S) allows some control of wiggles properties, in which S is
% a string with up to six characters, each one setting up a property,
% which can be Extrusion, Polarity, Direction, Wiggle Color and Lobes
% Color.
%
% Extrusion: '0', '1', ..., '9'
% It is how much a wiggle overlaps its neighbor. The default, '0',
% means there is no overlap. For instance, E='1' means that a
% wiggle overlaps only one neighbor and so on. Observe that only
% positve numbers are allowed.
%
% Polarity: '+' or '-'
% It defines which side of the wiggle is going to be filled.
% Polarity '+' (default) means that the positive lobes are filled,
% while '-' means that the negative lobes are filled.
%
% Wiggles Direction: 'v' or ' h'
% It specifies if the wiggles are vertical ('v'), which is the default,
% or horizontal ('h').
%
% Wiggles Color: 'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w' or 'i'
% It defines the wiggle color. This property uses the same color key
% as in function PLOT. The default is black, i.e., 'k'. In order to
% suppress the wiggle, the character 'o' must be used. Options 'i',
% invisible, means that no wiggle is displayed.
%
% Lobes color: 'B', 'G', 'R', 'C', 'M', 'Y', 'K', 'W', 'X', '*' or 'I'
% It defines filling color for the right and left lobes. This property
% uses mostly the same color key as used in command PLOT, but in
% uppercase.
% The order of preference is right before left lobes, meaning that if
% only one character is given, the right lobes are painted with the
% corresponding color and the left lobes are invisible. In this way,
% the default is left lobes invisible and right lobes in black, i.e.,
% the string contains 'K' or 'IK'. Notice that a single 'I' implies
% that both lobes are invisible, because by default the left lobes are
% already invisible. If two capital characters are given, the first
% one defines the color of the left lobes and the second one of the
% right lobes.
% There are still two special coloring options which use the current
% figure colormap: '*' means that the lobes ares filled with a variable
% color that is horizontally layered and 'X' means that the lobes are
% filled with a variable color that is vertically layered.
%
% Note that the characters that build string S can be given in any
% order, but respecting the range and precedence of each propetry:
%
% Extrusion Polarity Direction Color
% Wiggles Lobes
% 0 - (default) + - right lobe v - vertical b blue B
% 1 - - left lobe h - horizontal g green G
% 2 r red R
% ... c cyan C
% m magenta M
% y yellow Y
% k black K
% w white W
% i invisible I
% colormap_h X
% colormap_v *
%
% Examples
% C = 2*rand(200,20) - 1;
% D = filter([1,1,1],1,C);
% figure(1); clf
% subplot(131); wiggle(D); title('default: right lobes in black')
% subplot(132); wiggle(D, '-'); title('left lobes in black')
% subplot(133); wiggle(D, 'yBR'); title('magenta lines, blue and red lobes')
% figure(2); clf
% subplot(311); wiggle(D', 'h'); title('Horizontal wiggles')
% subplot(312); wiggle(D', 'hB'); title('Horizontal wiggles with blue lobes')
% subplot(313); wiggle(D', 'hbMR'); title('Hor. wiggles, blue lines with magenta and red lobes')
% figure(3); clf
% subplot(131); wiggle(D, 'BR'); title('Blue and red lobes')
% subplot(132); wiggle(D, 'XX'); title('Horizontally filled colormapped lobes')
% subplot(133); wiggle(D, '1.5**'); title('Vertically filled colormapped lobes with 1.5 of extrusion')
%
% See also IMAGESC, IMAGE, WATERFALL, PLOT, LINESPEC
% by Rodrigo S. Portugal ([email protected])
% last revision: 18/10/2012
% TODO:
% 1) Implement the invisible option (DONE)
% 2) Implement the variable color option (DONE)
% 3) Implement wiggles overlaid imagesc (DONE)
% 3) Pair-wise options for fine tuning of properties (NOT YET)
% 3) Inspect the code (DONE)
% 4) Optimize (+/-)
% 5) Test examples (DONE)
function wiggle(varargin)
switch (nargin)
case 0
error('Too few input arguments.');
% Only data
case 1
data = check_data(varargin{1});
[nr,nc] = size(data);
xr = 1:nr;
xc = 1:nc;
prop = '';
% Data and properties
case 2
data = check_data(varargin{1});
[nr,nc] = size(data);
xr = 1:nr;
xc = 1:nc;
prop = check_properties(varargin{2});
% Domain vectors and data
case 3
xr = check_data(varargin{1});
xc = check_data(varargin{2});
data = check_data(varargin{3});
prop = '';
% Domain vectors, data and properties
case 4
xr = check_data(varargin{1});
xc = check_data(varargin{2});
data = check_data(varargin{3});
prop = check_properties(varargin{4});
otherwise
error('Too many input arguments.');
end
[extr, pol, dir, wcol, vcoll, vcolr] = extract_properties(prop);
wiggleplot(data, xr, xc, extr, wcol, vcoll, vcolr, dir, pol)
end
%--------------------------------------------------------------------------
function data = check_data(v)
if isnumeric(v),
data = v;
else
error('Wiggle: value must be numeric');
end
end
%--------------------------------------------------------------------------
function prop = check_properties(v)
if ischar(v)
prop = v;
else
error('Wiggle: properties must be a string.');
end
end
%--------------------------------------------------------------------------
function check_rgb(color)
if any(isnan(color)) || any(color > 1) || ...
size(color,1) ~= 1 || size(color,2) ~= 3
error(['Wiggle: color must be a numeric 1 x 3 matrix, '...
'following RGB system'])
end
end
%--------------------------------------------------------------------------
function [extr, pol, dir, wcol, vcoll, vcolr] = extract_properties(prop)
wcol = 'k';
vcol = 'k';
dir = 0;
pol = 1;
extr = extractfloat(prop);
if isnan(extr), extr = 1.0; end
indv = 1;
for ip = 1:length(prop)
p = prop(ip);
if p == '+' || p == '-'
if p == '+'
pol = 1;
else
pol = -1;
end
continue
end
if p == 'h' || p == 'v' || p == 'H' || p == 'V'
if p == 'v' || p == 'V',
dir = 0;
else
dir = 1;
end
continue
end
if p == 'b' || p == 'g' || p == 'r' || p == 'c' || p == 'm' || ...
p == 'y' || p == 'k' || p == 'w' || p == 'i'
wcol = p;
continue
end
if p == 'B' || p == 'G' || p == 'R' || p == 'C' || p == 'M' || ...
p == 'Y' || p == 'K' || p == 'W' || p == 'I' || p == 'X' || p == '*'
vcol(indv) = lower(p);
indv = 2;
continue
end
end
wcol = str2rgb(wcol);
if length(vcol) == 2
vcoll = str2rgb(vcol(1));
vcolr = str2rgb(vcol(2));
else
vcoll = NaN;
vcolr = str2rgb(vcol(1));
end
end
%--------------------------------------------------------------------------
function f = extractfloat(str)
fs = blanks(length(str));
foundpoint = false;
count = 1;
for i = 1: length(str)
cs = str(i);
if cs == '.' && ~foundpoint
fs(count) = cs;
count = count + 1;
foundpoint = true;
continue
end
c = str2double(cs);
if ~isnan(c) && isreal(c)
fs(count) = cs;
count = count + 1;
end
end
f = str2double(fs);
end
%--------------------------------------------------------------------------
function rgb = str2rgb(s)
switch s
case 'r'
rgb = [1, 0, 0];
case 'g'
rgb = [0, 1, 0];
case 'b'
rgb = [0, 0, 1];
case 'c'
rgb = [0, 1, 1];
case 'm'
rgb = [1, 0, 1];
case 'y'
rgb = [1, 1, 0];
case 'k'
rgb = [0, 0, 0];
case 'w'
rgb = [1, 1, 1];
case 'i'
rgb = NaN;
case 'x'
rgb = 1;
case '*'
rgb = 2;
otherwise
rgb = NaN;
end
end
%--------------------------------------------------------------------------
% WIGGLEPLOT plots seismic data as wiggles and variable area
% WIGGLEPLOT(data, y, x, k, wc, vcl, vcr, d, p)
% INPUT DESCRIPTION TYPE SIZE
% data oscilatory data matrix (nx x nt)
% y vertical coordinates vector ( 1 x ny)
% x horizontal coordinates vector ( 1 x nx)
% k extrusion scalar ( 1 x 1 )
% wc wiggle color matrix ( 1 x 3 )
% wc=0 supress the wiggle
% vcl variable area color (left lobe) matrix ( 1 x 3 )
% vcl=0 or NaN suppress the left variable area
% vcr variable area color matrix ( 1 x 3 )
% vcr=0 or NaN suppress the right variable area
% d wiggle direction scalar ( 1 x 1 )
% d=0 for vertical
% d=1 for horizontal
% p polarity scalar ( 1 x 1 )
% p=1 (SEG convention) positive area
% p=-1 (EAGE convention) negative area
%
% See also IMAGESC, IMAGE
function wiggleplot(data, xr, xc, extr, wcol, vcoll, vcolr, dir, pol)
[nrows,ncols] = size(data);
if ncols ~= length(xc) || nrows ~= length(xr)
error('Input data must have compatible dimensions');
end
if dir == 1
data = data';
extr = -extr;
aux = xc;
xc = xr;
xr = aux;
end
nxr = length(xr);
nxc = length(xc);
if nxc > 1,
dx = xc(2)-xc(1);
else
dx = 1;
end
% ir = nxr-1:-1:2;
plot_var = true;
plot_val = true;
if length(vcoll) == 1
if isnan(vcoll) || vcoll == 0
plot_val = false;
elseif vcoll ~= 1 && vcoll ~= 2
error('wiggleplot: color not recognized.')
end
else
check_rgb(vcoll)
end
if length(vcolr) == 1
if isnan(vcolr) || vcolr == 0
plot_var = false;
elseif vcolr ~= 1 && vcolr ~= 2
error('wiggleplot: color not recognized.')
end
else
check_rgb(vcolr)
end
plot_w = true;
if length(wcol) == 1
if isnan(wcol) || wcol == 0
plot_w = false;
else
error('wiggleplot: color not recognized.')
end
else
check_rgb(wcol)
end
if pol == -1,
data = -data;
end
count = make_counter(nxc, dir);
[plotdir, patchdirl, patchdirr] = select_functions(dir, plot_w, plot_val, plot_var);
scale = pol * extr * dx / (max(data(:))+eps);
hold on
xwig = zeros(nxc,2*nxr+1);
ywig = zeros(nxc,2*nxr+1);
if vcoll == 2
chunk = zeros(nxc,4*nxr+3);
else
chunk = zeros(nxc,2*nxr+2);
end
xval = chunk; yval = chunk; %cval = chunk;
xvar = chunk; yvar = chunk; %cvar = chunk;
for ic = count(1):count(2):count(3)
[xr1, d, sl1, sr1, ~, ~] = make_lines(xr, data(:,ic)');
xr2 = xr1;
sr2 = sr1;
sl2 = sl1;
if vcolr == 1
colr = [0, d, 0];
elseif vcolr == 2
colr = [0, d, 0, fliplr(d), 0];
xr2 = [xr1, fliplr(xr1(1:end-1))];
sr2 = [sr1, zeros(1,length(sr1)-1)];
else
colr = vcolr;
end
xvar(ic,:) = xc(ic) + scale * sr2;
yvar(ic,:) = xr2;
cvar(ic,:) = colr;
if vcoll == 1
coll = [0, d, 0];
elseif vcoll == 2
coll = [0, d, 0, fliplr(d), 0];
xr2 = [xr1, fliplr(xr1(1:end-1))];
sl2 = [sl1, zeros(1,length(sl1)-1)];
else
coll = vcoll;
end
xval(ic,:) = xc(ic) + scale * sl2;
yval(ic,:) = xr2;
cval(ic,:) = coll;
xwig(ic,:) = [xc(ic) + scale * d, NaN];
ywig(ic,:) = [xr1(2:end-1), NaN];
end
patchdirl(xval', yval', cval');
patchdirr(xvar', yvar', cvar');
plotdir(xwig,ywig,wcol);
hold off
if dir == 1,
axis([min(xr), max(xr), min(xc) - extr * dx, max(xc) + extr * dx])
else
axis([min(xc) - extr * dx, max(xc) + extr * dx, min(xr), max(xr)])
end
set(gca,'NextPlot','replace', 'XDir','normal','YDir','reverse')
end
%--------------------------------------------------------------------------
function counter = make_counter(nxc, dir)
if dir == 1,
ic_first = 1;
ic_last = nxc;
ic_step = 1;
else
ic_first = nxc;
ic_last = 1;
ic_step = -1;
end
counter = [ic_first, ic_step, ic_last];
end
%--------------------------------------------------------------------------
function [fw, fval, fvar] = select_functions(dir, plot_w, plot_val, plot_var)
fw = @plot_vert;
fval = @patch_vert;
fvar = @patch_vert;
if dir == 1,
fw = @plot_hor;
fval = @patch_hor;
fvar = @patch_hor;
end
if plot_w == false
fw = @donothing;
end
if plot_val == false
fval = @donothing;
end
if plot_var == false
fvar = @donothing;
end
if (plot_val == false) && (plot_var == false) && (plot_w == false),
disp('wiggle warning: neither variable area and wiggles are displayed');
end
end
%--------------------------------------------------------------------------
function [t1, d, sl, sr, ul, ur] = make_lines(t, s)
nt = length(t);
dt = t(2) - t(1);
ds = s(2:nt)-s(1:nt-1);
r = ((s(2:nt)<0) .* (s(1:nt-1)>0)) + ((s(2:nt)>0) .* (s(1:nt-1)<0));
a = r .* s(2:nt)./(ds+eps) + (1-r).*0.5;
tc(1:2:2*nt-1) = t;
tc(2:2:2*nt-2) = t(2:nt) - dt * a;
sc(1:2:2*nt-1) = s;
sc(2:2:2*nt-2) = 0.5*(s(1:nt-1)+ s(2:nt)).*(1-r);
t1 = [t(1), tc, t(nt), t(nt)];
d0 = [0, sc, s(nt), 0];
dr = [max(sc), sc, s(nt), max(sc)];
dl = [min(sc), sc, s(nt), min(sc)];
sl = min(0,d0);
sr = max(0,d0);
ul = min(0,dl);
ur = max(0,dr);
d = d0(2:end-1);
end
%--------------------------------------------------------------------------
function donothing(~,~,~)
end
%--------------------------------------------------------------------------
function ph = plot_vert(x,y,col)
x = reshape(x',1,numel(x));
y = reshape(y',1,numel(y));
ph = line(x,y,'linewidth',0.25,'color', col);
end
%--------------------------------------------------------------------------
function ph = plot_hor(x,y,col)
x = reshape(x',1,numel(x));
y = reshape(y',1,numel(y));
ph = line(y,x,'linewidth',0.25,'color', col);
end
%--------------------------------------------------------------------------
function fh = patch_vert(x,y,col)
if size(col,1) == 3,
col = col(:,1)';
end
fh = patch(x,y,col,'edgecolor','none');
hold on
end
%--------------------------------------------------------------------------
function fh = patch_hor(x,y,col)
if size(col,1) == 3,
col = col(:,1)';
end
fh = patch(y,x,col,'edgecolor','none');
hold on
end
|
github
|
lijunzh/fd_elastic-master
|
lbfgs.m
|
.m
|
fd_elastic-master/src/lbfgs.m
| 3,948 |
utf_8
|
4fafb45e1f656cdb02aa7dc9fc971fe2
|
function [x, f] = lbfgs(fh,x0,options)
% Simple L-BFGS method with Wolfe linesearch
%
% use:
% [xn,info] = lbfgs(fh,x0,options)
%
% input:
% fh - function handle to misfit of the form [f,g] = fh(x)
% where f is the function value, g is the gradient of the same size
% as the input vector x.
% x0 - initial guess
%
% options.itermax - max iterations [default 10]
% options.tol - tolerance on 2-norm of gradient [default 1e-6]
% options.M - history size [default 5]
% options.fid - file id for output [default 1]
%
% output:
% xn - final estimate
%
%
% Author: Tristan van Leeuwen
% Seismic Laboratory for Imaging and Modeling
% Department of Earch & Ocean Sciences
% The University of British Columbia
%
% Date: February, 2012
%
% You may use this code only under the conditions and terms of the
% license contained in the file LICENSE provided with this source
% code. If you do not agree to these terms you may not use this
% software.
if nargin<3
options = [];
end
% various parameters
M = 5;
fid = 1;
itermax = 10;
tol = 1e-6;
if isfield(options,'itermax')
itermax = options.itermax;
end
if isfield(options,'M');
M = options.M;
end
if isfield(options,'fid')
fid = options.fid;
end
if isfield(options,'tol')
tol = options.tol;
end
% initialization
n = length(x0);
converged = 0;
iter = 0;
x = x0;
S = zeros(n,0);
Y = zeros(n,0);
% initial evaluation
[f,g] = fh(x);
nfeval = 1;
fprintf(fid,'# iter, # eval, stepsize, f(x) , ||g(x)||_2\n');
fprintf(fid,'%6d, %6d, %1.2e, %1.5e, %1.5e\n',iter,nfeval,1,f,norm(g));
% main loop
while ~converged
% compute search direction
s = B(-g,S,Y);
p = -(s'*g)/(g'*g);
if (p < 0)
fprintf(fid,'Loss of descent, reset history\n');
S = zeros(n,0);
Y = zeros(n,0);
s = B(-g,S,Y);
end
% linesearch
[ft,gt,lambda,lsiter] = wWolfeLS(fh,x,f,g,s);
nfeval = nfeval + lsiter;
% update
xt = x + lambda*s;
S = [S xt - x];
Y = [Y gt - g];
if size(S,2)>M
S = S(:,end-M+1:end);
Y = Y(:,end-M+1:end);
end
f = ft;
g = gt;
x = xt;
iter = iter + 1;
fprintf(fid,'%6d, %6d, %1.2e, %1.5e, %1.5e\n',iter,nfeval,lambda,f,norm(g));
% check convergence
converged = (iter>itermax)||(norm(g)<tol)||(lambda<tol);
end
end
function z = B(x,S,Y)
% apply lbfgs inverse Hessian to vector
%
% Tristan van Leeuwen, 2011
% [email protected]
%
% use:
% z = B(x,S,Y,b0,Binit)
%
% input:
% x - vector of length n
% S - history of steps in n x M matrix
% Y - history of gradient differences in n x M matrix
%
% output
% z - vector of length n
%
M = size(S,2);
alpha = zeros(M,1);
rho = zeros(M,1);
for k = 1:M
rho(k) = 1/(Y(:,k)'*S(:,k));
end
q = x;
% first recursion
for k = M:-1:1
alpha(k) = rho(k)*S(:,k)'*q;
q = q - alpha(k)*Y(:,k);
end
% apply `initial' Hessian
if M>0
a = (Y(:,end)'*S(:,end)/(Y(:,end)'*Y(:,end)));
else
a = 1/norm(x,1);
end
z = a*q;
% second recursion
for k = 1:M
beta = rho(k)*Y(:,k)'*z;
z = z + (alpha(k) - beta)*S(:,k);
end
end
function [ft,gt,lambda,lsiter] = wWolfeLS(fh,x0,f0,g0,s0)
% Simple Wolfe linesearch, adapted from
% (http://cs.nyu.edu/overton/mstheses/skajaa/msthesis.pdf, algorihtm 3).
%
%
lsiter = 0;
c1 = 1e-2;
c2 = 0.9;
done = 0;
mu = 0;
nu = inf;
lambda = .5;
while ~done
if nu < inf
lambda = (nu + mu)/2;
else
lambda = 2*lambda;
end
if lsiter < 50
[ft,gt] = fh(x0 + lambda*s0);
lsiter = lsiter + 1;
else
% lambda = 0;
break;
end
fprintf(1,' >%d, %1.5e, %1.5e, %1.5e\n',lsiter, lambda, ft, gt'*s0);
if ft > f0 + c1*lambda*g0'*s0
nu = lambda;
elseif gt'*s0 < c2*g0'*s0
mu = lambda;
else
done = 1;
end
end
end
|
github
|
lijunzh/fd_elastic-master
|
fdct_wrapping_dispcoef.m
|
.m
|
fd_elastic-master/src/CurveLab-2.1.3/fdct_wrapping_matlab/fdct_wrapping_dispcoef.m
| 1,919 |
utf_8
|
2af5a55f76ce583e6879244514db1b37
|
function img = fdct_wrapping_dispcoef(C)
% fdct_wrapping_dispcoef - returns an image containing all the curvelet coefficients
%
% Inputs
% C Curvelet coefficients
%
% Outputs
% img Image containing all the curvelet coefficients. The coefficents are rescaled so that
% the largest coefficent in each subband has unit norm.
%
[m,n] = size(C{end}{1});
nbscales = floor(log2(min(m,n)))-3;
img = C{1}{1}; img = img/max(max(abs(img))); %normalize
for sc=2:nbscales-1
nd = length(C{sc})/4;
wcnt = 0;
ONE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
ONE = [ONE, fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
TWO = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
TWO = [TWO; fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
THREE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
THREE = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}), THREE];
end
wcnt = wcnt+nd;
FOUR = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
FOUR = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}); FOUR];
end
wcnt = wcnt+nd;
[p,q] = size(img);
[a,b] = size(ONE);
[g,h] = size(TWO);
m = 2*a+g; n = 2*h+b; %size of new image
scale = max(max( max(max(abs(ONE))),max(max(abs(TWO))) ), max(max(max(abs(THREE))), max(max(abs(FOUR))) )); %scaling factor
new = 0.5 * ones(m,n);%background value
new(a+1:a+g,1:h) = FOUR/scale;
new(a+g+1:2*a+g,h+1:h+b) = THREE/scale;
new(a+1:a+g,h+b+1:2*h+b) = TWO/scale;
new(1:a,h+1:h+b) = ONE/scale;%normalize
dx = floor((g-p)/2); dy = floor((b-q)/2);
new(a+1+dx:a+p+dx,h+1+dy:h+q+dy) = img;
img = new;
end
function A = fdct_wrapping_dispcoef_expand(u,v,B)
A = zeros(u,v);
[p,q] = size(B);
A(1:p,1:q) = B;
|
github
|
lijunzh/fd_elastic-master
|
spgdemo.m
|
.m
|
fd_elastic-master/src/spgl1-1.8/spgdemo.m
| 16,195 |
utf_8
|
629972a6bc0f55788ac56dda78d403a2
|
function spgdemo(interactive)
%DEMO Demonstrates the use of the SPGL1 solver
%
% See also SPGL1.
% demo.m
% $Id: spgdemo.m 1079 2008-08-20 21:34:15Z ewout78 $
%
% ----------------------------------------------------------------------
% This file is part of SPGL1 (Spectral Projected Gradient for L1).
%
% Copyright (C) 2007 Ewout van den Berg and Michael P. Friedlander,
% Department of Computer Science, University of British Columbia, Canada.
% All rights reserved. E-mail: <{ewout78,mpf}@cs.ubc.ca>.
%
% SPGL1 is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation; either version 2.1 of the
% License, or (at your option) any later version.
%
% SPGL1 is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with SPGL1; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
% USA
% ----------------------------------------------------------------------
if nargin < 1 || isempty(interactive), interactive = true; end
% Initialize random number generators
rand('state',0);
randn('state',0);
% Create random m-by-n encoding matrix and sparse vector
m = 50; n = 128; k = 14;
[A,Rtmp] = qr(randn(n,m),0);
A = A';
p = randperm(n); p = p(1:k);
x0 = zeros(n,1); x0(p) = randn(k,1);
% -----------------------------------------------------------
% Solve the underdetermined LASSO problem for ||x||_1 <= pi:
%
% minimize ||Ax-b||_2 subject to ||x||_1 <= 3.14159...
%
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the underdetermined LASSO problem for \n');
fprintf('%% \n');
fprintf('%% minimize ||Ax-b||_2 subject to ||x||_1 <= 3.14159...\n');
fprintf('%% \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Set up vector b, and run solver
b = A * x0;
tau = pi;
x = spg_lasso(A, b, tau);
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf(['nonzeros(x) = %i, ' ...
'||x||_1 = %12.6e, ' ...
'||x||_1 - pi = %13.6e\n'], ...
length(find(abs(x)>1e-5)), norm(x,1), norm(x,1)-pi);
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve the basis pursuit (BP) problem:
%
% minimize ||x||_1 subject to Ax = b
%
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the basis pursuit (BP) problem:\n');
fprintf('%% \n');
fprintf('%% minimize ||x||_1 subject to Ax = b \n');
fprintf('%% \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Set up vector b, and run solver
b = A * x0; % Signal
opts = spgSetParms('verbosity',1);
x = spg_bp(A, b, opts);
figure(1); subplot(2,4,1);
plot(1:n,x,'b', 1:n,x0,'ro');
legend('Recovered coefficients','Original coefficients');
title('(a) Basis Pursuit');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(a).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve the basis pursuit denoise (BPDN) problem:
%
% minimize ||x||_1 subject to ||Ax - b||_2 <= 0.1
%
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the basis pursuit denoise (BPDN) problem: \n');
fprintf('%% \n');
fprintf('%% minimize ||x||_1 subject to ||Ax - b||_2 <= 0.1\n');
fprintf('%% \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Set up vector b, and run solver
b = A * x0 + randn(m,1) * 0.075;
sigma = 0.10; % Desired ||Ax - b||_2
opts = spgSetParms('verbosity',1);
x = spg_bpdn(A, b, sigma, opts);
figure(1); subplot(2,4,2);
plot(1:n,x,'b', 1:n,x0,'ro');
legend('Recovered coefficients','Original coefficients');
title('(b) Basis Pursuit Denoise');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(b).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve the basis pursuit (BP) problem in COMPLEX variables:
%
% minimize ||z||_1 subject to Az = b
%
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the basis pursuit (BP) problem in COMPLEX variables:\n');
fprintf('%% \n');
fprintf('%% minimize ||z||_1 subject to Az = b \n');
fprintf('%% \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Create partial Fourier operator with rows idx
idx = randperm(n); idx = idx(1:m);
opA = @(x,mode) partialFourier(idx,n,x,mode);
% Create sparse coefficients and b = 'A' * z0;
z0 = zeros(n,1);
z0(p) = randn(k,1) + sqrt(-1) * randn(k,1);
b = opA(z0,1);
opts = spgSetParms('verbosity',1);
z = spg_bp(opA,b,opts);
figure(1); subplot(2,4,3);
plot(1:n,real(z),'b+',1:n,real(z0),'bo', ...
1:n,imag(z),'r+',1:n,imag(z0),'ro');
legend('Recovered (real)', 'Original (real)', ...
'Recovered (imag)', 'Original (imag)');
title('(c) Complex Basis Pursuit');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(c).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Sample the Pareto frontier at 100 points:
%
% phi(tau) = minimize ||Ax-b||_2 subject to ||x|| <= tau
%
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Sample the Pareto frontier at 100 points:\n');
fprintf('%% \n');
fprintf('%% phi(tau) = minimize ||Ax-b||_2 subject to ||x|| <= tau\n');
fprintf('%% \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
fprintf('\nComputing sample');
% Set up vector b, and run solver
b = A*x0;
x = zeros(n,1);
tau = linspace(0,1.05 * norm(x0,1),100);
phi = zeros(size(tau));
opts = spgSetParms('iterations',1000,'verbosity',0);
for i=1:length(tau)
[x,r] = spgl1(A,b,tau(i),[],x,opts);
phi(i) = norm(r);
if ~mod(i,10), fprintf('...%i',i); end
end
fprintf('\n');
figure(1); subplot(2,4,4);
plot(tau,phi);
title('(d) Pareto frontier');
xlabel('||x||_1'); ylabel('||Ax-b||_2');
fprintf('\n');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(d).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve
%
% minimize ||y||_1 subject to AW^{-1}y = b
%
% and the weighted basis pursuit (BP) problem:
%
% minimize ||Wx||_1 subject to Ax = b
%
% followed by setting y = Wx.
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve \n');
fprintf('%% \n');
fprintf('%% (1) minimize ||y||_1 subject to AW^{-1}y = b \n');
fprintf('%% \n');
fprintf('%% and the weighted basis pursuit (BP) problem: \n');
fprintf('%% \n');
fprintf('%% (2) minimize ||Wx||_1 subject to Ax = b \n');
fprintf('%% \n');
fprintf('%% followed by setting y = Wx. \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Sparsify vector x0 a bit more to get exact recovery
k = 9;
x0 = zeros(n,1); x0(p(1:k)) = randn(k,1);
% Set up weights w and vector b
w = rand(n,1) + 0.1; % Weights
b = A * (x0 ./ w); % Signal
% Run solver for both variants
opts = spgSetParms('iterations',1000,'verbosity',1);
AW = A * spdiags(1./w,0,n,n);
x = spg_bp(AW, b, opts);
x1 = x; % Reconstruct solution, no weighting
opts = spgSetParms('iterations',1000,'verbosity',1,'weights',w);
x = spg_bp(A, b, opts);
x2 = x .* w; % Reconstructed solution, with weighting
figure(1); subplot(2,4,5);
plot(1:n,x1,'m*',1:n,x2,'b', 1:n,x0,'ro');
legend('Coefficients (1)','Coefficients (2)','Original coefficients');
title('(e) Weighted Basis Pursuit');
fprintf('\n');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(e).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve the multiple measurement vector (MMV) problem
%
% minimize ||Y||_1,2 subject to AW^{-1}Y = B
%
% and the weighted MMV problem (weights on the rows of X):
%
% minimize ||WX||_1,2 subject to AX = B
%
% followed by setting Y = WX.
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the multiple measurement vector (MMV) problem \n');
fprintf('%% \n');
fprintf('%% (1) minimize ||Y||_1,2 subject to AW^{-1}Y = B \n');
fprintf('%% \n');
fprintf('%% and the weighted MMV problem (weights on the rows of X): \n');
fprintf('%% \n');
fprintf('%% (2) minimize ||WX||_1,2 subject to AX = B \n');
fprintf('%% \n');
fprintf('%% followed by setting Y = WX. \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Initialize random number generator
randn('state',0); rand('state',0);
% Create problem
m = 100; n = 150; k = 12; l = 6;
A = randn(m,n);
p = randperm(n); p = p(1:k);
X0= zeros(n,l); X0(p,:) = randn(k,l);
weights = 3 * rand(n,1) + 0.1;
W = spdiags(1./weights,0,n,n);
B = A*W*X0;
% Solve unweighted version
opts = spgSetParms('verbosity',1);
x = spg_mmv(A*W,B,0,opts);
x1 = x;
% Solve weighted version
opts = spgSetParms('verbosity',1,'weights',weights);
x = spg_mmv(A,B,0,opts);
x2 = spdiags(weights,0,n,n) * x;
% Plot results
figure(1); subplot(2,4,6);
plot(x1(:,1),'b-'); hold on;
plot(x2(:,1),'b.');
plot(X0,'ro');
plot(x1(:,2:end),'-');
plot(x2(:,2:end),'b.');
legend('Coefficients (1)','Coefficients (2)','Original coefficients');
title('(f) Weighted Basis Pursuit with Multiple Measurement Vectors');
fprintf('\n');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(f).\n');
fprintf([repmat('-',1,80), '\n']);
fprintf('\n\n');
% -----------------------------------------------------------
% Solve the group-sparse Basis Pursuit problem
%
% minimize sum_i ||y(group == i)||_2
% subject to AW^{-1}y = b,
%
% with W(i,i) = w(group(i)), and the weighted group-sparse
% problem
%
% minimize sum_i w(i)*||x(group == i)||_2
% subject to Ax = b,
%
% followed by setting y = Wx.
% -----------------------------------------------------------
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('%% Solve the group-sparse Basis Pursuit problem \n');
fprintf('%% \n');
fprintf('%% (1) minimize sum_i ||y(group == i)||_2 \n');
fprintf('%% subject to AW^{-1}y = b, \n');
fprintf('%% \n');
fprintf('%% with W(i,i) = w(group(i)), and the weighted group-sparse\n');
fprintf('%% problem \n');
fprintf('%% \n');
fprintf('%% (2) minimize sum_i w(i)*||x(group == i)||_2 \n');
fprintf('%% subject to Ax = b, \n');
fprintf('%% \n');
fprintf('%% followed by setting y = Wx. \n');
fprintf(['%% ', repmat('-',1,78), '\n']);
fprintf('\nPress <return> to continue ... \n');
if interactive, pause; end
% Initialize random number generator
randn('state',0); rand('state',2); % 2
% Set problem size and number of groups
m = 100; n = 150; nGroups = 25; groups = [];
% Generate groups with desired number of unique groups
while (length(unique(groups)) ~= nGroups)
groups = sort(ceil(rand(n,1) * nGroups)); % Sort for display purpose
end
% Determine weight for each group
weights = 3*rand(nGroups,1) + 0.1;
W = spdiags(1./weights(groups),0,n,n);
% Create sparse vector x0 and observation vector b
p = randperm(nGroups); p = p(1:3);
idx = ismember(groups,p);
x0 = zeros(n,1); x0(idx) = randn(sum(idx),1);
b = A*W*x0;
% Solve unweighted version
opts = spgSetParms('verbosity',1);
x = spg_group(A*W,b,groups,0,opts);
x1 = x;
% Solve weighted version
opts = spgSetParms('verbosity',1,'weights',weights);
x = spg_group(A,b,groups,0,opts);
x2 = spdiags(weights(groups),0,n,n) * x;
% Plot results
figure(1); subplot(2,4,7);
plot(x1); hold on;
plot(x2,'b+');
plot(x0,'ro'); hold off;
legend('Coefficients (1)','Coefficients (2)','Original coefficients');
title('(g) Weighted Group-sparse Basis Pursuit');
fprintf('\n');
fprintf([repmat('-',1,35), ' Solution ', repmat('-',1,35), '\n']);
fprintf('See figure 1(g).\n');
fprintf([repmat('-',1,80), '\n']);
end % function demo
function y = partialFourier(idx,n,x,mode)
if mode==1
% y = P(idx) * FFT(x)
z = fft(x) / sqrt(n);
y = z(idx);
else
z = zeros(n,1);
z(idx) = x;
y = ifft(z) * sqrt(n);
end
end % function partialFourier
|
github
|
lijunzh/fd_elastic-master
|
spg_mmv.m
|
.m
|
fd_elastic-master/src/spgl1-1.8/spg_mmv.m
| 2,853 |
utf_8
|
d6de8533593624586e911b8b26de8f3b
|
function [x,r,g,info] = spg_mmv( A, B, sigma, options )
%SPG_MMV Solve multi-measurement basis pursuit denoise (BPDN)
%
% SPG_MMV is designed to solve the basis pursuit denoise problem
%
% (BPDN) minimize ||X||_1,2 subject to ||A X - B||_2,2 <= SIGMA,
%
% where A is an M-by-N matrix, B is an M-by-G matrix, and SIGMA is a
% nonnegative scalar. In all cases below, A can be an explicit M-by-N
% matrix or matrix-like object for which the operations A*x and A'*y
% are defined (i.e., matrix-vector multiplication with A and its
% adjoint.)
%
% Also, A can be a function handle that points to a function with the
% signature
%
% v = A(w,mode) which returns v = A *w if mode == 1;
% v = A'*w if mode == 2.
%
% X = SPG_MMV(A,B,SIGMA) solves the BPDN problem. If SIGMA=0 or
% SIGMA=[], then the basis pursuit (BP) problem is solved; i.e., the
% constraints in the BPDN problem are taken as AX=B.
%
% X = SPG_MMV(A,B,SIGMA,OPTIONS) specifies options that are set using
% SPGSETPARMS.
%
% [X,R,G,INFO] = SPG_BPDN(A,B,SIGMA,OPTIONS) additionally returns the
% residual R = B - A*X, the objective gradient G = A'*R, and an INFO
% structure. (See SPGL1 for a description of this last output argument.)
%
% See also spgl1, spgSetParms, spg_bp, spg_lasso.
% Copyright 2008, Ewout van den Berg and Michael P. Friedlander
% http://www.cs.ubc.ca/labs/scl/spgl1
% $Id$
if ~exist('options','var'), options = []; end
if ~exist('sigma','var'), sigma = 0; end
if ~exist('B','var') || isempty(B)
error('Second argument cannot be empty.');
end
if ~exist('A','var') || isempty(A)
error('First argument cannot be empty.');
end
groups = size(B,2);
if isa(A,'function_handle')
y = A(B(:,1),2); m = size(B,1); n = length(y);
A = @(x,mode) blockDiagonalImplicit(A,m,n,groups,x,mode);
else
m = size(A,1); n = size(A,2);
A = @(x,mode) blockDiagonalExplicit(A,m,n,groups,x,mode);
end
% Set projection specific functions
options.project = @(x,weight,tau) NormL12_project(groups,x,weight,tau);
options.primal_norm = @(x,weight ) NormL12_primal(groups,x,weight);
options.dual_norm = @(x,weight ) NormL12_dual(groups,x,weight);
tau = 0;
x0 = [];
[x,r,g,info] = spgl1(A,B(:),tau,sigma,x0,options);
n = round(length(x) / groups);
m = size(B,1);
x = reshape(x,n,groups);
y = reshape(r,m,groups);
g = reshape(g,n,groups);
function y = blockDiagonalImplicit(A,m,n,g,x,mode)
if mode == 1
y = zeros(m*g,1);
for i=1:g
y(1+(i-1)*m:i*m) = A(x(1+(i-1)*n:i*n),mode);
end
else
y = zeros(n*g,1);
for i=1:g
y(1+(i-1)*n:i*n) = A(x(1+(i-1)*m:i*m),mode);
end
end
function y = blockDiagonalExplicit(A,m,n,g,x,mode)
if mode == 1
y = A * reshape(x,n,g);
y = y(:);
else
x = reshape(x,m,g);
y = (x' * A)';
y = y(:);
end
|
github
|
lijunzh/fd_elastic-master
|
spgl1.m
|
.m
|
fd_elastic-master/src/spgl1-1.8/spgl1.m
| 31,061 |
utf_8
|
ba9dfd0ef199543c9289ed4fd0d301bd
|
function [x,r,g,info] = spgl1( A, b, tau, sigma, x, options )
%SPGL1 Solve basis pursuit, basis pursuit denoise, and LASSO
%
% [x, r, g, info] = spgl1(A, b, tau, sigma, x0, options)
%
% ---------------------------------------------------------------------
% Solve the basis pursuit denoise (BPDN) problem
%
% (BPDN) minimize ||x||_1 subj to ||Ax-b||_2 <= sigma,
%
% or the l1-regularized least-squares problem
%
% (LASSO) minimize ||Ax-b||_2 subj to ||x||_1 <= tau.
% ---------------------------------------------------------------------
%
% INPUTS
% ======
% A is an m-by-n matrix, explicit or an operator.
% If A is a function, then it must have the signature
%
% y = A(x,mode) if mode == 1 then y = A x (y is m-by-1);
% if mode == 2 then y = A'x (y is n-by-1).
%
% b is an m-vector.
% tau is a nonnegative scalar; see (LASSO).
% sigma if sigma != inf or != [], then spgl1 will launch into a
% root-finding mode to find the tau above that solves (BPDN).
% In this case, it's STRONGLY recommended that tau = 0.
% x0 is an n-vector estimate of the solution (possibly all
% zeros). If x0 = [], then SPGL1 determines the length n via
% n = length( A'b ) and sets x0 = zeros(n,1).
% options is a structure of options from spgSetParms. Any unset options
% are set to their default value; set options=[] to use all
% default values.
%
% OUTPUTS
% =======
% x is a solution of the problem
% r is the residual, r = b - Ax
% g is the gradient, g = -A'r
% info is a structure with the following information:
% .tau final value of tau (see sigma above)
% .rNorm two-norm of the optimal residual
% .rGap relative duality gap (an optimality measure)
% .gNorm Lagrange multiplier of (LASSO)
% .stat = 1 found a BPDN solution
% = 2 found a BP sol'n; exit based on small gradient
% = 3 found a BP sol'n; exit based on small residual
% = 4 found a LASSO solution
% = 5 error: too many iterations
% = 6 error: linesearch failed
% = 7 error: found suboptimal BP solution
% = 8 error: too many matrix-vector products
% .time total solution time (seconds)
% .nProdA number of multiplications with A
% .nProdAt number of multiplications with A'
%
% OPTIONS
% =======
% Use the options structure to control various aspects of the algorithm:
%
% options.fid File ID to direct log output
% .verbosity 0=quiet, 1=some output, 2=more output.
% .iterations Max. number of iterations (default if 10*m).
% .bpTol Tolerance for identifying a basis pursuit solution.
% .optTol Optimality tolerance (default is 1e-4).
% .decTol Larger decTol means more frequent Newton updates.
% .subspaceMin 0=no subspace minimization, 1=subspace minimization.
%
% EXAMPLE
% =======
% m = 120; n = 512; k = 20; % m rows, n cols, k nonzeros.
% p = randperm(n); x0 = zeros(n,1); x0(p(1:k)) = sign(randn(k,1));
% A = randn(m,n); [Q,R] = qr(A',0); A = Q';
% b = A*x0 + 0.005 * randn(m,1);
% opts = spgSetParms('optTol',1e-4);
% [x,r,g,info] = spgl1(A, b, 0, 1e-3, [], opts); % Find BP sol'n.
%
% AUTHORS
% =======
% Ewout van den Berg ([email protected])
% Michael P. Friedlander ([email protected])
% Scientific Computing Laboratory (SCL)
% University of British Columbia, Canada.
%
% BUGS
% ====
% Please send bug reports or comments to
% Michael P. Friedlander ([email protected])
% Ewout van den Berg ([email protected])
% 15 Apr 07: First version derived from spg.m.
% Michael P. Friedlander ([email protected]).
% Ewout van den Berg ([email protected]).
% 17 Apr 07: Added root-finding code.
% 18 Apr 07: sigma was being compared to 1/2 r'r, rather than
% norm(r), as advertised. Now immediately change sigma to
% (1/2)sigma^2, and changed log output accordingly.
% 24 Apr 07: Added quadratic root-finding code as an option.
% 24 Apr 07: Exit conditions need to guard against small ||r||
% (ie, a BP solution). Added test1,test2,test3 below.
% 15 May 07: Trigger to update tau is now based on relative difference
% in objective between consecutive iterations.
% 15 Jul 07: Added code to allow a limited number of line-search
% errors.
% 23 Feb 08: Fixed bug in one-norm projection using weights. Thanks
% to Xiangrui Meng for reporting this bug.
% 26 May 08: The simple call spgl1(A,b) now solves (BPDN) with sigma=0.
% 18 Mar 13: Reset f = fOld if curvilinear line-search fails.
% Avoid computing the Barzilai-Borwein scaling parameter
% when both line-search algorithms failed.
% ----------------------------------------------------------------------
% This file is part of SPGL1 (Spectral Projected-Gradient for L1).
%
% Copyright (C) 2007 Ewout van den Berg and Michael P. Friedlander,
% Department of Computer Science, University of British Columbia, Canada.
% All rights reserved. E-mail: <{ewout78,mpf}@cs.ubc.ca>.
%
% SPGL1 is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation; either version 2.1 of the
% License, or (at your option) any later version.
%
% SPGL1 is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with SPGL1; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
% USA
% ----------------------------------------------------------------------
REVISION = '$Revision: 1017 $';
DATE = '$Date: 2008-06-16 22:43:07 -0700 (Mon, 16 Jun 2008) $';
REVISION = REVISION(11:end-1);
DATE = DATE(35:50);
tic; % Start your watches!
m = length(b);
%----------------------------------------------------------------------
% Check arguments.
%----------------------------------------------------------------------
if ~exist('options','var'), options = []; end
if ~exist('x','var'), x = []; end
if ~exist('sigma','var'), sigma = []; end
if ~exist('tau','var'), tau = []; end
if nargin < 2 || isempty(b) || isempty(A)
error('At least two arguments are required');
elseif isempty(tau) && isempty(sigma)
tau = 0;
sigma = 0;
singleTau = false;
elseif isempty(sigma) % && ~isempty(tau) <-- implied
singleTau = true;
else
if isempty(tau)
tau = 0;
end
singleTau = false;
end
%----------------------------------------------------------------------
% Grab input options and set defaults where needed.
%----------------------------------------------------------------------
defaultopts = spgSetParms(...
'fid' , 1 , ... % File ID for output
'verbosity' , 2 , ... % Verbosity level
'iterations' , 10*m , ... % Max number of iterations
'nPrevVals' , 3 , ... % Number previous func values for linesearch
'bpTol' , 1e-06 , ... % Tolerance for basis pursuit solution
'lsTol' , 1e-06 , ... % Least-squares optimality tolerance
'optTol' , 1e-04 , ... % Optimality tolerance
'decTol' , 1e-04 , ... % Req'd rel. change in primal obj. for Newton
'stepMin' , 1e-16 , ... % Minimum spectral step
'stepMax' , 1e+05 , ... % Maximum spectral step
'rootMethod' , 2 , ... % Root finding method: 2=quad,1=linear (not used).
'activeSetIt', Inf , ... % Exit with EXIT_ACTIVE_SET if nnz same for # its.
'subspaceMin', 0 , ... % Use subspace minimization
'iscomplex' , NaN , ... % Flag set to indicate complex problem
'maxMatvec' , Inf , ... % Maximum matrix-vector multiplies allowed
'weights' , 1 , ... % Weights W in ||Wx||_1
'project' , @NormL1_project , ...
'primal_norm', @NormL1_primal , ...
'dual_norm' , @NormL1_dual ...
);
options = spgSetParms(defaultopts, options);
fid = options.fid;
logLevel = options.verbosity;
maxIts = options.iterations;
nPrevVals = options.nPrevVals;
bpTol = options.bpTol;
lsTol = options.lsTol;
optTol = options.optTol;
decTol = options.decTol;
stepMin = options.stepMin;
stepMax = options.stepMax;
activeSetIt = options.activeSetIt;
subspaceMin = options.subspaceMin;
maxMatvec = max(3,options.maxMatvec);
weights = options.weights;
maxLineErrors = 10; % Maximum number of line-search failures.
pivTol = 1e-12; % Threshold for significant Newton step.
%----------------------------------------------------------------------
% Initialize local variables.
%----------------------------------------------------------------------
iter = 0; itnTotLSQR = 0; % Total SPGL1 and LSQR iterations.
nProdA = 0; nProdAt = 0;
lastFv = -inf(nPrevVals,1); % Last m function values.
nLineTot = 0; % Total no. of linesearch steps.
printTau = false;
nNewton = 0;
bNorm = norm(b,2);
stat = false;
timeProject = 0;
timeMatProd = 0;
nnzIter = 0; % No. of its with fixed pattern.
nnzIdx = []; % Active-set indicator.
subspace = false; % Flag if did subspace min in current itn.
stepG = 1; % Step length for projected gradient.
testUpdateTau = 0; % Previous step did not update tau
% Determine initial x, vector length n, and see if problem is complex
explicit = ~(isa(A,'function_handle'));
if isempty(x)
if isnumeric(A)
n = size(A,2);
realx = isreal(A) && isreal(b);
else
x = Aprod(b,2);
n = length(x);
realx = isreal(x) && isreal(b);
end
x = zeros(n,1);
else
n = length(x);
realx = isreal(x) && isreal(b);
end
if isnumeric(A), realx = realx && isreal(A); end;
% Override options when options.iscomplex flag is set
if (~isnan(options.iscomplex)), realx = (options.iscomplex == 0); end
% Check if all weights (if any) are strictly positive. In previous
% versions we also checked if the number of weights was equal to
% n. In the case of multiple measurement vectors, this no longer
% needs to apply, so the check was removed.
if ~isempty(weights)
if any(~isfinite(weights))
error('Entries in options.weights must be finite');
end
if any(weights <= 0)
error('Entries in options.weights must be strictly positive');
end
else
weights = 1;
end
% Quick exit if sigma >= ||b||. Set tau = 0 to short-circuit the loop.
if bNorm <= sigma
printf('W: sigma >= ||b||. Exact solution is x = 0.\n');
tau = 0; singleTau = true;
end
% Don't do subspace minimization if x is complex.
if ~realx && subspaceMin
printf('W: Subspace minimization disabled when variables are complex.\n');
subspaceMin = false;
end
% Pre-allocate iteration info vectors
xNorm1 = zeros(min(maxIts,10000),1);
rNorm2 = zeros(min(maxIts,10000),1);
lambda = zeros(min(maxIts,10000),1);
% Exit conditions (constants).
EXIT_ROOT_FOUND = 1;
EXIT_BPSOL_FOUND = 2;
EXIT_LEAST_SQUARES = 3;
EXIT_OPTIMAL = 4;
EXIT_ITERATIONS = 5;
EXIT_LINE_ERROR = 6;
EXIT_SUBOPTIMAL_BP = 7;
EXIT_MATVEC_LIMIT = 8;
EXIT_ACTIVE_SET = 9; % [sic]
%----------------------------------------------------------------------
% Log header.
%----------------------------------------------------------------------
printf('\n');
printf(' %s\n',repmat('=',1,80));
printf(' SPGL1 v.%s (%s)\n', REVISION, DATE);
printf(' %s\n',repmat('=',1,80));
printf(' %-22s: %8i %4s' ,'No. rows' ,m ,'');
printf(' %-22s: %8i\n' ,'No. columns' ,n );
printf(' %-22s: %8.2e %4s' ,'Initial tau' ,tau ,'');
printf(' %-22s: %8.2e\n' ,'Two-norm of b' ,bNorm );
printf(' %-22s: %8.2e %4s' ,'Optimality tol' ,optTol ,'');
if singleTau
printf(' %-22s: %8.2e\n' ,'Target one-norm of x' ,tau );
else
printf(' %-22s: %8.2e\n','Target objective' ,sigma );
end
printf(' %-22s: %8.2e %4s' ,'Basis pursuit tol' ,bpTol ,'');
printf(' %-22s: %8i\n' ,'Maximum iterations',maxIts );
printf('\n');
if singleTau
logB = ' %5i %13.7e %13.7e %9.2e %6.1f %6i %6i';
logH = ' %5s %13s %13s %9s %6s %6s %6s\n';
printf(logH,'Iter','Objective','Relative Gap','gNorm','stepG','nnzX','nnzG');
else
logB = ' %5i %13.7e %13.7e %9.2e %9.3e %6.1f %6i %6i';
logH = ' %5s %13s %13s %9s %9s %6s %6s %6s %13s\n';
printf(logH,'Iter','Objective','Relative Gap','Rel Error',...
'gNorm','stepG','nnzX','nnzG','tau');
end
% Project the starting point and evaluate function and gradient.
x = project(x,tau);
r = b - Aprod(x,1); % r = b - Ax
g = - Aprod(r,2); % g = -A'r
f = r'*r / 2;
% Required for nonmonotone strategy.
lastFv(1) = f;
fBest = f;
xBest = x;
fOld = f;
% Compute projected gradient direction and initial steplength.
dx = project(x - g, tau) - x;
dxNorm = norm(dx,inf);
if dxNorm < (1 / stepMax)
gStep = stepMax;
else
gStep = min( stepMax, max(stepMin, 1/dxNorm) );
end
%----------------------------------------------------------------------
% MAIN LOOP.
%----------------------------------------------------------------------
while 1
%------------------------------------------------------------------
% Test exit conditions.
%------------------------------------------------------------------
% Compute quantities needed for log and exit conditions.
gNorm = options.dual_norm(-g,weights);
rNorm = norm(r, 2);
gap = r'*(r-b) + tau*gNorm;
rGap = abs(gap) / max(1,f);
aError1 = rNorm - sigma;
aError2 = f - sigma^2 / 2;
rError1 = abs(aError1) / max(1,rNorm);
rError2 = abs(aError2) / max(1,f);
% Count number of consecutive iterations with identical support.
nnzOld = nnzIdx;
[nnzX,nnzG,nnzIdx,nnzDiff] = activeVars(x,g,nnzIdx,options);
if nnzDiff
nnzIter = 0;
else
nnzIter = nnzIter + 1;
if nnzIter >= activeSetIt, stat=EXIT_ACTIVE_SET; end
end
% Single tau: Check if we're optimal.
% The 2nd condition is there to guard against large tau.
if singleTau
if rGap <= optTol || rNorm < optTol*bNorm
stat = EXIT_OPTIMAL;
end
% Multiple tau: Check if found root and/or if tau needs updating.
else
% Test if a least-squares solution has been found
if gNorm <= lsTol * rNorm
stat = EXIT_LEAST_SQUARES;
end
if rGap <= max(optTol, rError2) || rError1 <= optTol
% The problem is nearly optimal for the current tau.
% Check optimality of the current root.
test1 = rNorm <= bpTol * bNorm;
% test2 = gNorm <= bpTol * rNorm;
test3 = rError1 <= optTol;
test4 = rNorm <= sigma;
if test4, stat=EXIT_SUBOPTIMAL_BP;end % Found suboptimal BP sol.
if test3, stat=EXIT_ROOT_FOUND; end % Found approx root.
if test1, stat=EXIT_BPSOL_FOUND; end % Resid minim'zd -> BP sol.
% 30 Jun 09: Large tau could mean large rGap even near LS sol.
% Move LS check out of this if statement.
% if test2, stat=EXIT_LEAST_SQUARES; end % Gradient zero -> BP sol.
end
testRelChange1 = (abs(f - fOld) <= decTol * f);
testRelChange2 = (abs(f - fOld) <= 1e-1 * f * (abs(rNorm - sigma)));
testUpdateTau = ((testRelChange1 && rNorm > 2 * sigma) || ...
(testRelChange2 && rNorm <= 2 * sigma)) && ...
~stat && ~testUpdateTau;
if testUpdateTau
% Update tau.
tauOld = tau;
tau = max(0,tau + (rNorm * aError1) / gNorm);
nNewton = nNewton + 1;
printTau = abs(tauOld - tau) >= 1e-6 * tau; % For log only.
if tau < tauOld
% The one-norm ball has decreased. Need to make sure that the
% next iterate if feasible, which we do by projecting it.
x = project(x,tau);
end
end
end
% Too many its and not converged.
if ~stat && iter >= maxIts
stat = EXIT_ITERATIONS;
end
%------------------------------------------------------------------
% Print log, update history and act on exit conditions.
%------------------------------------------------------------------
if logLevel >= 2 || singleTau || printTau || iter == 0 || stat
tauFlag = ' '; subFlag = '';
if printTau, tauFlag = sprintf(' %13.7e',tau); end
if subspace, subFlag = sprintf(' S %2i',itnLSQR); end
if singleTau
printf(logB,iter,rNorm,rGap,gNorm,log10(stepG),nnzX,nnzG);
if subspace
printf(' %s',subFlag);
end
else
printf(logB,iter,rNorm,rGap,rError1,gNorm,log10(stepG),nnzX,nnzG);
if printTau || subspace
printf(' %s',[tauFlag subFlag]);
end
end
printf('\n');
end
printTau = false;
subspace = false;
% Update history info
xNorm1(iter+1) = options.primal_norm(x,weights);
rNorm2(iter+1) = rNorm;
lambda(iter+1) = gNorm;
if stat, break; end % Act on exit conditions.
%==================================================================
% Iterations begin here.
%==================================================================
iter = iter + 1;
xOld = x; fOld = f; gOld = g; rOld = r;
try
%---------------------------------------------------------------
% Projected gradient step and linesearch.
%---------------------------------------------------------------
[f,x,r,nLine,stepG,lnErr] = ...
spgLineCurvy(x,gStep*g,max(lastFv),@Aprod,b,@project,tau);
nLineTot = nLineTot + nLine;
if lnErr
% Projected backtrack failed. Retry with feasible dir'n linesearch.
x = xOld;
f = fOld;
dx = project(x - gStep*g, tau) - x;
gtd = g'*dx;
[f,x,r,nLine,lnErr] = spgLine(f,x,dx,gtd,max(lastFv),@Aprod,b);
nLineTot = nLineTot + nLine;
end
if lnErr
% Failed again. Revert to previous iterates and damp max BB step.
x = xOld;
f = fOld;
if maxLineErrors <= 0
stat = EXIT_LINE_ERROR;
else
stepMax = stepMax / 10;
printf(['W: Linesearch failed with error %i. '...
'Damping max BB scaling to %6.1e.\n'],lnErr,stepMax);
maxLineErrors = maxLineErrors - 1;
end
end
%---------------------------------------------------------------
% Subspace minimization (only if active-set change is small).
%---------------------------------------------------------------
doSubspaceMin = false;
if subspaceMin
g = - Aprod(r,2);
[nnzX,nnzG,nnzIdx,nnzDiff] = activeVars(x,g,nnzOld,options);
if ~nnzDiff
if nnzX == nnzG, itnMaxLSQR = 20;
else itnMaxLSQR = 5;
end
nnzIdx = abs(x) >= optTol;
doSubspaceMin = true;
end
end
if doSubspaceMin
% LSQR parameters
damp = 1e-5;
aTol = 1e-1;
bTol = 1e-1;
conLim = 1e12;
showLSQR = 0;
ebar = sign(x(nnzIdx));
nebar = length(ebar);
Sprod = @(y,mode)LSQRprod(@Aprod,nnzIdx,ebar,n,y,mode);
[dxbar, istop, itnLSQR] = ...
lsqr(m,nebar,Sprod,r,damp,aTol,bTol,conLim,itnMaxLSQR,showLSQR);
itnTotLSQR = itnTotLSQR + itnLSQR;
if istop ~= 4 % LSQR iterations successful. Take the subspace step.
% Push dx back into full space: dx = Z dx.
dx = zeros(n,1);
dx(nnzIdx) = dxbar - (1/nebar)*(ebar'*dxbar)*dxbar;
% Find largest step to a change in sign.
block1 = nnzIdx & x < 0 & dx > +pivTol;
block2 = nnzIdx & x > 0 & dx < -pivTol;
alpha1 = Inf; alpha2 = Inf;
if any(block1), alpha1 = min(-x(block1) ./ dx(block1)); end
if any(block2), alpha2 = min(-x(block2) ./ dx(block2)); end
alpha = min([1 alpha1 alpha2]);
ensure(alpha >= 0);
ensure(ebar'*dx(nnzIdx) <= optTol);
% Update variables.
x = x + alpha*dx;
r = b - Aprod(x,1);
f = r'*r / 2;
subspace = true;
end
end
ensure(options.primal_norm(x,weights) <= tau+optTol);
%---------------------------------------------------------------
% Update gradient and compute new Barzilai-Borwein scaling.
%---------------------------------------------------------------
if (~lnErr)
g = - Aprod(r,2);
s = x - xOld;
y = g - gOld;
sts = s'*s;
sty = s'*y;
if sty <= 0, gStep = stepMax;
else gStep = min( stepMax, max(stepMin, sts/sty) );
end
else
gStep = min( stepMax, gStep );
end
catch err % Detect matrix-vector multiply limit error
if strcmp(err.identifier,'SPGL1:MaximumMatvec')
stat = EXIT_MATVEC_LIMIT;
iter = iter - 1;
x = xOld; f = fOld; g = gOld; r = rOld;
break;
else
rethrow(err);
end
end
%------------------------------------------------------------------
% Update function history.
%------------------------------------------------------------------
if singleTau || f > sigma^2 / 2 % Don't update if superoptimal.
lastFv(mod(iter,nPrevVals)+1) = f;
if fBest > f
fBest = f;
xBest = x;
end
end
end % while 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Restore best solution (only if solving single problem).
if singleTau && f > fBest
rNorm = sqrt(2*fBest);
printf('\n Restoring best iterate to objective %13.7e\n',rNorm);
x = xBest;
r = b - Aprod(x,1);
g = - Aprod(r,2);
gNorm = options.dual_norm(g,weights);
rNorm = norm(r, 2);
end
% Final cleanup before exit.
info.tau = tau;
info.rNorm = rNorm;
info.rGap = rGap;
info.gNorm = gNorm;
info.rGap = rGap;
info.stat = stat;
info.iter = iter;
info.nProdA = nProdA;
info.nProdAt = nProdAt;
info.nNewton = nNewton;
info.timeProject = timeProject;
info.timeMatProd = timeMatProd;
info.itnLSQR = itnTotLSQR;
info.options = options;
info.timeTotal = toc;
info.xNorm1 = xNorm1(1:iter);
info.rNorm2 = rNorm2(1:iter);
info.lambda = lambda(1:iter);
% Print final output.
switch (stat)
case EXIT_OPTIMAL
printf('\n EXIT -- Optimal solution found\n')
case EXIT_ITERATIONS
printf('\n ERROR EXIT -- Too many iterations\n');
case EXIT_ROOT_FOUND
printf('\n EXIT -- Found a root\n');
case {EXIT_BPSOL_FOUND}
printf('\n EXIT -- Found a BP solution\n');
case {EXIT_LEAST_SQUARES}
printf('\n EXIT -- Found a least-squares solution\n');
case EXIT_LINE_ERROR
printf('\n ERROR EXIT -- Linesearch error (%i)\n',lnErr);
case EXIT_SUBOPTIMAL_BP
printf('\n EXIT -- Found a suboptimal BP solution\n');
case EXIT_MATVEC_LIMIT
printf('\n EXIT -- Maximum matrix-vector operations reached\n');
case EXIT_ACTIVE_SET
printf('\n EXIT -- Found a possible active set\n');
otherwise
error('Unknown termination condition\n');
end
printf('\n');
printf(' %-20s: %6i %6s %-20s: %6.1f\n',...
'Products with A',nProdA,'','Total time (secs)',info.timeTotal);
printf(' %-20s: %6i %6s %-20s: %6.1f\n',...
'Products with A''',nProdAt,'','Project time (secs)',timeProject);
printf(' %-20s: %6i %6s %-20s: %6.1f\n',...
'Newton iterations',nNewton,'','Mat-vec time (secs)',timeMatProd);
printf(' %-20s: %6i %6s %-20s: %6i\n', ...
'Line search its',nLineTot,'','Subspace iterations',itnTotLSQR);
printf('\n');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NESTED FUNCTIONS. These share some vars with workspace above.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = Aprod(x,mode)
if (nProdA + nProdAt >= maxMatvec)
error('SPGL1:MaximumMatvec','');
end
tStart = toc;
if mode == 1
nProdA = nProdA + 1;
if explicit, z = A*x;
else z = A(x,1);
end
elseif mode == 2
nProdAt = nProdAt + 1;
if explicit, z = A'*x;
else z = A(x,2);
end
else
error('Wrong mode!');
end
timeMatProd = timeMatProd + (toc - tStart);
end % function Aprod
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function printf(varargin)
if logLevel > 0
fprintf(fid,varargin{:});
end
end % function printf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = project(x, tau)
tStart = toc;
x = options.project(x,weights,tau);
timeProject = timeProject + (toc - tStart);
end % function project
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% End of nested functions.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end % function spg
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PRIVATE FUNCTIONS.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [nnzX,nnzG,nnzIdx,nnzDiff] = activeVars(x,g,nnzIdx,options)
% Find the current active set.
% nnzX is the number of nonzero x.
% nnzG is the number of elements in nnzIdx.
% nnzIdx is a vector of primal/dual indicators.
% nnzDiff is the no. of elements that changed in the support.
xTol = min(.1,10*options.optTol);
gTol = min(.1,10*options.optTol);
gNorm = options.dual_norm(g,options.weights);
nnzOld = nnzIdx;
% Reduced costs for postive & negative parts of x.
z1 = gNorm + g;
z2 = gNorm - g;
% Primal/dual based indicators.
xPos = x > xTol & z1 < gTol; %g < gTol;%
xNeg = x < -xTol & z2 < gTol; %g > gTol;%
nnzIdx = xPos | xNeg;
% Count is based on simple primal indicator.
nnzX = sum(abs(x) >= xTol);
nnzG = sum(nnzIdx);
if isempty(nnzOld)
nnzDiff = inf;
else
nnzDiff = sum(nnzIdx ~= nnzOld);
end
end % function spgActiveVars
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = LSQRprod(Aprod,nnzIdx,ebar,n,dx,mode)
% Matrix multiplication for subspace minimization.
% Only called by LSQR.
nbar = length(ebar);
if mode == 1
y = zeros(n,1);
y(nnzIdx) = dx - (1/nbar)*(ebar'*dx)*ebar; % y(nnzIdx) = Z*dx
z = Aprod(y,1); % z = S Z dx
else
y = Aprod(dx,2);
z = y(nnzIdx) - (1/nbar)*(ebar'*y(nnzIdx))*ebar;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fNew,xNew,rNew,iter,err] = spgLine(f,x,d,gtd,fMax,Aprod,b)
% Nonmonotone linesearch.
EXIT_CONVERGED = 0;
EXIT_ITERATIONS = 1;
maxIts = 10;
step = 1;
iter = 0;
gamma = 1e-4;
gtd = -abs(gtd); % 03 Aug 07: If gtd is complex,
% then should be looking at -abs(gtd).
while 1
% Evaluate trial point and function value.
xNew = x + step*d;
rNew = b - Aprod(xNew,1);
fNew = rNew'*rNew / 2;
% Check exit conditions.
if fNew < fMax + gamma*step*gtd % Sufficient descent condition.
err = EXIT_CONVERGED;
break
elseif iter >= maxIts % Too many linesearch iterations.
err = EXIT_ITERATIONS;
break
end
% New linesearch iteration.
iter = iter + 1;
% Safeguarded quadratic interpolation.
if step <= 0.1
step = step / 2;
else
tmp = (-gtd*step^2) / (2*(fNew-f-step*gtd));
if tmp < 0.1 || tmp > 0.9*step || isnan(tmp)
tmp = step / 2;
end
step = tmp;
end
end % while 1
end % function spgLine
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fNew,xNew,rNew,iter,step,err] = ...
spgLineCurvy(x,g,fMax,Aprod,b,project,tau)
% Projected backtracking linesearch.
% On entry,
% g is the (possibly scaled) steepest descent direction.
EXIT_CONVERGED = 0;
EXIT_ITERATIONS = 1;
EXIT_NODESCENT = 2;
gamma = 1e-4;
maxIts = 10;
step = 1;
sNorm = 0;
scale = 1; % Safeguard scaling. (See below.)
nSafe = 0; % No. of safeguarding steps.
iter = 0;
debug = false; % Set to true to enable log.
n = length(x);
if debug
fprintf(' %5s %13s %13s %13s %8s\n',...
'LSits','fNew','step','gts','scale');
end
while 1
% Evaluate trial point and function value.
xNew = project(x - step*scale*g, tau);
rNew = b - Aprod(xNew,1);
fNew = rNew'*rNew / 2;
s = xNew - x;
gts = scale * real(g' * s);
% gts = scale * (g' * s);
if gts >= 0
err = EXIT_NODESCENT;
break
end
if debug
fprintf(' LS %2i %13.7e %13.7e %13.6e %8.1e\n',...
iter,fNew,step,gts,scale);
end
% 03 Aug 07: If gts is complex, then should be looking at -abs(gts).
% 13 Jul 11: It's enough to use real part of g's (see above).
if fNew < fMax + gamma*step*gts
% if fNew < fMax - gamma*step*abs(gts) % Sufficient descent condition.
err = EXIT_CONVERGED;
break
elseif iter >= maxIts % Too many linesearch iterations.
err = EXIT_ITERATIONS;
break
end
% New linesearch iteration.
iter = iter + 1;
step = step / 2;
% Safeguard: If stepMax is huge, then even damped search
% directions can give exactly the same point after projection. If
% we observe this in adjacent iterations, we drastically damp the
% next search direction.
% 31 May 07: Damp consecutive safeguarding steps.
sNormOld = sNorm;
sNorm = norm(s) / sqrt(n);
% if sNorm >= sNormOld
if abs(sNorm - sNormOld) <= 1e-6 * sNorm
gNorm = norm(g) / sqrt(n);
scale = sNorm / gNorm / (2^nSafe);
nSafe = nSafe + 1;
end
end % while 1
end % function spgLineCurvy
|
github
|
lijunzh/fd_elastic-master
|
oneProjectorMex.m
|
.m
|
fd_elastic-master/src/spgl1-1.8/private/oneProjectorMex.m
| 3,797 |
utf_8
|
df5afe507062bc6b713674d862bf73cd
|
function [x, itn] = oneProjectorMex(b,d,tau)
% [x, itn] = oneProjectorMex(b,d,tau)
% Return the orthogonal projection of the vector b >=0 onto the
% (weighted) L1 ball. In case vector d is specified, matrix D is
% defined as diag(d), otherwise the identity matrix is used.
%
% On exit,
% x solves minimize ||b-x||_2 st ||Dx||_1 <= tau.
% itn is the number of elements of b that were thresholded.
%
% See also spgl1, oneProjector.
% oneProjectorMex.m
% $Id: oneProjectorMex.m 1200 2008-11-21 19:58:28Z mpf $
%
% ----------------------------------------------------------------------
% This file is part of SPGL1 (Spectral Projected Gradient for L1).
%
% Copyright (C) 2007 Ewout van den Berg and Michael P. Friedlander,
% Department of Computer Science, University of British Columbia, Canada.
% All rights reserved. E-mail: <{ewout78,mpf}@cs.ubc.ca>.
%
% SPGL1 is free software; you can redistribute it and/or modify it
% under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation; either version 2.1 of the
% License, or (at your option) any later version.
%
% SPGL1 is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
% Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public
% License along with SPGL1; if not, write to the Free Software
% Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
% USA
% ----------------------------------------------------------------------
if nargin < 3
tau = d;
d = 1;
end
if isscalar(d)
[x,itn] = oneProjectorMex_I(b,tau/abs(d));
else
[x,itn] = oneProjectorMex_D(b,d,tau);
end
end % function oneProjectorMex
% ----------------------------------------------------------------------
function [x,itn] = oneProjectorMex_I(b,tau)
% ----------------------------------------------------------------------
% Initialization
n = length(b);
x = zeros(n,1);
bNorm = norm(b,1);
% Check for quick exit.
if (tau >= bNorm), x = b; itn = 0; return; end
if (tau < eps ), itn = 0; return; end
% Preprocessing (b is assumed to be >= 0)
[b,idx] = sort(b,'descend'); % Descending.
csb = -tau;
alphaPrev = 0;
for j= 1:n
csb = csb + b(j);
alpha = csb / j;
% We are done as soon as the constraint can be satisfied
% without exceeding the current minimum value of b
if alpha >= b(j)
break;
end
alphaPrev = alpha;
end
% Set the solution by applying soft-thresholding with
% the previous value of alpha
x(idx) = max(0,b - alphaPrev);
% Set number of iterations
itn = j;
end
% ----------------------------------------------------------------------
function [x,itn] = oneProjectorMex_D(b,d,tau)
% ----------------------------------------------------------------------
% Initialization
n = length(b);
x = zeros(n,1);
% Check for quick exit.
if (tau >= norm(d.*b,1)), x = b; itn = 0; return; end
if (tau < eps ), itn = 0; return; end
% Preprocessing (b is assumed to be >= 0)
[bd,idx] = sort(b ./ d,'descend'); % Descending.
b = b(idx);
d = d(idx);
% Optimize
csdb = 0; csd2 = 0;
soft = 0; alpha1 = 0; i = 1;
while (i <= n)
csdb = csdb + d(i).*b(i);
csd2 = csd2 + d(i).*d(i);
alpha1 = (csdb - tau) / csd2;
alpha2 = bd(i);
if alpha1 >= alpha2
break;
end
soft = alpha1; i = i + 1;
end
x(idx(1:i-1)) = b(1:i-1) - d(1:i-1) * max(0,soft);
% Set number of iterations
itn = i;
end
|
github
|
lijunzh/fd_elastic-master
|
lsqr.m
|
.m
|
fd_elastic-master/src/spgl1-1.8/private/lsqr.m
| 11,849 |
utf_8
|
b60925c5944249161e00049c67d30868
|
function [ x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var ]...
= lsqr( m, n, A, b, damp, atol, btol, conlim, itnlim, show )
%
% [ x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var ]...
% = lsqr( m, n, A, b, damp, atol, btol, conlim, itnlim, show );
%
% LSQR solves Ax = b or min ||b - Ax||_2 if damp = 0,
% or min || (b) - ( A )x || otherwise.
% || (0) (damp I) ||2
% A is an m by n matrix defined or a function handle of aprod( mode,x ),
% that performs the matrix-vector operations.
% If mode = 1, aprod must return y = Ax without altering x.
% If mode = 2, aprod must return y = A'x without altering x.
%-----------------------------------------------------------------------
% LSQR uses an iterative (conjugate-gradient-like) method.
% For further information, see
% 1. C. C. Paige and M. A. Saunders (1982a).
% LSQR: An algorithm for sparse linear equations and sparse least squares,
% ACM TOMS 8(1), 43-71.
% 2. C. C. Paige and M. A. Saunders (1982b).
% Algorithm 583. LSQR: Sparse linear equations and least squares problems,
% ACM TOMS 8(2), 195-209.
% 3. M. A. Saunders (1995). Solution of sparse rectangular systems using
% LSQR and CRAIG, BIT 35, 588-604.
%
% Input parameters:
% atol, btol are stopping tolerances. If both are 1.0e-9 (say),
% the final residual norm should be accurate to about 9 digits.
% (The final x will usually have fewer correct digits,
% depending on cond(A) and the size of damp.)
% conlim is also a stopping tolerance. lsqr terminates if an estimate
% of cond(A) exceeds conlim. For compatible systems Ax = b,
% conlim could be as large as 1.0e+12 (say). For least-squares
% problems, conlim should be less than 1.0e+8.
% Maximum precision can be obtained by setting
% atol = btol = conlim = zero, but the number of iterations
% may then be excessive.
% itnlim is an explicit limit on iterations (for safety).
% show = 1 gives an iteration log,
% show = 0 suppresses output.
%
% Output parameters:
% x is the final solution.
% istop gives the reason for termination.
% istop = 1 means x is an approximate solution to Ax = b.
% = 2 means x approximately solves the least-squares problem.
% r1norm = norm(r), where r = b - Ax.
% r2norm = sqrt( norm(r)^2 + damp^2 * norm(x)^2 )
% = r1norm if damp = 0.
% anorm = estimate of Frobenius norm of Abar = [ A ].
% [damp*I]
% acond = estimate of cond(Abar).
% arnorm = estimate of norm(A'*r - damp^2*x).
% xnorm = norm(x).
% var (if present) estimates all diagonals of (A'A)^{-1} (if damp=0)
% or more generally (A'A + damp^2*I)^{-1}.
% This is well defined if A has full column rank or damp > 0.
% (Not sure what var means if rank(A) < n and damp = 0.)
%
%
% 1990: Derived from Fortran 77 version of LSQR.
% 22 May 1992: bbnorm was used incorrectly. Replaced by anorm.
% 26 Oct 1992: More input and output parameters added.
% 01 Sep 1994: Matrix-vector routine is now a parameter 'aprodname'.
% Print log reformatted.
% 14 Jun 1997: show added to allow printing or not.
% 30 Jun 1997: var added as an optional output parameter.
% 07 Aug 2002: Output parameter rnorm replaced by r1norm and r2norm.
% Michael Saunders, Systems Optimization Laboratory,
% Dept of MS&E, Stanford University.
% 03 Jul 2007: Modified 'aprodname' to A, which can either be an m by n
% matrix, or a function handle.
% Ewout van den Berg, University of British Columbia
% 03 Jul 2007: Modified 'test2' condition, omitted 'test1'.
% Ewout van den Berg, University of British Columbia
%-----------------------------------------------------------------------
% Initialize.
msg=['The exact solution is x = 0 '
'Ax - b is small enough, given atol, btol '
'The least-squares solution is good enough, given atol '
'The estimate of cond(Abar) has exceeded conlim '
'Ax - b is small enough for this machine '
'The least-squares solution is good enough for this machine'
'Cond(Abar) seems to be too large for this machine '
'The iteration limit has been reached '];
wantvar= nargout >= 6;
if wantvar, var = zeros(n,1); end
if show
disp(' ')
disp('LSQR Least-squares solution of Ax = b')
str1 = sprintf('The matrix A has %8g rows and %8g cols', m, n);
str2 = sprintf('damp = %20.14e wantvar = %8g', damp,wantvar);
str3 = sprintf('atol = %8.2e conlim = %8.2e', atol, conlim);
str4 = sprintf('btol = %8.2e itnlim = %8g' , btol, itnlim);
disp(str1); disp(str2); disp(str3); disp(str4);
end
itn = 0; istop = 0; nstop = 0;
ctol = 0; if conlim > 0, ctol = 1/conlim; end;
anorm = 0; acond = 0;
dampsq = damp^2; ddnorm = 0; res2 = 0;
xnorm = 0; xxnorm = 0; z = 0;
cs2 = -1; sn2 = 0;
% Set up the first vectors u and v for the bidiagonalization.
% These satisfy beta*u = b, alfa*v = A'u.
u = b(1:m); x = zeros(n,1);
alfa = 0; beta = norm( u );
if beta > 0
u = (1/beta) * u; v = Aprod(u,2);
alfa = norm( v );
end
if alfa > 0
v = (1/alfa) * v; w = v;
end
arnorm = alfa * beta;
if arnorm == 0
if show, disp(msg(1,:)); end
return
end
arnorm0= arnorm;
rhobar = alfa; phibar = beta; bnorm = beta;
rnorm = beta;
r1norm = rnorm;
r2norm = rnorm;
head1 = ' Itn x(1) r1norm r2norm ';
head2 = ' Compatible LS Norm A Cond A';
if show
disp(' ')
disp([head1 head2])
test1 = 1; test2 = alfa / beta;
str1 = sprintf( '%6g %12.5e', itn, x(1) );
str2 = sprintf( ' %10.3e %10.3e', r1norm, r2norm );
str3 = sprintf( ' %8.1e %8.1e', test1, test2 );
disp([str1 str2 str3])
end
%------------------------------------------------------------------
% Main iteration loop.
%------------------------------------------------------------------
while itn < itnlim
itn = itn + 1;
% Perform the next step of the bidiagonalization to obtain the
% next beta, u, alfa, v. These satisfy the relations
% beta*u = a*v - alfa*u,
% alfa*v = A'*u - beta*v.
u = Aprod(v,1) - alfa*u;
beta = norm( u );
if beta > 0
u = (1/beta) * u;
anorm = norm([anorm alfa beta damp]);
v = Aprod(u, 2) - beta*v;
alfa = norm( v );
if alfa > 0, v = (1/alfa) * v; end
end
% Use a plane rotation to eliminate the damping parameter.
% This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
rhobar1 = norm([rhobar damp]);
cs1 = rhobar / rhobar1;
sn1 = damp / rhobar1;
psi = sn1 * phibar;
phibar = cs1 * phibar;
% Use a plane rotation to eliminate the subdiagonal element (beta)
% of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
rho = norm([rhobar1 beta]);
cs = rhobar1/ rho;
sn = beta / rho;
theta = sn * alfa;
rhobar = - cs * alfa;
phi = cs * phibar;
phibar = sn * phibar;
tau = sn * phi;
% Update x and w.
t1 = phi /rho;
t2 = - theta/rho;
dk = (1/rho)*w;
x = x + t1*w;
w = v + t2*w;
ddnorm = ddnorm + norm(dk)^2;
if wantvar, var = var + dk.*dk; end
% Use a plane rotation on the right to eliminate the
% super-diagonal element (theta) of the upper-bidiagonal matrix.
% Then use the result to estimate norm(x).
delta = sn2 * rho;
gambar = - cs2 * rho;
rhs = phi - delta * z;
zbar = rhs / gambar;
xnorm = sqrt(xxnorm + zbar^2);
gamma = norm([gambar theta]);
cs2 = gambar / gamma;
sn2 = theta / gamma;
z = rhs / gamma;
xxnorm = xxnorm + z^2;
% Test for convergence.
% First, estimate the condition of the matrix Abar,
% and the norms of rbar and Abar'rbar.
acond = anorm * sqrt( ddnorm );
res1 = phibar^2;
res2 = res2 + psi^2;
rnorm = sqrt( res1 + res2 );
arnorm = alfa * abs( tau );
% 07 Aug 2002:
% Distinguish between
% r1norm = ||b - Ax|| and
% r2norm = rnorm in current code
% = sqrt(r1norm^2 + damp^2*||x||^2).
% Estimate r1norm from
% r1norm = sqrt(r2norm^2 - damp^2*||x||^2).
% Although there is cancellation, it might be accurate enough.
r1sq = rnorm^2 - dampsq * xxnorm;
r1norm = sqrt( abs(r1sq) ); if r1sq < 0, r1norm = - r1norm; end
r2norm = rnorm;
% Now use these norms to estimate certain other quantities,
% some of which will be small near a solution.
test1 = rnorm / bnorm;
test2 = arnorm / arnorm0;
% test2 = arnorm/( anorm * rnorm );
test3 = 1 / acond;
t1 = test1 / (1 + anorm * xnorm / bnorm);
rtol = btol + atol * anorm * xnorm / bnorm;
% The following tests guard against extremely small values of
% atol, btol or ctol. (The user may have set any or all of
% the parameters atol, btol, conlim to 0.)
% The effect is equivalent to the normal tests using
% atol = eps, btol = eps, conlim = 1/eps.
if itn >= itnlim, istop = 7; end
if 1 + test3 <= 1, istop = 6; end
if 1 + test2 <= 1, istop = 5; end
if 1 + t1 <= 1, istop = 4; end
% Allow for tolerances set by the user.
if test3 <= ctol, istop = 3; end
if test2 <= atol, istop = 2; end
% if test1 <= rtol, istop = 1; end
% See if it is time to print something.
prnt = 0;
if n <= 40 , prnt = 1; end
if itn <= 10 , prnt = 1; end
if itn >= itnlim-10, prnt = 1; end
if rem(itn,10) == 0 , prnt = 1; end
if test3 <= 2*ctol , prnt = 1; end
if test2 <= 10*atol , prnt = 1; end
% if test1 <= 10*rtol , prnt = 1; end
if istop ~= 0 , prnt = 1; end
if prnt == 1
if show
str1 = sprintf( '%6g %12.5e', itn, x(1) );
str2 = sprintf( ' %10.3e %10.3e', r1norm, r2norm );
str3 = sprintf( ' %8.1e %8.1e', test1, test2 );
str4 = sprintf( ' %8.1e %8.1e', anorm, acond );
disp([str1 str2 str3 str4])
end
end
if istop > 0, break, end
end
% End of iteration loop.
% Print the stopping condition.
if show
disp(' ')
disp('LSQR finished')
disp(msg(istop+1,:))
disp(' ')
str1 = sprintf( 'istop =%8g r1norm =%8.1e', istop, r1norm );
str2 = sprintf( 'anorm =%8.1e arnorm =%8.1e', anorm, arnorm );
str3 = sprintf( 'itn =%8g r2norm =%8.1e', itn, r2norm );
str4 = sprintf( 'acond =%8.1e xnorm =%8.1e', acond, xnorm );
disp([str1 ' ' str2])
disp([str3 ' ' str4])
disp(' ')
end
%-----------------------------------------------------------------------
% End of lsqr.m
%-----------------------------------------------------------------------
function z = Aprod(x,mode)
if mode == 1
if isnumeric(A), z = A*x;
else z = A(x,1);
end
else
if isnumeric(A), z = (x'*A)';
else z = A(x,2);
end
end
end % function Aprod
end
|
github
|
lijunzh/fd_elastic-master
|
wfb2rec.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/wfb2rec.m
| 1,419 |
utf_8
|
a8eb98892d022925b472758e34d4640d
|
function x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g)
% WFB2REC 2-D Wavelet Filter Bank Decomposition
%
% x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g)
%
% Input:
% x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands
% h, g: lowpass analysis and synthesis wavelet filters
%
% Output:
% x: reconstructed image
% Make sure filter in a row vector
h = h(:)';
g = g(:)';
g0 = g;
len_g0 = length(g0);
ext_g0 = floor((len_g0 - 1) / 2);
% Highpass synthesis filter: G1(z) = -z H0(-z)
len_g1 = length(h);
c = floor((len_g1 + 1) / 2);
g1 = (-1) * h .* (-1) .^ ([1:len_g1] - c);
ext_g1 = len_g1 - (c + 1);
% Get the output image size
[height, width] = size(x_LL);
x_B = zeros(height * 2, width);
x_B(1:2:end, :) = x_LL;
% Column-wise filtering
x_L = rowfiltering(x_B', g0, ext_g0)';
x_B(1:2:end, :) = x_LH;
x_L = x_L + rowfiltering(x_B', g1, ext_g1)';
x_B(1:2:end, :) = x_HL;
x_H = rowfiltering(x_B', g0, ext_g0)';
x_B(1:2:end, :) = x_HH;
x_H = x_H + rowfiltering(x_B', g1, ext_g1)';
% Row-wise filtering
x_B = zeros(2*height, 2*width);
x_B(:, 1:2:end) = x_L;
x = rowfiltering(x_B, g0, ext_g0);
x_B(:, 1:2:end) = x_H;
x = x + rowfiltering(x_B, g1, ext_g1);
% Internal function: Row-wise filtering with border handling
function y = rowfiltering(x, f, ext1)
ext2 = length(f) - ext1 - 1;
x = [x(:, end-ext1+1:end) x x(:, 1:ext2)];
y = conv2(x, f, 'valid');
|
github
|
lijunzh/fd_elastic-master
|
wfb2dec.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/wfb2dec.m
| 1,359 |
utf_8
|
cf0a7abcc9abae631039550460b07a48
|
function [x_LL, x_LH, x_HL, x_HH] = wfb2dec(x, h, g)
% WFB2DEC 2-D Wavelet Filter Bank Decomposition
%
% y = wfb2dec(x, h, g)
%
% Input:
% x: input image
% h, g: lowpass analysis and synthesis wavelet filters
%
% Output:
% x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands
% Make sure filter in a row vector
h = h(:)';
g = g(:)';
h0 = h;
len_h0 = length(h0);
ext_h0 = floor(len_h0 / 2);
% Highpass analysis filter: H1(z) = -z^(-1) G0(-z)
len_h1 = length(g);
c = floor((len_h1 + 1) / 2);
% Shift the center of the filter by 1 if its length is even.
if mod(len_h1, 2) == 0
c = c + 1;
end
h1 = - g .* (-1).^([1:len_h1] - c);
ext_h1 = len_h1 - c + 1;
% Row-wise filtering
x_L = rowfiltering(x, h0, ext_h0);
x_L = x_L(:, 1:2:end);
x_H = rowfiltering(x, h1, ext_h1);
x_H = x_H(:, 1:2:end);
% Column-wise filtering
x_LL = rowfiltering(x_L', h0, ext_h0)';
x_LL = x_LL(1:2:end, :);
x_LH = rowfiltering(x_L', h1, ext_h1)';
x_LH = x_LH(1:2:end, :);
x_HL = rowfiltering(x_H', h0, ext_h0)';
x_HL = x_HL(1:2:end, :);
x_HH = rowfiltering(x_H', h1, ext_h1)';
x_HH = x_HH(1:2:end, :);
% Internal function: Row-wise filtering with border handling
function y = rowfiltering(x, f, ext1)
ext2 = length(f) - ext1 - 1;
x = [x(:, end-ext1+1:end) x x(:, 1:ext2)];
y = conv2(x, f, 'valid');
|
github
|
lijunzh/fd_elastic-master
|
extend2.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/extend2.m
| 1,861 |
utf_8
|
40bc6d67909280efd214bb2536a4a46f
|
function y = extend2(x, ru, rd, cl, cr, extmod)
% EXTEND2 2D extension
%
% y = extend2(x, ru, rd, cl, cr, extmod)
%
% Input:
% x: input image
% ru, rd: amount of extension, up and down, for rows
% cl, cr: amount of extension, left and rigth, for column
% extmod: extension mode. The valid modes are:
% 'per': periodized extension (both direction)
% 'qper_row': quincunx periodized extension in row
% 'qper_col': quincunx periodized extension in column
%
% Output:
% y: extended image
%
% Note:
% Extension modes 'qper_row' and 'qper_col' are used multilevel
% quincunx filter banks, assuming the original image is periodic in
% both directions. For example:
% [y0, y1] = fbdec(x, h0, h1, 'q', '1r', 'per');
% [y00, y01] = fbdec(y0, h0, h1, 'q', '2c', 'qper_col');
% [y10, y11] = fbdec(y1, h0, h1, 'q', '2c', 'qper_col');
%
% See also: FBDEC
[rx, cx] = size(x);
switch extmod
case 'per'
I = getPerIndices(rx, ru, rd);
y = x(I, :);
I = getPerIndices(cx, cl, cr);
y = y(:, I);
case 'qper_row'
rx2 = round(rx / 2);
y = [[x(rx2+1:rx, cx-cl+1:cx); x(1:rx2, cx-cl+1:cx)], x, ...
[x(rx2+1:rx, 1:cr); x(1:rx2, 1:cr)]];
I = getPerIndices(rx, ru, rd);
y = y(I, :);
case 'qper_col'
cx2 = round(cx / 2);
y = [x(rx-ru+1:rx, cx2+1:cx), x(rx-ru+1:rx, 1:cx2); x; ...
x(1:rd, cx2+1:cx), x(1:rd, 1:cx2)];
I = getPerIndices(cx, cl, cr);
y = y(:, I);
otherwise
error('Invalid input for EXTMOD')
end
%----------------------------------------------------------------------------%
% Internal Function(s)
%----------------------------------------------------------------------------%
function I = getPerIndices(lx, lb, le)
I = [lx-lb+1:lx , 1:lx , 1:le];
if (lx < lb) | (lx < le)
I = mod(I, lx);
I(I==0) = lx;
end
|
github
|
lijunzh/fd_elastic-master
|
Meyer_sf_vkbook.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/Meyer_sf_vkbook.m
| 664 |
utf_8
|
c34c2143df4bcd9c3d5d9f2588e4550d
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Meyer_sf_vkbook.m
%
% First Created: 08-26-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function theta = Meyer_sf_vkbook(x)
% The smooth passband function for constructing Meyer filters
% See the following book for details:
% M. Vetterli and J. Kovacevic, Wavelets and Subband Coding, Prentice
% Hall, 1995.
theta = 3 * x .^ 2 - 2 * x .^ 3;
theta(x <= 0) = 0;
theta(x >= 1) = 1;
|
github
|
lijunzh/fd_elastic-master
|
rcos.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/rcos.m
| 476 |
utf_8
|
e62db4d444bbc10be5c8478b7b671042
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% rcos.m
%
% First Created: 08-26-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function theta = rcos(x)
% The raised cosine function
theta = 0.5 * (1 - cos(pi*x));
theta(x <= 0) = 0;
theta(x >= 1) = 1;
|
github
|
lijunzh/fd_elastic-master
|
PyrNDDec_mm.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/PyrNDDec_mm.m
| 3,663 |
utf_8
|
2f1cda7f9c0e6816ff309802f6040e9e
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PyrNDDec_mm.m
%
% First Created: 10-11-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function subs = PyrNDDec_mm(X, OutD, L, Pyr_mode, smooth_func)
% N-dimensional multiscale pyramid decomposition - with multiple modes
%
% INPUT:
%
% X: input signal in the spatial domain
%
% OutD: "S", then the output subbands are given in the spatial domain.
% "F", then the output subbands are given in the frequency domain.
% This option can be used to get rid of the unnecessary (and
% time-consuming) "ifftn-fftn" operations in the middle steps.
% L: level of decomposition
%
% Pyr_mode: Decomposition modes, including the following options.
% 1: do not downsample the lowpass subband at the first level
% of decomposition
% 1.5: downsampling the first lowpass subbabnd by a factor of
% 1.5 along each dimension
% 2: use a lowpass filter with 1/3 pi cutoff frequency at the
% first level of decomposition.
%
% smooth_func: function handle to generate the filter for the pyramid
% decomposition
%
% OUTPUT:
%
% subs: an L+1 by 1 cell array storing subbands from the coarsest (i.e.
% lowpass) to the finest scales.
%
% See also:
%
% PyrNDRec_mm.m
OutD = upper(OutD);
% The dimensionality of the input signal
N = ndims(X);
switch Pyr_mode
case {1}
% the cutoff frequencies at each scale
w_array = [0.25 * ones(1, L - 1) 0.5];
% the transition bandwidths at each scale
tbw_array = [1/12 * ones(1, L - 1) 1/6];
% the downsampling factor at each scale
% no downsampling at the finest scale
D_array = [2 * ones(1, L - 1) 1];
case {1.5}
% the cutoff frequencies at each scale
w_array = [3/8 * ones(1, L - 1) 0.5];
% the transition bandwidths at each scale
tbw_array = [1/9 * ones(1, L - 1) 1/7];
% the downsampling factor at each scale
% the lowpass channel at the first level of decomposition is
% downsampled by a factor of 1.5 along each dimension.
D_array = [2 * ones(1, L - 1) 1.5];
case {2}
% the cutoff frequencies at each scale
w_array = 1 / 3 * ones(1, L);
% the transition bandwidths at each scale
tbw_array = 1 / 7 * ones(1, L);
% the downsampling factor at each scale
D_array = 2 * ones(1, L);
otherwise
error('Unsupported Pyr mode.');
end
X = fftn(X);
% We assume real-valued input signal X. Half of its Fourier
% coefficients can be removed due to conjugate symmetry.
X = ccsym(X, N, 'c');
subs = cell(L+1, 1);
for n = L : -1: 1
% One level of the pyramid decomposition
[Lp, Hp] = PrySDdec_onestep(X, w_array(n), tbw_array(n), D_array(n), smooth_func);
X = Lp;
Hp = ccsym(Hp, N, 'e');
if OutD == 'S'
% Go back to the spatial domain
subs{n+1} = real(ifftn(Hp));
else
% Retain the frequency domain results
subs{n+1} = Hp;
end
clear Lp Hp;
end
X = ccsym(X, N, 'e');
if OutD == 'S'
subs{1} = real(ifftn(X));
else
subs{1} = X;
end
|
github
|
lijunzh/fd_elastic-master
|
PyrNDRec_mm.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/PyrNDRec_mm.m
| 3,341 |
utf_8
|
626e7e143d4a6d7138676e79f47b8b04
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PyrNDRec_mm.m
%
% First Created: 10-11-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rec = PyrNDRec_mm(subs, InD, Pyr_mode, smooth_func)
% N-dimensional multiscale pyramid reconstruction - with multiple modes
%
% INPUT:
%
% subs: an L+1 by 1 cell array storing subbands from the coarsest scale
% to the coarsest scale. subs{1} contains the lowpass subband.
%
% InD: "S", then the output subbands are given in the spatial domain.
% "F", then the output subbands are given in the frequency domain.
% This option can be used to get rid of the unnecessary (and
% time-consuming) "ifftn-fftn" operations in the middle steps.
%
% Pyr_mode: Decomposition modes, including the following options.
% 1: do not downsample the lowpass subband at the first level
% of decomposition
% 1.5: downsampling the first lowpass subbabnd by a factor of
% 1.5 along each dimension
% 2: use a lowpass filter with 1/3 pi cutoff frequency at the
% first level of decomposition.
%
% smooth_func: function handle to generate the filter for the pyramid
% decomposition
%
% OUTPUT:
%
% rec: the reconstructed signal in the spatial domain
%
% See also:
%
% PyrNDRec_mm.m
InD = upper(InD);
N = ndims(subs{1});
L = length(subs) - 1;
switch Pyr_mode
case {1}
% the cutoff frequencies at each scale
w_array = [0.25 * ones(1, L - 1) 0.5];
% the transition bandwidths at each scale
tbw_array = [1/12 * ones(1, L - 1) 1/6];
% the downsampling factor at each scale
% no downsampling at the finest scale
D_array = [2 * ones(1, L - 1) 1];
case {1.5}
% the cutoff frequencies at each scale
w_array = [3/8 * ones(1, L - 1) 0.5];
% the transition bandwidths at each scale
tbw_array = [1/9 * ones(1, L - 1) 1/7];
% the downsampling factor at each scale
% the lowpass channel at the first level of decomposition is
% downsampled by a factor of 1.5 along each dimension.
D_array = [2 * ones(1, L - 1) 1.5];
case {2}
% the cutoff frequencies at each scale
w_array = 1 / 3 * ones(1, L);
% the transition bandwidths at each scale
tbw_array = 1 / 7 * ones(1, L);
% the downsampling factor at each scale
D_array = 2 * ones(1, L);
otherwise
error('Unsupported Pyr mode.');
end
Lp = subs{1};
subs{1} = [];
if InD == 'S'
Lp = fftn(Lp);
end
Lp = ccsym(Lp, N, 'c');
for n = 1 : L
Hp = subs{n+1};
subs{n+1} = [];
if InD == 'S'
Hp = fftn(Hp);
end
Hp = ccsym(Hp, N, 'c');
Lp = PrySDrec_onestep(Lp, Hp, w_array(n), tbw_array(n), D_array(n), smooth_func);
end
clear Hp
Lp = ccsym(Lp, N, 'e');
rec = real(ifftn(Lp));
|
github
|
lijunzh/fd_elastic-master
|
PSNR.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/PSNR.m
| 448 |
utf_8
|
e453f5dc8f9837e471e9bcab2c65c239
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PSNR.m
%
% First Created: 09-23-06
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PSNRdb = PSNR(x, y)
err = x - y;
err = err(:);
PSNRdb = 20 * log10(255/sqrt(mean(err .^2)));
|
github
|
lijunzh/fd_elastic-master
|
ccsym.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/ccsym.m
| 1,229 |
utf_8
|
466eff5ba10dd1882486bc8bb8b773fc
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ccsym.m
%
% First created: 08-14-05
% Last modified: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = ccsym(x, k, type)
% Exploit the complex conjugate symmetry in the fourier transform of
% real-valued signals
%
% INPUT
%
% x: the input signal
%
% type: 'c' compaction 'e' expansion
%
% k: along which dimension
%
% OUTPUT
%
% y: the compacted (or expanded) signal in the frequency domain
% Dimensions of the problem
N = ndims(x);
szX = size(x);
if type == 'c'
% initialize the subscript array
sub_array = repmat({':'}, [N, 1]);
sub_array{k} = 1 : szX(k) / 2 + 1;
y = x(sub_array{:});
else
% subscript mapping for complex conjugate symmetric signal recovery
szX(k) = (szX(k)-1) * 2;
sub_conj = cell(N, 1);
for m = 1 : N
sub_conj{m} = [1 szX(m):-1:2];
end
sub_conj{k} = [szX(k)/2 : -1 : 2];
% recover the full signal
y = cat(k, x, conj(x(sub_conj{:})));
end
|
github
|
lijunzh/fd_elastic-master
|
ContourletSDDec.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/ContourletSDDec.m
| 2,103 |
utf_8
|
ca02dc7beab42188367dfff90105a5fe
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContourletSDDec.m
%
% First Created: 10-13-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = ContourletSDDec(x, nlevs, Pyr_mode, smooth_func, dfilt)
% ContourletSD Decomposition
%
% INPUT
%
% x: the input image.
%
% nlevs: vector of numbers of directional filter bank decomposition
% levels at each pyramidal level (from coarse to fine scale).
%
% Pyr_mode: Decomposition modes, including the following options.
% 1: do not downsample the lowpass subband at the first level
% of decomposition
% 1.5: downsampling the first lowpass subbabnd by a factor of
% 1.5 along each dimension
% 2: use a lowpass filter with 1/3 pi cutoff frequency at the
% first level of decomposition.
%
% smooth_func: function handle to generate the filter for the pyramid
% decomposition
%
% dfilt: filter name for the directional decomposition step
%
% OUTPUT
%
% y: a cell vector of length length(nlevs) + 1, where except y{1} is
% the lowpass subband, each cell corresponds to one pyramidal
% level and is a cell vector that contains bandpass directional
% subbands from the DFB at that level.
%
% See also:
%
% ContourletSDRec.m
L = length(nlevs);
y = PyrNDDec_mm(x, 'S', L, Pyr_mode, smooth_func);
for k = 2 : L+1
% DFB on the bandpass image
switch dfilt % Decide the method based on the filter name
case {'pkva6', 'pkva8', 'pkva12', 'pkva'}
% Use the ladder structure (whihc is much more efficient)
y{k} = dfbdec_l(y{k}, dfilt, nlevs(k-1));
otherwise
% General case
y{k} = dfbdec(y{k}, dfilt, nlevs(k-1));
end
end
|
github
|
lijunzh/fd_elastic-master
|
PrySDdec_onestep.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/PrySDdec_onestep.m
| 3,399 |
utf_8
|
6c4ba7db35e6e5fc98bf07e16f46ddb7
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PrySDdec_onestep.m
%
% First Created: 10-11-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Lp, Hp] = PrySDdec_onestep(X, w, tbw, D, smooth_func)
% N-dimensional multiscale pyramid decomposition - One Step
%
% INPUT:
%
% X: input signal in the Fourier domain. Note: Since the signal is
% real-vaued in the spatial domain, we remove the symmetric part of
% X along the last dimension to save computation time. This is
% important when X is a large 3-D array. See ccsym.m for details.
%
% w: The ideal cutoff frequency of the lowpass subband. w is specified
% as a fraction of PI, e.g. 0.5, 1/3, ....
%
% tbw: Width of the transition band, specified as a fraction of PI.
%
% D: downsampling factor. For example, 1, 1.5, 2, ......
% Note: D should divide the size of the FFT array.
%
% smooth_func: function handle to generate the smooth passband theta
% function
%
% OUTPUT:
%
% Lp: the lowpass subband in the Fourier domain with the symmetric part
% removed along the last dimension.
%
% Hp: the highpass subband in the Fourier domain with the symmetric part
% removed along the last dimension.
%
% See also:
%
% PyrSDrec_onestep.m, PyrNDDec_mm.m, PyrNDRec_mm.m
%% The dimension of the problem
N = ndims(X);
szX = size(X);
%% the original full size
szF = szX;
szF(end) = (szX(end) - 1) * 2;
%% Passband index arrays
pbd_array = cell(N, 1);
%% Lowpass filter (nonzero part)
szLf = 2 * ceil(szF / 2 * (w + tbw)) + 1;
szLf(end) = (szLf(end) + 1) / 2;
Lf = ones(szLf);
szR = ones(1, N); % for resizing
for n = 1 : N
%% current Fourier domain resolution
nr = szF(n);
szR(n) = szLf(n);
%% passband
pbd = [0 : ceil(nr / 2 * (w + tbw))] .';
%% passband value
pbd_value = realsqrt(smooth_func((pbd(end) - pbd) ./ (ceil(nr / 2 * (w + tbw)) ...
- floor(nr / 2 * (w - tbw)))));
%% See if we need to consider the symmetric part
if n ~= N
pbd = [pbd ; [nr - pbd(end) : nr - 1].'];
pbd_value = [pbd_value ; flipud(pbd_value(2:end))];
end
pbd_array{n} = pbd + 1;
pbd_value = reshape(pbd_value, szR);
Lf = Lf .* repmat(pbd_value, szLf ./ szR);
szR(n) = 1;
end
%% Get the lowpass subband
szLp = szF ./ D;
if any(fix(szLp) ~= szLp)
error('The downsampling factor must be able to divide the size of the FFT matrix!');
end
szLp(end) = szLp(end) / 2 + 1;
pbd_array_sml = pbd_array;
for n = 1 : N - 1
pbd = pbd_array{n};
pbd((length(pbd) + 3) / 2 : end) = pbd((length(pbd) + 3) / 2 : end) ...
+ szLp(n) - szX(n);
pbd_array_sml{n} = pbd;
end
Lp = repmat(complex(0), szLp);
Lp(pbd_array_sml{:}) = (Lf ./ D^(N/2)) .* X(pbd_array{:});
%% Get the highpass subband
Hp = X;
Hp(pbd_array{:}) = realsqrt(1 - realpow(Lf, 2)) .* X(pbd_array{:});
% Lf = ccsym(Lf, N, 'e');
% a = sum(realpow(Lf(:), 2));
% Lp = Lp ./ sqrt(a * prod(szF) / prod(szF./D)^2) * D^(N/2);
% Hp = Hp ./ sqrt(1 - a/prod(szF));
|
github
|
lijunzh/fd_elastic-master
|
ContourletSDRec.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/ContourletSDRec.m
| 1,936 |
utf_8
|
dff2ea8a87a784ea1c51d735fd9d59ab
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ContourletSDRec.m
%
% First Created: 10-13-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = ContourletSDRec(y, Pyr_mode, smooth_func, dfilt)
% ContourletSD Reconstruction
%
% INPUT
%
% y: a cell vector of length length(nlevs) + 1, where except y{1} is
% the lowpass subband, each cell corresponds to one pyramidal
% level and is a cell vector that contains bandpass directional
% subbands from the DFB at that level.
%
% Pyr_mode: Decomposition modes, including the following options.
% 1: do not downsample the lowpass subband at the first level
% of decomposition
% 1.5: downsampling the first lowpass subbabnd by a factor of
% 1.5 along each dimension
% 2: use a lowpass filter with 1/3 pi cutoff frequency at the
% first level of decomposition.
%
% smooth_func: function handle to generate the filter for the pyramid
% decomposition
%
% dfilt: filter name for the directional decomposition step
%
% OUTPUT
%
% x: the reconstructed image
%
% See also:
%
% ContourletSDDec.m
L = length(y) - 1;
for k = 2 : L+1
% Reconstruct the bandpass image from DFB
% Decide the method based on the filter name
switch dfilt
case {'pkva6', 'pkva8', 'pkva12', 'pkva'}
% Use the ladder structure (much more efficient)
y{k} = dfbrec_l(y{k}, dfilt);
otherwise
% General case
y{k} = dfbrec(y{k}, dfilt);
end
end
x = PyrNDRec_mm(y, 'S', Pyr_mode, smooth_func);
|
github
|
lijunzh/fd_elastic-master
|
PrySDrec_onestep.m
|
.m
|
fd_elastic-master/src/contourlet_toolbox/contourlet_sfl/PrySDrec_onestep.m
| 3,291 |
utf_8
|
177fd547ae5154f355724cff80c2656a
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Yue M. Lu and Minh N. Do
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PrySDrec_onestep.m
%
% First Created: 10-11-05
% Last Revision: 07-13-09
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function rec = PrySDrec_onestep(Lp, Hp, w, tbw, D, smooth_func)
% N-dimensional multiscale pyramid reconstruction - One Step
%
% INPUT:
%
% Lp: the lowpass subband in the Fourier domain with the symmetric part
% removed along the last dimension.
%
% Hp: the highpass subband in the Fourier domain with the symmetric part
% removed along the last dimension.
%
% w: The ideal cutoff frequency of the lowpass subband. w is specified as a
% fraction of PI, e.g. 0.5, 1/3, ....
%
% tbw: Width of the transition band, specified as a fraction of PI.
%
% D: downsampling factor. For example, 1, 1.5, 2, ......
% Note: D should divide the size of the FFT array.
%
% smooth_func: function handle to generate the smooth passband theta
% function
%
% OUTPUT:
%
% rec: the reconstructed signal in the Fourier domain. Note: Since the
% signal is real-vaued in the spatial domain, we remove the
% symmetric part of rec along the last dimension to save
% computation time. This is important when rec is a large 3-D
% array. See ccsym.m for details.
%
% See also:
%
% PyrSDdec_onestep.m, PyrNDDec_mm.m, PyrNDRec_mm.m
%% The dimension of the problem
N = ndims(Hp);
szX = size(Hp);
%% the original full size
szF = szX;
szF(end) = (szX(end) - 1) * 2;
%% Passband index arrays
pbd_array = cell(N, 1);
%% Lowpass filter (nonzero part)
szLf = 2 * ceil(szF / 2 * (w + tbw)) + 1;
szLf(end) = (szLf(end) + 1) / 2;
Lf = ones(szLf);
szR = ones(1, N); %% for resizing
for n = 1 : N
%% current Fourier domain resolution
nr = szF(n);
szR(n) = szLf(n);
%% passband
pbd = [0 : ceil(nr / 2 * (w + tbw))] .';
%% passband value
pbd_value = realsqrt(smooth_func((pbd(end) - pbd) ./ (ceil(nr / 2 * (w + tbw)) ...
- floor(nr / 2 * (w - tbw)))));
%% See if we need to consider the symmetric part
if n ~= N
pbd = [pbd ; [nr - pbd(end) : nr - 1].'];
pbd_value = [pbd_value ; flipud(pbd_value(2:end))];
end
pbd_array{n} = pbd + 1;
pbd_value = reshape(pbd_value, szR);
Lf = Lf .* repmat(pbd_value, szLf ./ szR);
szR(n) = 1;
end
%% Get the reconstruction
rec = Hp;
clear Hp;
rec(pbd_array{:}) = realsqrt(1 - realpow(Lf, 2)) .* rec(pbd_array{:});
%% Get the lowpass subband
szLp = szF ./ D;
if any(fix(szLp ~= szLp))
error('The downsampling factor must be able to divide the size of the FFT matrix!');
end
szLp(end) = szLp(end) / 2 + 1;
pbd_array_sml = pbd_array;
for n = 1 : N - 1
pbd = pbd_array{n};
pbd((length(pbd) + 3) / 2 : end) = pbd((length(pbd) + 3) / 2 : end) ...
+ szLp(n) - szX(n);
pbd_array_sml{n} = pbd;
end
rec(pbd_array{:}) = rec(pbd_array{:}) + Lp(pbd_array_sml{:}) .* (Lf .* D^(N/2));
|
github
|
lijunzh/fd_elastic-master
|
dynamicimage.m
|
.m
|
fd_elastic-master/src/deblocking_filter/dynamicimage.m
| 3,024 |
utf_8
|
f1ac482da624a445cd56661d94ef410f
|
function ttbin=dynamicimage(stackeddataM2int,nrpixels,imag_col)
if nargin==1
%nrpixels=16;
nrpixels=30;
%nrpixels = 64;
%nrpixels=128;
%imag_col=255;
imag_col = 255;
end
if nargin==2
imag_col=64;
end
sc=size(stackeddataM2int,2);
begin_im=zeros(1,sc);end_im=zeros(1,sc);
for s=1:sc
begin_im(s)=find(isnan(stackeddataM2int(:,s))==0,1,'first');
end_im(s)=find(isnan(stackeddataM2int(:,s))==0,1,'last');
end
if isempty(begin_im);startdepthbin=1;end
if isempty(end_im);enddepthbin=size(stackeddataM2int,1);end
startdepthbin=min(begin_im);
enddepthbin=max(end_im);
W=nrpixels;
Ltot=enddepthbin-startdepthbin+1;
j=0;clear lvlsM2 pixnr;pixnr=zeros(1,floor(Ltot/W-1));
for i=startdepthbin:W:enddepthbin
j=j+1;E=min(i+W-1,enddepthbin);pixnr(j)=round(i+W/2);
lvlsM2dyn(1:imag_col,j)=colorbinlevels(stackeddataM2int(i:E,1:sc),imag_col,sc);
end
y=zeros(imag_col,length(stackeddataM2int));
for i=1:imag_col
y(i,1:pixnr(1))=lvlsM2dyn(i,1);
y(i,pixnr(end):enddepthbin)=lvlsM2dyn(i,end);
if length(pixnr)>1
y(i,pixnr(1):pixnr(end))=interp1(pixnr,lvlsM2dyn(i,:),pixnr(1):pixnr(end),'linear');
end
end
x=stackeddataM2int;
clrs=y;
% %%%%%%%%%%%%%%make 64 step histogram data for coloring
startdpt=1;
[enddpt dummy]=size(x);
[nrclrs dummy]=size(clrs);
ttbin=zeros(enddpt-startdpt+1,sc,'int16');
for i=1:sc
for j=startdpt:enddpt
for k=nrclrs-1:-1:1
if x(j,i)>clrs(k,j) %-1e-3 %if I use x=>clrs, it does not work properly
ttbin(j,i)=k;
break
end
end
end
end
[a b]=find(x==Inf);
for i=1:length(a);ttbin(a(i),b(i))=nrclrs;end
%[a b]=find(x==0);
%for i=1:length(a);ttbin(a(i),b(i))=nrclrs;end
[a2 b2]=find(isnan(x));
for i=1:length(a2);ttbin(a2(i),b2(i))=nrclrs;end
%if length(a)==0 & length(a2)==0;ttbin(end,end)=nrclrs;end
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ttbinlevels=colorbinlevels(x,ncolors,sc)
% %%%%%%%%%%%%%%make step histogram data for coloring
startdpt=1;
[enddpt dummy]=size(x);
dptlong=zeros(sc*(enddpt-startdpt+1)-length(find(x==Inf))-length(find(isnan(x)))-length(find(x==0)),1);
m=0;
% drop all zeros and Nan and Inf's from the array
for i=1:sc
for j=startdpt:enddpt
if x(j,i)~=Inf & isnan(x(j,i))~=1 & x(j,i)~=0;
m=m+1;
dptlong(m)=x(j,i);
end
end
end
sizel=m;
i=m;
remove_val=zeros(1,m);l=0;
while i>1
if dptlong(i-1)==dptlong(i)
l=l+1;
remove_val(l)=i;
end
i=i-1;
end
remove_val(l+1:end)=[];
dptlong(remove_val)=[];
sizel=length(dptlong);
%sort the resulting values and find the values where the color needs to
%change
% if sizel~=0
if sizel>ncolors
sortdptlong=sortrows(dptlong,1);
for i=1:ncolors
clrs(i)=sortdptlong(round(i*sizel/ncolors));
end
ttbinlevels=clrs;
else
ttbinlevels(1:ncolors)=-1;
end
end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
lijunzh/fd_elastic-master
|
example_PQN_Lasso_Complex.m
|
.m
|
fd_elastic-master/src/PQN/example_PQN_Lasso_Complex.m
| 1,568 |
utf_8
|
e16a33e8a000fd7b25dbc0b78fce3c6d
|
function example_PQN_Lasso_Complex
% solve min_x ||R*fft(x)-b||^2 s.t. ||x||_1 <= tau
close all;
clear;
clc;
addpath(genpath('./'));
m = 128;
n = 512;
R = randn(m, n) + 1j * randn(m, n);
R = R / sqrt(m);
x = 10 * randn(n,1).*(rand(n,1) > 0.9);
X = 1/sqrt(n) * fft(x, n);
F = 1/sqrt(n) * fft(eye(n, n));
b = R * X;
tau = norm(x, 1);
%% SPGL1
xL1_spgLasso = spg_lasso(R * F, b, tau);
%% minConF
options.verbose = 2;
options.optTol = 1e-8;
options.SPGoptTol = 1e-25;
options.adjustStep = 1;
options.bbInit = 1;
options.maxIter = 2000;
func = @(zRealImag) misfitFunc([real(R) -imag(R); imag(R) real(R)], zRealImag, [real(b); imag(b)]);
% L2-norm minimization with L1-norm regularization, i.e., LASSO
tau = norm(x, 1);
funProj = @(zRealImag) complexProject(zRealImag, tau);
% % L2-norm minimization without L1-norm regularization
% funProj = @(x) boundProject(x, [-inf(2*n, 1)], [inf(2*n, 1)]);
xL1_pqnRealImag = minConF_PQN_new(func, [zeros(n, 1); zeros(n, 1)], funProj, options);
xL1_pqn = xL1_pqnRealImag(1:n) + 1j*xL1_pqnRealImag(n+1:2*n);
end
function [value, grad] = misfitFunc(R, x, b)
n = length(x);
Xreal = 1/sqrt(n/2) * ( real(fft(x(1:n/2), n/2)) - imag(fft(x(n/2+1:n), n/2)) );
Ximag = 1/sqrt(n/2) * ( imag(fft(x(1:n/2), n/2)) + real(fft(x(n/2+1:n), n/2)) );
X = [Xreal; Ximag];
value = 1/2 * sum((R*X-b).^2);
grad = R'*(R*X-b);
gradReal = sqrt(n/2) * ( real(ifft(grad(1:n/2), n/2)) - imag(ifft(grad(n/2+1:n), n/2)) );
gradImag = sqrt(n/2) * ( imag(ifft(grad(1:n/2), n/2)) + real(ifft(grad(n/2+1:n), n/2)) );
grad = [gradReal; gradImag];
end
|
github
|
lijunzh/fd_elastic-master
|
prettyPlot.m
|
.m
|
fd_elastic-master/src/PQN/misc/prettyPlot.m
| 4,994 |
utf_8
|
b170f4e05629a1115ee65f9f364039b1
|
function [] = prettyPlot(xData,yData,legendStr,plotTitle,plotXlabel,plotYlabel,type,style,errors)
% prettyPlot(xData,yData,legendStr,plotTitle,plotXlabel,plotYlabel,type,style,errors)
%
% type 0: plot
% type 1: semilogx
%
% style -1: matlab style
% style 0: use line styles
% style 1: use markers
%
% Save as image:
% set(gcf, 'PaperPositionMode', 'auto');
% print -depsc2 finalPlot1.eps
if nargin < 7
type = 0;
end
if nargin < 8
style = 0;
end
if nargin < 9
errors = [];
end
if style == -1 % Matlab style
doLineStyle = 0;
doMarker = 0;
lineWidth = 1.5;
colors = getColorsRGB;
elseif style == 0 % Paper style (line styles)
doLineStyle = 1;
doMarker = 0;
lineWidth = 3;
colors = [.5 0 0
0 .5 0
0 0 .5
0 .5 .5
.5 .5 0];
else % Paper style (markers)
doLineStyle = 0;
doMarker = 1;
lineWidth = 3;
colors = [.5 0 0
0 .5 0
0 0 .5
0 .5 .5
.5 .5 0];
end
if type == 1
plotFunc = @semilogx;
else
plotFunc = @plot;
end
if isempty(xData)
for i = 1:length(yData)
h(i) = plotFunc(1:length(yData{i}),yData{i});
applyStyle(h(i),i,colors,doLineStyle,doMarker,lineWidth)
hold on;
end
elseif iscell(xData)
for i = 1:length(yData)
h(i) = plotFunc(xData{i}-xData{i}(1),yData{i});
applyStyle(h(i),i,colors,doLineStyle,doMarker,lineWidth)
hold on;
end
elseif iscell(yData)
for i = 1:length(yData)
if length(yData{i}) >= length(xData)
h(i) = plotFunc(xData,yData{i}(1:length(xData)));
else
if isscalar(yData{i})
h(i) = hline(yData{i},'-');
else
h(i) = plotFunc(xData(1:length(yData{i})),yData{i});
end
end
applyStyle(h(i),i,colors,doLineStyle,doMarker,lineWidth)
hold on;
end
else
for i = 1:size(yData,2)
h(i) = plotFunc(xData,yData(:,i));
applyStyle(h(i),i,colors,doLineStyle,doMarker,lineWidth)
hold on;
end
end
set(gca,'FontName','AvantGarde','FontWeight','normal','FontSize',12);
if ~isempty(legendStr)
h = legend(h,legendStr);
set(h,'FontSize',10,'FontWeight','normal');
set(h,'Location','NorthEast');
end
h = title(plotTitle);
set(h,'FontName','AvantGarde','FontSize',10,'FontWeight','bold');
h1 = xlabel(plotXlabel);
h2 = ylabel(plotYlabel);
set([h1 h2],'FontName','AvantGarde','FontSize',14,'FontWeight','normal');
set(gca, ...
'Box' , 'on' , ...
'TickDir' , 'out' , ...
'TickLength' , [.02 .02] , ...
'XMinorTick' , 'off' , ...
'YMinorTick' , 'off' , ...
'LineWidth' , 1 );
% 'YGrid' , 'on' , ...
% 'XColor' , [.3 .3 .3], ...
% 'YColor' , [.3 .3 .3], ...
if ~isempty(errors)
for i = 1:length(yData)
if isscalar(yData{i})
hE1 = hline(yData{i}+errors{i});
hE2 = hline(yData{i}-errors{i});
else
if length(yData{i}) >= length(xData)
if type == 1
hE1 = plotFunc(xData,yData{i}(1:length(xData))+errors{i}(1:length(xData)));
hE2 = plotFunc(xData,yData{i}(1:length(xData))-errors{i}(1:length(xData)));
end
end
end
set(hE1,'Color',min(1,colors(i,:)+.75),'LineWidth',1);
set(hE2,'Color',min(1,colors(i,:)+.75),'LineWidth',1);
if 0
switch i
case 2
set(hE1,'LineStyle','--');
set(hE2,'LineStyle','--');
case 3
set(hE1,'LineStyle','-.');
set(hE2,'LineStyle','-.');
case 4
set(hE1,'LineStyle',':');
set(hE2,'LineStyle',':');
end
else
set(hE1,'LineStyle','-');
set(hE2,'LineStyle','-');
end
pause;
end
end
set(gcf, 'PaperPositionMode', 'auto');
print -depsc2 finalPlot1.eps
end
function [] = applyStyle(h,i,colors,doLineStyle,doMarker,lineWidth)
set(h,'Color',colors(i,:),'LineWidth',lineWidth);
if doLineStyle
switch i
case 2
set(h,'LineStyle','--');
case 3
set(h,'LineStyle','-.');
case 4
set(h,'LineStyle',':');
end
end
if doMarker
% MarkerFaceColor
% MarkerSize
% MarkerEdgeColor
switch i
case 1
set(h,'Marker','o');
case 2
set(h,'Marker','s');
case 3
set(h,'Marker','d');
case 4
%set(h,'LineStyle','--');
set(h,'Marker','v');
end
set(h,'MarkerSize',10);
set(h,'MarkerFaceColor',[1 1 .9]);
%set(h,'MarkerFaceColor',min(colors(i,:)+.75,1));
end
end
|
github
|
lijunzh/fd_elastic-master
|
myProcessOptions.m
|
.m
|
fd_elastic-master/src/PQN/misc/myProcessOptions.m
| 674 |
utf_8
|
b94d252a960faa95a3074129247619e6
|
function [varargout] = myProcessOptions(options,varargin)
% Similar to processOptions, but case insensitive and
% using a struct instead of a variable length list
options = toUpper(options);
for i = 1:2:length(varargin)
if isfield(options,upper(varargin{i}))
v = getfield(options,upper(varargin{i}));
if isempty(v)
varargout{(i+1)/2}=varargin{i+1};
else
varargout{(i+1)/2}=v;
end
else
varargout{(i+1)/2}=varargin{i+1};
end
end
end
function [o] = toUpper(o)
if ~isempty(o)
fn = fieldnames(o);
for i = 1:length(fn)
o = setfield(o,upper(fn{i}),getfield(o,fn{i}));
end
end
end
|
github
|
lijunzh/fd_elastic-master
|
auxGroupLinfProject.m
|
.m
|
fd_elastic-master/src/PQN/project/auxGroupLinfProject.m
| 1,001 |
utf_8
|
beb66218882b76d74e58a8e4e86a0591
|
function w = groupLinfProject(w,p,groupStart,groupPtr)
alpha = w(p+1:end);
w = w(1:p);
for i = 1:length(groupStart)-1
groupInd = groupPtr(groupStart(i):groupStart(i+1)-1);
[w(groupInd) alpha(i)] = projectAuxSort(w(groupInd),alpha(i));
end
w = [w;alpha];
end
%% Function to solve the projection for a single group
function [w,alpha] = projectAuxSort(w,alpha)
if ~all(abs(w) <= alpha)
sorted = [sort(abs(w),'descend');0];
s = 0;
for k = 1:length(sorted)
% Compute Projection with k largest elements
s = s + sorted(k);
projPoint = (s+alpha)/(k+1);
if projPoint > 0 && projPoint > sorted(k+1)
w(abs(w) >= sorted(k)) = sign(w(abs(w) >= sorted(k)))*projPoint;
alpha = projPoint;
break;
end
if k == length(sorted)
% alpha is too negative, optimal answer is 0
w = zeros(size(w));
alpha = 0;
end
end
end
end
|
github
|
lijunzh/fd_elastic-master
|
Algorithm3BlockMatrix.m
|
.m
|
fd_elastic-master/src/PQN/DuchiEtAl_UAI2008/Algorithm3BlockMatrix.m
| 2,981 |
utf_8
|
abb9e934001a060787e9cd1c805a7a70
|
function [K,W,f] = Algorithm3(Sigma, groups, lambda,normtype)
% normtype = {2,Inf}
% Groups is a vector containing the group numbers for each row
% construct cell-array with indices for faster projection
groups = groups(:);
nGroups = max(groups);
indices = cell(nGroups,1);
for i=1:nGroups
indices{i} = find(groups == i);
end
% ASSUMPTION: indices are contiguous!
nIndices = zeros(size(indices));
for i=1:nGroups
nIndices(i) = length(indices{i});
end
% Get problem size
n = size(Sigma,1);
% Setup projection function
if normtype == 2
% funProj = @projectLinf2BlockMatrix;
funProj = @(a,b,c) projectLinf2BlockFast(a,nIndices,c); % (W, nIndices, lambda)
else
%funProj = @projectLinf1BlockMatrix;
funProj = @(a,b,c) projectLinf1BlockFast(a,nIndices,c); % (W, nIndices, lambda)
end
% Find initial W, using lemma 1 and diag(W) = lambda
W = initialW(Sigma,lambda(groups+nGroups*(groups-1)));
W = projectLinf1BlockMatrix(W,indices,lambda);
K = inv(Sigma + W);
% Print header
fprintf('%4s %11s %9s %9s\n','Iter','Objective','Gap','Step');
% Main loop
i = 0; maxiter = 500; epsilon = 1e-4; alpha = 1e-3; beta = 0.5; t = 1;
f = logdet(Sigma + W,-Inf);
while (1)
% Compute unconstrained gradient
G = K;
% Compute direction of step
D = funProj(W+t*G,indices,lambda);
% Compute initial and next objective values
f0 = f;
ft = logdet(Sigma + D,-Inf);
% Perform backtracking line search
while ft < f0 + alpha * traceMatProd(D-W,G)
% Exit with alpha is too small
if (t < 1e-6), break; end;
% Decrease t, recalculate direction and objective
t = beta * t;
D = funProj(W + t*G,indices,lambda);
ft = logdet(Sigma + D,-Inf);
end
f = ft;
% Update W and K
W = D;
K = inv(Sigma + W);
% Compute duality gap
eta = traceMatProd(Sigma,K) - n;
for j=1:nGroups
for l=1:nGroups
if j==l
y = K(indices{j},indices{l});
mak = sum(sum(abs(y)));
else
y = K(indices{j},indices{l}); y = y(:);
mak = norm(y,normtype);
end
if ~isempty(mak)
eta = eta + lambda(j+nGroups*(l-1)) * mak;
end
end
end
% Increment iteration
i = i + 1;
% Print progress
fprintf('%4d %11.4e %9.2e %9.2e\n',i,f,eta,t);
% Check stopping criterion
if (eta < epsilon)
fprintf('Exit: Optimal solution\n');
break;
elseif (i >= maxiter)
fprintf('Exit: Maximum number of iterations reached\n');
break;
elseif (t < 1e-6)
fprintf('Exit: Linesearch error\n');
break;
end
% Increase t slightly
t = t / beta;
end
end
function l = logdet(M,errorDet)
[R,p] = chol(M);
if p ~= 0
l = errorDet;
else
l = 2*sum(log(diag(R)));
end
global trace
if trace == 1
global fValues
fValues(end+1,1) = l;
drawnow
end
end
|
github
|
lijunzh/fd_elastic-master
|
Algorithm1.m
|
.m
|
fd_elastic-master/src/PQN/DuchiEtAl_UAI2008/Algorithm1.m
| 2,282 |
utf_8
|
c242f4201c7825c86e7951b13c83425a
|
function [K,W] = Algorithm1(Sigma, lambda)
% Get problem size
n = size(Sigma,1);
% Find initial W, using lemma 1 and diag(W) = lambda
W = initialW(Sigma,diag(lambda));
K = inv(Sigma + W);
% Print header
fprintf('%4s %11s %9s %9s\n','Iter','Objective','Gap','Step');
% Main loop
i = 0; maxiter = 1200; epsilon = 1e-4;
f = logdet(Sigma+W,-Inf);
while (1)
% Compute unconstrained gradient
G = K;
% Zero components of gradient which would result in constrain violation
G((1:n) + (0:n-1)*n) = 0; % Gii = 0
G((W == lambda) & (G > 0)) = 0;
G((W ==-lambda) & (G < 0)) = 0;
% Perform line search and obtain new W
[t,f,W] = Algorithm2(Sigma,W,K,G,lambda,f);
% Update K
K = inv(Sigma + W);
% Compute duality gap
eta = trace(Sigma * K) + sum(sum(lambda.*abs(K))) - n;
% Increment iteration
i = i + 1;
% Print progress
fprintf('%4d %11.4e %9.2e %9.2e\n',i,f,eta,t);
% Check stopping criterion
if (eta < epsilon)
fprintf('Exit: Optimal solution\n');
break;
elseif (i >= maxiter)
fprintf('Exit: Maximum number of iterations reached\n');
break;
elseif (t < 1e-6)
fprintf('Exit: Linesearch error\n');
break;
end
end
end
function [t,f,W] = Algorithm2(Sigma,W0,K,G,lambda,f0)
KG = K*G;
t = trace(KG) / traceMatProd(KG,KG);
while(1)
% Trial solution projected onto feasible box
W = W0 + t*G;
idx = W > lambda; W(idx) = lambda(idx); % Project - Positive part
idx = W <-lambda; W(idx) = -lambda(idx); % Project - Negative part
% Compute new objective
f = logdet(Sigma + W,-Inf);
fHat = f;
% D = W - W0;
% KD = K * D;
% fHat = f0 + trace(KD) - traceMatProd(KD,KD) / 2;
% Test exit conditions
if fHat >= f0, break; end;
if t < 1e-6, break; end;
% Reduce step length
t = t / 2;
end
% Following is needed when using the approximate evaluation
%f = logdet(Sigma+W);
end
function l = logdet(M,errorDet)
[R,p] = chol(M);
if p ~= 0
l = errorDet;
else
l = 2*sum(log(diag(R)));
end;
global trace
if trace == 1
global fValues
fValues(end+1,1) = l;
drawnow
end
end
|
github
|
lijunzh/fd_elastic-master
|
minConF_PQN.m
|
.m
|
fd_elastic-master/src/PQN/minConF/minConF_PQN.m
| 8,435 |
utf_8
|
9af951891988336bc11af977e11f33f2
|
function [x,f,funEvals] = minConF_PQN(funObj,x,funProj,options)
% function [x,f] = minConF_PQN(funObj,funProj,x,options)
%
% Function for using a limited-memory projected quasi-Newton to solve problems of the form
% min funObj(x) s.t. x in C
%
% The projected quasi-Newton sub-problems are solved the spectral projected
% gradient algorithm
%
% @funObj(x): function to minimize (returns gradient as second argument)
% @funProj(x): function that returns projection of x onto C
%
% options:
% verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3:
% debug)
% optTol: tolerance used to check for progress (default: 1e-6)
% maxIter: maximum number of calls to funObj (default: 500)
% maxProject: maximum number of calls to funProj (default: 100000)
% numDiff: compute derivatives numerically (0: use user-supplied
% derivatives (default), 1: use finite differences, 2: use complex
% differentials)
% suffDec: sufficient decrease parameter in Armijo condition (default: 1e-4)
% corrections: number of lbfgs corrections to store (default: 10)
% adjustStep: use quadratic initialization of line search (default: 0)
% bbInit: initialize sub-problem with Barzilai-Borwein step (default: 1)
% SPGoptTol: optimality tolerance for SPG direction finding (default: 1e-6)
% SPGiters: maximum number of iterations for SPG direction finding (default:10)
nVars = length(x);
% Set Parameters
if nargin < 4
options = [];
end
[verbose,numDiff,optTol,maxIter,maxProject,suffDec,corrections,adjustStep,bbInit,SPGoptTol,SPGiters,SPGtestOpt] = ...
myProcessOptions(...
options,'verbose',2,'numDiff',0,'optTol',1e-6,'maxIter',500,'maxProject',100000,'suffDec',1e-4,...
'corrections',10,'adjustStep',0,'bbInit',0,'SPGoptTol',1e-6,'SPGiters',10,'SPGtestOpt',0);
% Output Parameter Settings
if verbose >= 3
fprintf('Running PQN...\n');
fprintf('Number of L-BFGS Corrections to store: %d\n',corrections);
fprintf('Spectral initialization of SPG: %d\n',bbInit);
fprintf('Maximum number of SPG iterations: %d\n',SPGiters);
fprintf('SPG optimality tolerance: %.2e\n',SPGoptTol);
fprintf('PQN optimality tolerance: %.2e\n',optTol);
fprintf('Quadratic initialization of line search: %d\n',adjustStep);
fprintf('Maximum number of function evaluations: %d\n',maxIter);
fprintf('Maximum number of projections: %d\n',maxProject);
end
% Output Log
if verbose >= 2
fprintf('%10s %10s %10s %15s %15s %15s\n','Iteration','FunEvals','Projections','Step Length','Function Val','Opt Cond');
end
% Make objective function (if using numerical derivatives)
funEvalMultiplier = 1;
if numDiff
if numDiff == 2
useComplex = 1;
else
useComplex = 0;
end
funObj = @(x)autoGrad(x,useComplex,funObj);
funEvalMultiplier = nVars+1-useComplex;
end
% Project initial parameter vector
x = funProj(x);
projects = 1;
% Evaluate initial parameters
[f,g] = funObj(x);
funEvals = 1;
% Check Optimality of Initial Point
projects = projects+1;
if sum(abs(funProj(x-g)-x)) < optTol
if verbose >= 1
fprintf('First-Order Optimality Conditions Below optTol at Initial Point\n');
end
return;
end
i = 1;
while funEvals <= maxIter
% Compute Step Direction
if i == 1
p = funProj(x-g);
projects = projects+1;
S = zeros(nVars,0);
Y = zeros(nVars,0);
Hdiag = 1;
else
y = g-g_old;
s = x-x_old;
[S,Y,Hdiag] = lbfgsUpdate(y,s,corrections,verbose==3,S,Y,Hdiag);
% Make Compact Representation
k = size(Y,2);
L = zeros(k);
for j = 1:k
L(j+1:k,j) = S(:,j+1:k)'*Y(:,j);
end
N = [S/Hdiag Y];
M = [S'*S/Hdiag L;L' -diag(diag(S'*Y))];
HvFunc = @(v)lbfgsHvFunc2(v,Hdiag,N,M);
if bbInit
% Use Barzilai-Borwein step to initialize sub-problem
alpha = (s'*s)/(s'*y);
if alpha <= 1e-10 || alpha > 1e10
alpha = 1/norm(g);
end
% Solve Sub-problem
xSubInit = x-alpha*g;
feasibleInit = 0;
else
xSubInit = x;
feasibleInit = 1;
end
% Solve Sub-problem
[p,subProjects] = solveSubProblem(x,g,HvFunc,funProj,SPGoptTol,SPGiters,SPGtestOpt,feasibleInit,x);
projects = projects+subProjects;
end
d = p-x;
g_old = g;
x_old = x;
% Check that Progress can be made along the direction
gtd = g'*d;
if gtd > -optTol
if verbose >= 1
fprintf('Directional Derivative below optTol\n');
end
break;
end
% Select Initial Guess to step length
if i == 1 || adjustStep == 0
t = 1;
else
t = min(1,2*(f-f_old)/gtd);
end
% Bound Step length on first iteration
if i == 1
t = min(1,1/sum(abs(g)));
end
% Evaluate the Objective and Gradient at the Initial Step
x_new = x + t*d;
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
% Backtracking Line Search
f_old = f;
while f_new > f + suffDec*t*gtd || ~isLegal(f_new)
temp = t;
% Backtrack to next trial value
if ~isLegal(f_new) || ~isLegal(g_new)
if verbose == 3
fprintf('Halving Step Size\n');
end
t = t/2;
else
if verbose == 3
fprintf('Cubic Backtracking\n');
end
t = polyinterp([0 f gtd; t f_new g_new'*d]);
end
% Adjust if change is too small/large
if t < temp*1e-3
if verbose == 3
fprintf('Interpolated value too small, Adjusting\n');
end
t = temp*1e-3;
elseif t > temp*0.6
if verbose == 3
fprintf('Interpolated value too large, Adjusting\n');
end
t = temp*0.6;
end
% Check whether step has become too small
if sum(abs(t*d)) < optTol || t == 0
if verbose == 3
fprintf('Line Search failed\n');
end
t = 0;
f_new = f;
g_new = g;
break;
end
% Evaluate New Point
f_prev = f_new;
t_prev = temp;
x_new = x + t*d;
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
end
% Take Step
x = x_new;
f = f_new;
g = g_new;
optCond = sum(abs(funProj(x-g)-x));
projects = projects+1;
% Output Log
if verbose >= 2
fprintf('%10d %10d %10d %15.5e %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,projects,t,f,optCond);
end
% Check optimality
if optCond < optTol
fprintf('First-Order Optimality Conditions Below optTol\n');
break;
end
if sum(abs(t*d)) < optTol
if verbose >= 1
fprintf('Step size below optTol\n');
end
break;
end
if abs(f-f_old) < optTol
if verbose >= 1
fprintf('Function value changing by less than optTol\n');
end
break;
end
if funEvals*funEvalMultiplier > maxIter
if verbose >= 1
fprintf('Function Evaluations exceeds maxIter\n');
end
break;
end
if projects > maxProject
if verbose >= 1
fprintf('Number of projections exceeds maxProject\n');
end
break;
end
i = i + 1;
end
end
function [p,subProjects] = solveSubProblem(x,g,H,funProj,optTol,maxIter,testOpt,feasibleInit,x_init)
% Uses SPG to solve for projected quasi-Newton direction
options.verbose = 0;
options.optTol = optTol;
options.maxIter = maxIter;
options.testOpt = testOpt;
options.feasibleInit = feasibleInit;
funObj = @(p)subHv(p,x,g,H);
[p,f,funEvals,subProjects] = minConF_SPG(funObj,x_init,funProj,options);
end
function [f,g] = subHv(p,x,g,HvFunc)
d = p-x;
Hd = HvFunc(d);
f = g'*d + (1/2)*d'*Hd;
g = g + Hd;
end
|
github
|
lijunzh/fd_elastic-master
|
minConF_PQN_new.m
|
.m
|
fd_elastic-master/src/PQN/minConF/minConF_PQN_new.m
| 9,327 |
utf_8
|
9a3b5e452f461865773d72fe89f5373f
|
function [x,f,funEvals] = minConF_PQN_new(funObj,x,funProj,options)
% function [x,f] = minConF_PQN(funObj,funProj,x,options)
%
% Function for using a limited-memory projected quasi-Newton to solve problems of the form
% min funObj(x) s.t. x in C
%
% The projected quasi-Newton sub-problems are solved the spectral projected
% gradient algorithm
%
% @funObj(x): function to minimize (returns gradient as second argument)
% @funProj(x): function that returns projection of x onto C
%
% options:
% verbose: level of verbosity (0: no output, 1: final, 2: iter (default), 3:
% debug)
% optTol: tolerance used to check for progress (default: 1e-6)
% maxIter: maximum number of calls to funObj (default: 500)
% maxProject: maximum number of calls to funProj (default: 100000)
% numDiff: compute derivatives numerically (0: use user-supplied
% derivatives (default), 1: use finite differences, 2: use complex
% differentials)
% suffDec: sufficient decrease parameter in Armijo condition (default: 1e-4)
% corrections: number of lbfgs corrections to store (default: 10)
% adjustStep: use quadratic initialization of line search (default: 0)
% testOpt: test optimality condition (default: 1)
% bbInit: initialize sub-problem with Barzilai-Borwein step (default: 1)
% SPGoptTol: optimality tolerance for SPG direction finding (default: 1e-6)
% SPGiters: maximum number of iterations for SPG direction finding (default:10)
% SPGtestOpt: test optimality condition for sub-problems to be solved by SPG (default: 0)
nVars = length(x);
% Set Parameters
if nargin < 4
options = [];
end
[verbose,numDiff,optTol,maxIter,maxProject,suffDec,corrections,adjustStep,testOpt,bbInit,SPGoptTol,SPGiters,SPGtestOpt] = ...
myProcessOptions(...
options,'verbose',2,'numDiff',0,'optTol',1e-6,'maxIter',500,'maxProject',1e6,'suffDec',1e-4,...
'corrections',10,'adjustStep',0,'testOpt',1,'bbInit',0,'SPGoptTol',1e-6,'SPGiters',10,'SPGtestOpt',0);
% Output Parameter Settings
if verbose >= 3
fprintf('Running PQN...\n');
fprintf('Number of L-BFGS Corrections to store: %d\n',corrections);
fprintf('Spectral initialization of SPG: %d\n',bbInit);
fprintf('Maximum number of SPG iterations: %d\n',SPGiters);
fprintf('SPG optimality tolerance: %.2e\n',SPGoptTol);
fprintf('PQN optimality tolerance: %.2e\n',optTol);
fprintf('Quadratic initialization of line search: %d\n',adjustStep);
fprintf('Maximum number of function evaluations: %d\n',maxIter);
fprintf('Maximum number of projections: %d\n',maxProject);
end
% Output Log
if verbose >= 2
if testOpt
fprintf('%10s %10s %10s %15s %15s %15s\n','Iteration','FunEvals','Projections','Step Length','Function Val','Opt Cond');
else
fprintf('%10s %10s %10s %15s %15s\n','Iteration','FunEvals','Projections','Step Length','Function Val');
end
end
% Make objective function (if using numerical derivatives)
funEvalMultiplier = 1;
if numDiff
if numDiff == 2
useComplex = 1;
else
useComplex = 0;
end
funObj = @(x)autoGrad(x,useComplex,funObj);
funEvalMultiplier = nVars+1-useComplex;
end
% Project initial parameter vector
x = funProj(x);
projects = 1;
% Evaluate initial parameters
[f,g] = funObj(x);
funEvals = 1;
% Optionally check Optimality of Initial Point
if testOpt
projects = projects+1;
if sum(abs(funProj(x-g)-x)) < optTol
if verbose >= 1
fprintf('First-Order Optimality Conditions Below optTol at Initial Point\n');
end
return;
end
end
i = 1;
while funEvals <= maxIter
% Compute Step Direction
if i == 1
p = x-g; % funProj(x-g);
% projects = projects+1;
S = zeros(nVars,0);
Y = zeros(nVars,0);
Hdiag = 1;
else
y = g-g_old;
s = x-x_old;
[S,Y,Hdiag] = lbfgsUpdate(y,s,corrections,verbose==3,S,Y,Hdiag);
% Make Compact Representation
k = size(Y,2);
L = zeros(k);
for j = 1:k
L(j+1:k,j) = S(:,j+1:k)'*Y(:,j);
end
N = [S/Hdiag Y];
M = [S'*S/Hdiag L;L' -diag(diag(S'*Y))];
HvFunc = @(v)lbfgsHvFunc2(v,Hdiag,N,M);
if bbInit
% Use Barzilai-Borwein step to initialize sub-problem
alpha = (s'*s)/(s'*y);
if alpha <= 1e-20 || alpha > 1e20 % if (alpha <= 1e-10 || alpha > 1e10)
alpha = 1/norm(g);
end
% Solve Sub-problem
xSubInit = x-alpha*g;
feasibleInit = 0;
else
xSubInit = x;
feasibleInit = 1;
end
% Solve Sub-problem
[p,subProjects] = solveSubProblem(x,g,HvFunc,funProj,SPGoptTol,SPGiters,SPGtestOpt,feasibleInit,xSubInit);
projects = projects+subProjects;
end
d = p-x;
g_old = g;
x_old = x;
% Check that Progress can be made along the direction
gtd = g'*d;
if gtd > -optTol
if verbose >= 1
fprintf('Directional Derivative below optTol\n');
end
break;
end
% Select Initial Guess to step length
if i == 1 || adjustStep == 0
t = 1;
else
t = min(1,2*(f-f_old)/gtd);
end
% Bound Step length on first iteration
if i == 1
t = min(1,1/sum(abs(g)));
end
% Evaluate the Objective and Gradient at the Initial Step
% x_new = x + t*d;
x_new = funProj(x + t*d);
projects = projects+1;
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
% Backtracking Line Search
f_old = f;
while f_new > f + suffDec*t*gtd || ~isLegal(f_new)
temp = t;
% Backtrack to next trial value
if ~isLegal(f_new) || ~isLegal(g_new)
if verbose == 3
fprintf('Halving Step Size\n');
end
t = t/2;
else
if verbose == 3
fprintf('Cubic Backtracking\n');
end
t = polyinterp([0 f gtd; t f_new g_new'*d]);
end
% Adjust if change is too small/large
if t < temp*1e-3
if verbose == 3
fprintf('Interpolated value too small, Adjusting\n');
end
t = temp*1e-3;
elseif t > temp*0.6
if verbose == 3
fprintf('Interpolated value too large, Adjusting\n');
end
t = temp*0.6;
end
% Check whether step has become too small
if sum(abs(t*d)) < optTol || t == 0
if verbose == 3
fprintf('Line Search failed\n');
end
t = 0;
f_new = f;
g_new = g;
break;
end
% Evaluate New Point
f_prev = f_new;
t_prev = temp;
% x_new = x + t*d;
x_new = funProj(x + t*d);
projects = projects+1;
[f_new,g_new] = funObj(x_new);
funEvals = funEvals+1;
end
% Take Step
x = x_new;
f = f_new;
g = g_new;
if testOpt
optCond = sum(abs(funProj(x-g)-x));
projects = projects+1;
end
% Output Log
if verbose >= 2
if testOpt
fprintf('%10d %10d %10d %15.5e %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,projects,t,f,optCond);
else
fprintf('%10d %10d %10d %15.5e %15.5e\n',i,funEvals*funEvalMultiplier,projects,t,f);
end
end
% Check optimality
if testOpt
if optCond < optTol
if verbose >= 1
fprintf('First-Order Optimality Conditions Below optTol\n');
end
break;
end
end
if sum(abs(t*d)) < optTol
if verbose >= 1
fprintf('Step size below optTol\n');
end
break;
end
if abs(f-f_old) < optTol
if verbose >= 1
fprintf('Function value changing by less than optTol\n');
end
break;
end
if funEvals*funEvalMultiplier > maxIter
if verbose >= 1
fprintf('Function Evaluations exceeds maxIter\n');
end
break;
end
if projects > maxProject
if verbose >= 1
fprintf('Number of projections exceeds maxProject\n');
end
break;
end
i = i + 1;
end
end
function [p,subProjects] = solveSubProblem(x,g,H,funProj,optTol,maxIter,testOpt,feasibleInit,x_init)
% Uses SPG to solve for projected quasi-Newton direction
options.verbose = 2; % 0;
options.optTol = optTol;
options.maxIter = maxIter;
options.testOpt = testOpt;
options.curvilinear = 1;
options.feasibleInit = feasibleInit;
funObj = @(p)subHv(p,x,g,H);
[p,f,funEvals,subProjects] = minConF_SPG_new(funObj,x_init,funProj,options);
end
function [f,g] = subHv(p,x,g,HvFunc)
d = p-x;
Hd = HvFunc(d);
f = g'*d + (1/2)*d'*Hd;
g = g + Hd;
end
|
github
|
lijunzh/fd_elastic-master
|
L1groupGraft.m
|
.m
|
fd_elastic-master/src/PQN/groupL1/L1groupGraft.m
| 2,228 |
utf_8
|
8ea295e38bf112e79fe77edecfb68dac
|
function [w] = L1groupGraft(funObj,w,groups,lambda,options)
if nargin < 5
options = [];
end
[maxIter,optTol] = myProcessOptions(options,'maxIter',500,'optTol',1e-6);
nVars = length(w);
nGroups = max(groups);
reg = sqrt(accumarray(groups(groups~=0),w(groups~=0).^2));
% Compute Initial Free Variables
free = ones(nVars,1);
for s = 1:nGroups
if reg(s) == 0
free(groups==s) = 0;
end
end
% Optimize Initial Free Variables
subOptions = options;
subOptions.TolFun = 1e-16;
subOptions.TolX = 1e-16;
subOptions.Display = 'none';
if any(free == 1)
[w(free==1) f junk2 output] = minFunc(@subGradient,w(free==1),subOptions,free,funObj,groups,lambda);
fEvals = output.funcCount;
end
i = 1;
maxViolGroup = -2;
old_maxViolGroup = -1;
while fEvals < maxIter
reg = sqrt(accumarray(groups(groups~=0),w(groups~=0).^2));
[f,g] = subGradient(w,ones(nVars,1),funObj,groups,lambda);
fprintf('%5d %5d %15.5f %15.5e %5d\n',i,fEvals,f,sum(abs(g)),sum(reg > 0));
if sum(abs(g)) < optTol
fprintf('Solution Found\n');
break;
end
if all(free==1)
fprintf('Stuck\n');
end
% Compute Free Variables
free = ones(nVars,1);
for s = 1:nGroups
if reg(s) == 0
free(groups==s) = 0;
end
end
% Add Group with biggest sub-gradient
gradReg = sqrt(accumarray(groups(groups~=0),g(groups~=0).^2));
[maxViol maxViolGroup] = max(gradReg);
free(groups==maxViolGroup) = 1;
if maxViolGroup == old_maxViolGroup
fprintf('Stuck (optTol = %15.5e)\n',sum(abs(g)));
break;
end
old_maxViolGroup = maxViolGroup;
% Optimize Free Variables
if any(free == 1)
[w(free==1) f junk2 output] = minFunc(@subGradient,w(free==1),subOptions,free,funObj,groups,lambda);
fEvals = fEvals+output.funcCount;
end
i = i + 1;
end
end
function [f,g] = subGradient(wSub,free,funObj,groups,lambda)
w = zeros(size(free));
w(free==1) = wSub;
[f,g] = funObj(w);
f = f + lambda*sum(sqrt(accumarray(groups(groups~=0),w(groups~=0).^2)));
g = getGroupSlope(w,lambda,g,groups,1e-4);
g = g(free==1);
end
|
github
|
lijunzh/fd_elastic-master
|
L1groupMinConF.m
|
.m
|
fd_elastic-master/src/PQN/groupL1/L1groupMinConF.m
| 4,352 |
utf_8
|
6a8c330fabfaf0dae63c047818b43b5c
|
function [w,f] = L1groupMinConF(funObj,w,groups,lambda,options)
% [w] = L1groupMinConF(funObj,w,groups,lambda,options)
if nargin < 5
options = [];
end
[normType,mode,optTol] = myProcessOptions(options,'normType',2,'mode','spg','optTol',1e-6);
nVars = length(w);
nGroups = max(groups);
% Make initial values for auxiliary variables
wAlpha = [w;zeros(nGroups,1)];
for g = 1:nGroups
if normType == 2
wAlpha(nVars+g) = norm(w(groups==g));
else
if any(groups==g)
wAlpha(nVars+g) = max(abs(w(groups==g)));
end
end
end
% Make Objective Function
wrapFunObj = @(w)auxGroupLoss(w,groups,lambda,funObj);
if normType == 2
switch mode
case 'barrier'
wAlpha(nVars+1:end) = wAlpha(nVars+1:end)+1e-2;
funCon = @(w)groupL2Barrier(w,groups);
[wAlpha,f,fEvals] = minConF_LB(wrapFunObj,wAlpha,funCon,options);
case 'penalty'
% Doesn't work
funCon = @(w)groupL2Penalty(w,groups);
[wAlpha,f,fEvals] = minConF_Pen(wrapFunObj,wAlpha,funCon,options);
case 'spg'
[groupStart,groupPtr] = groupl1_makeGroupPointers(groups);
funProj = @(w)auxGroupL2Project(w,nVars,groupStart,groupPtr);
%funProj = @(w)auxGroupL2Proj(w,groups);
wAlpha = minConF_SPG(wrapFunObj,wAlpha,funProj,options);
case 'sop'
[groupStart,groupPtr] = groupl1_makeGroupPointers(groups);
funProj = @(w)auxGroupL2Project(w,nVars,groupStart,groupPtr);
options.bbInit = 0;
options.SPGoptTol = 1e-6;
options.SPGiters = 500;
options.maxProject = inf;
options.SPGtestOpt = 1;
[wAlpha,f] = minConF_PQN(wrapFunObj,wAlpha,funProj,options);
case 'interior'
wAlpha(nVars+1:end) = wAlpha(nVars+1:end)+1e-2;
funCon = @(w,lambda)groupL2Residuals(w,lambda,groups);
wAlpha = minConF_IP2(wrapFunObj,wAlpha,funCon,options);
case 'sep'
funObj1 = @(w)funObj(w);
funObj2 = @(w)groupL1regularizer(w,lambda,groups);
funProj = @(w,stepSize)groupSoftThreshold(w,stepSize,lambda,groups);
wAlpha = minConF_Sep(funObj1,funObj2,w,funProj,options);
end
else
switch mode
case 'barrier'
[A,b] = makeL1LinfConstraints(groups);
wAlpha(nVars+1:end) = wAlpha(nVars+1:end)+1e-2;
funCon = @(w)linearBarrier(w,A,b);
[wAlpha,f,fEvals] = minConF_LB(wrapFunObj,wAlpha,funCon,options);
case 'penalty'
[A,b] = makeL1LinfConstraints(groups);
funCon = @(w)linearInequalityPenalty(w,A,b);
[wAlpha,f,fEvals] = minConF_Pen(wrapFunObj,wAlpha,funCon,options);
case 'spg'
funProj = @(w)auxGroupLinfProj(w,groups);
wAlpha = minConF_SPG(wrapFunObj,wAlpha,funProj,options);
case 'sop'
funProj = @(w)auxGroupLinfProj(w,groups);
funSOP = @(w,g,H)SOP_SPG(w,g,H,funProj);
wAlpha = minConF_SOP(wrapFunObj,wAlpha,funProj,funSOP,options);
case 'active'
% Doesn't work (constraints are degenerate)
[A,b] = makeL1LinfConstraints(groups);
wAlpha = minConF_AS(wrapFunObj,wAlpha,A,b,options);
case 'interior'
[A,b] = makeL1LinfConstraints(groups);
wAlpha(nVars+1:end) = wAlpha(nVars+1:end)+1e-2;
wAlpha = minConF_IP(wrapFunObj,wAlpha,-A,b,options);
end
end
w = wAlpha(1:nVars);
end
function [A,b] = makeL1LinfConstraints(groups)
nVars = length(groups);
nGroups = max(groups);
A = zeros(0,nVars+nGroups);
j = 1;
for i = 1:nVars
if groups(i) ~= 0
A(j,i) = 1;
A(j,nVars+groups(i)) = 1;
A(j+1,i) = -1;
A(j+1,nVars+groups(i)) = 1;
j = j+2;
end
end
b = zeros(size(A,1),1);
end
function [f] = groupL1regularizer(w,lambda,groups)
f = lambda*sum(sqrt(accumarray(groups(groups~=0),w(groups~=0).^2)));
end
function [w] = groupSoftThreshold(w,alpha,lambda,groups)
nGroups = max(groups);
reg = sqrt(accumarray(groups(groups~=0),w(groups~=0).^2));
for g = 1:nGroups
w(groups==g) = (w(groups==g)/reg(g))*max(0,reg(g)-lambda*alpha);
end
end
|
github
|
lijunzh/fd_elastic-master
|
auxGroupL2Project.m
|
.m
|
fd_elastic-master/src/PQN/groupL1/auxGroupL2Project.m
| 605 |
utf_8
|
9c39c0d039de49b67d1d078c6467f3e3
|
function w = groupL2Proj(w,p,groupStart,groupPtr)
alpha = w(p+1:end);
w = w(1:p);
for i = 1:length(groupStart)-1
groupInd = groupPtr(groupStart(i):groupStart(i+1)-1);
[w(groupInd) alpha(i)] = projectAux(w(groupInd),alpha(i));
end
w = [w;alpha];
end
%% Function to solve the projection for a single group
function [w,alpha] = projectAux(w,alpha)
p = length(w);
nw = norm(w);
if nw > alpha
avg = (nw+alpha)/2;
if avg < 0
w(:) = 0;
alpha = 0;
else
w = w*avg/nw;
alpha = avg;
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.