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 | jhalakpatel/AI-ML-DL-master | loadubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | saveubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | submit.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | submitWithConfiguration.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex3/ex3/lib/submitWithConfiguration.m | 3,734 | utf_8 | 84d9a81848f6d00a7aff4f79bdbb6049 | function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github | jhalakpatel/AI-ML-DL-master | savejson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | loadjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | loadubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | saveubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | submit.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | submitWithConfiguration.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/machine-learning-ex1/ex1/lib/submitWithConfiguration.m | 3,734 | utf_8 | 84d9a81848f6d00a7aff4f79bdbb6049 | function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf( ...
'!! Submission failed: unexpected error: %s\n', ...
e.message);
fprintf('!! Please try again later.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
params = {'jsonBody', body};
responseBody = urlread(submissionUrl, 'post', params);
response = loadjson(responseBody);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github | jhalakpatel/AI-ML-DL-master | savejson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | loadjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | loadubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | jhalakpatel/AI-ML-DL-master | saveubjson.m | .m | AI-ML-DL-master/AndrewNg_MachineLearning/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 | SeRViCE-Lab/FormationControl-master | detector.m | .m | FormationControl-master/sphero_ros/detector.m | 6,914 | utf_8 | d28e558faed25d1343ebb11ae9439023 | % Version 1.4:
% - Replaces centroids by median of upper edge of the bbox.
% this provides a more stable representation for the
% location of the spheros
%
% Version 1.3:
% - Sends back the run time as a parameter
%
% Version 1.2:
% - Refined search method:
% blob detection, then circle detection around the
% blobs, but only when the correct number of robots
% is not detected
%
% Version 1.1:
% - It doesn't work, its just for trial purposes
%
% Version 1.0:
% - Initial version
% - Detects blobs of resonable size using binarization
% according to a threshold
% - Can distinguish between robots that have collided (using erosion)
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [locs, bboxes,t] = detect_SpheroV1_4 (frame, numRob)
tic
% initialize variables
locs = zeros(2, numRob);
centersTemp(:,1) = [0;0];
bboxes = zeros(4, numRob);
bboxesTemp(:,1) = [0;0;0;0];
thresh = 0.9;
newDetectedTotal = 0;
numBlobsChecked = 0;
% resizing the image
frame = imresize(frame, [480,640]);
% changing frame to grayscale
frameGray = rgb2gray(frame);
% figure;
% imshow(frameGray);
% binarize blurred image usign a threshold
frameBin = imbinarize (frameGray,thresh); % generate binary image using thresh
% figure;
% imshow(frameBin);
% erode the image to remove noise
erodeElt = strel('disk',5);
frameEr = imerode(frameBin,erodeElt);
% figure;
% imshow(frameEr);
% dilate eroded image
dilateElt = strel('disk',5);
frameDil = imdilate(frameEr, dilateElt);
% figure;
% imshow(frameDil);
% detect large enough blobs
whiteBlobs = bwpropfilt(frameDil, 'Area', [20, 100000]); % find white blobs
% figure;
% imshow(whiteBlobs);
% get statistics from whiteBolobs image
stats1 = regionprops ( logical(whiteBlobs), ...
'BoundingBox', 'Centroid', 'Area',...
'MajorAxisLength', 'MinorAxisLength');
% organize data
center1 = reshape([stats1.Centroid]', 2, numel(stats1));
bboxes1 = reshape([stats1.BoundingBox]', 4, numel(stats1)); % format: ULcorner(x,y), x-width, y-width
area1 = reshape([stats1.Area]', 1, numel(stats1));
majAxLeng1 = reshape([stats1.MajorAxisLength]', 1, numel(stats1));
minAxLeng1 = reshape([stats1.MinorAxisLength]', 1, numel(stats1));
numRobDetect = numel(stats1); % number of robots detected
% check to see if all robots were detected
if (numRobDetect == numRob) % if robots detected
bboxes = bboxes1;
locs(:,:) = bboxes(1:2, :) + [bboxes(3,:)/2;zeros(1,numel(bboxes)/4)];
elseif (numRobDetect > numRob)
disp('Error: More objects detected than spheros');
disp('Centers will be set to zero');
else % objects detected < num Spheros
% calculate ratios of maj/min axis length
for i = 1 : numel(stats1)
maj_minAxRatio(i) = majAxLeng1(i)/ minAxLeng1(i);
end
% sort the detected blobs based on maj/min axis ratio
[sortedAxRatio,sortAxRatioIndex] = sort(maj_minAxRatio); %finding sorting index using ratio
stats2 = stats1(sortAxRatioIndex); % sort stats based on index obtained
% organize data
centers2 = reshape([stats2.Centroid]', 2, numel(stats2));
bboxes2 = reshape([stats2.BoundingBox]', 4, numel(stats2)); % format: ULcorner(x,y), x-width, y-width
area2 = reshape([stats2.Area]', 1, numel(stats2));
majAxLeng2 = reshape([stats2.MajorAxisLength]', 1, numel(stats2));
minAxLeng2 = reshape([stats2.MinorAxisLength]', 1, numel(stats2));
% go through list to detect circles in blobs
for i = numel(stats2) : -1 : 1
if (numRobDetect ~= numRob)
box = bboxes2(:,i); % get bbox
center = centers2(:,i); % store center
cornerUL = [box(1); box(2)];% store UL corner
xCorner = box(1);
yCorner = box(2);
xWidth = box(3);
yWidth = box(4);
% zoom in on object
xWidthN = xWidth * 1.5; % new x-width
yWidthN = yWidth * 1.5; % new y-width
dxWidth = xWidthN -xWidth; % variation in xWidth
dyWidth = yWidthN -yWidth; % variation in yWidth
xCornerN = xCorner - dxWidth/2; % new x for UL corner
yCornerN = yCorner - dyWidth/2; % new y for UL corner
boxN = [xCornerN, yCornerN, xWidthN, yWidthN]; % new bbox
% take only image in new bbox
frameCrop = frameGray( ...
max(0,round(yCornerN)) : min(round(yCornerN + yWidthN), 480) ,...
max(0,round(xCornerN)) : min(round(xCornerN + xWidthN), 680));
% frame;
% imshow(frameCrop);
% hold on;
% scatter(xWidthN/2 ,yWidthN/2, 'filled', 'LineWidth', 2); % display center on image
% hold off;
% use circle detection on zoomed image
d = min(xWidthN, yWidthN); % minimum of new bbox sides
tic
[c, r] = imfindcircles(frameCrop,[round(d*0.1667), 3*round(0.1667*d)-1],'Sensitivity',0.9); % find circles
toc
% frame;
% imshow(frameCrop);
% hold on;
% viscircles(c, r,'Color','b');
% hold off
%
% moving back centers to the initial frame
cFrame = c + [xCornerN, yCornerN]; % cFrame = [x1, y1 ; x2, y2; x3,y3 ; ...]
% frame;
% imshow(frameGray);
% hold on;
% viscircles(cFrame, r,'Color','b');
% hold off;
% saving the new centers and bboxes
newDetected = numel(cFrame)/2;
for j = 1 : newDetected
centersTemp(:,numel(centersTemp)/2+1) = cFrame(j,:); % sotre new center
cornerUL = cFrame(j,:) - r(j); % calculate new corener for bbox
bboxesTemp(:,numel(bboxesTemp)/4+1) = [cornerUL' ; 2*r(j); 2*r(j)]; % store new bboc
end
% deleting old centers2 and bboxes2
centers2(:,i) = [];
bboxes2(:,i) = [];
% update numBlobsChecked, newDetectedTotal, and numRobDetect
numBlobsChecked = numBlobsChecked + 1; % keep track of number of blobs checked for robots
newDetectedTotal = newDetectedTotal + newDetected; % keep track of number of newly discovered robots
numRobDetect = numRobDetect + newDetected - 1; % update number of robots detected
end
end
bboxes(:, 1 : (numel(bboxesTemp)/4-1)) = bboxesTemp(:, 2 : end);
bboxes(:, (numel(bboxesTemp)/4) : numRob) = bboxes2(:,:);
locs(:,:) = bboxes(1:2, :) + [bboxes(3,:)/2;zeros(1,numel(bboxes)/4)];
end
t = toc;
|
github | panji530/EDSC-master | hungarian.m | .m | EDSC-master/hungarian.m | 11,781 | utf_8 | 294996aeeca4dadfc427da4f81f8b99d | function [C,T]=hungarian(A)
%HUNGARIAN Solve the Assignment problem using the Hungarian method.
%
%[C,T]=hungarian(A)
%A - a square cost matrix.
%C - the optimal assignment.
%T - the cost of the optimal assignment.
%s.t. T = trace(A(C,:)) is minimized over all possible assignments.
% Adapted from the FORTRAN IV code in Carpaneto and Toth, "Algorithm 548:
% Solution of the assignment problem [H]", ACM Transactions on
% Mathematical Software, 6(1):104-111, 1980.
% v1.0 96-06-14. Niclas Borlin, [email protected].
% Department of Computing Science, Ume? University,
% Sweden.
% All standard disclaimers apply.
% A substantial effort was put into this code. If you use it for a
% publication or otherwise, please include an acknowledgement or at least
% notify me by email. /Niclas
[m,n]=size(A);
if (m~=n)
error('HUNGARIAN: Cost matrix must be square!');
end
% Save original cost matrix.
orig=A;
% Reduce matrix.
A=hminired(A);
% Do an initial assignment.
[A,C,U]=hminiass(A);
% Repeat while we have unassigned rows.
while (U(n+1))
% Start with no path, no unchecked zeros, and no unexplored rows.
LR=zeros(1,n);
LC=zeros(1,n);
CH=zeros(1,n);
RH=[zeros(1,n) -1];
% No labelled columns.
SLC=[];
% Start path in first unassigned row.
r=U(n+1);
% Mark row with end-of-path label.
LR(r)=-1;
% Insert row first in labelled row set.
SLR=r;
% Repeat until we manage to find an assignable zero.
while (1)
% If there are free zeros in row r
if (A(r,n+1)~=0)
% ...get column of first free zero.
l=-A(r,n+1);
% If there are more free zeros in row r and row r in not
% yet marked as unexplored..
if (A(r,l)~=0 & RH(r)==0)
% Insert row r first in unexplored list.
RH(r)=RH(n+1);
RH(n+1)=r;
% Mark in which column the next unexplored zero in this row
% is.
CH(r)=-A(r,l);
end
else
% If all rows are explored..
if (RH(n+1)<=0)
% Reduce matrix.
[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);
end
% Re-start with first unexplored row.
r=RH(n+1);
% Get column of next free zero in row r.
l=CH(r);
% Advance "column of next free zero".
CH(r)=-A(r,l);
% If this zero is last in the list..
if (A(r,l)==0)
% ...remove row r from unexplored list.
RH(n+1)=RH(r);
RH(r)=0;
end
end
% While the column l is labelled, i.e. in path.
while (LC(l)~=0)
% If row r is explored..
if (RH(r)==0)
% If all rows are explored..
if (RH(n+1)<=0)
% Reduce cost matrix.
[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR);
end
% Re-start with first unexplored row.
r=RH(n+1);
end
% Get column of next free zero in row r.
l=CH(r);
% Advance "column of next free zero".
CH(r)=-A(r,l);
% If this zero is last in list..
if(A(r,l)==0)
% ...remove row r from unexplored list.
RH(n+1)=RH(r);
RH(r)=0;
end
end
% If the column found is unassigned..
if (C(l)==0)
% Flip all zeros along the path in LR,LC.
[A,C,U]=hmflip(A,C,LC,LR,U,l,r);
% ...and exit to continue with next unassigned row.
break;
else
% ...else add zero to path.
% Label column l with row r.
LC(l)=r;
% Add l to the set of labelled columns.
SLC=[SLC l];
% Continue with the row assigned to column l.
r=C(l);
% Label row r with column l.
LR(r)=l;
% Add r to the set of labelled rows.
SLR=[SLR r];
end
end
end
% Calculate the total cost.
T=sum(orig(logical(sparse(C,1:size(orig,2),1))));
function A=hminired(A)
%HMINIRED Initial reduction of cost matrix for the Hungarian method.
%
%B=assredin(A)
%A - the unreduced cost matris.
%B - the reduced cost matrix with linked zeros in each row.
% v1.0 96-06-13. Niclas Borlin, [email protected].
[m,n]=size(A);
% Subtract column-minimum values from each column.
colMin=min(A);
A=A-colMin(ones(n,1),:);
% Subtract row-minimum values from each row.
rowMin=min(A')';
A=A-rowMin(:,ones(1,n));
% Get positions of all zeros.
[i,j]=find(A==0);
% Extend A to give room for row zero list header column.
A(1,n+1)=0;
for k=1:n
% Get all column in this row.
cols=j(k==i)';
% Insert pointers in matrix.
A(k,[n+1 cols])=[-cols 0];
end
function [A,C,U]=hminiass(A)
%HMINIASS Initial assignment of the Hungarian method.
%
%[B,C,U]=hminiass(A)
%A - the reduced cost matrix.
%B - the reduced cost matrix, with assigned zeros removed from lists.
%C - a vector. C(J)=I means row I is assigned to column J,
% i.e. there is an assigned zero in position I,J.
%U - a vector with a linked list of unassigned rows.
% v1.0 96-06-14. Niclas Borlin, [email protected].
[n,np1]=size(A);
% Initalize return vectors.
C=zeros(1,n);
U=zeros(1,n+1);
% Initialize last/next zero "pointers".
LZ=zeros(1,n);
NZ=zeros(1,n);
for i=1:n
% Set j to first unassigned zero in row i.
lj=n+1;
j=-A(i,lj);
% Repeat until we have no more zeros (j==0) or we find a zero
% in an unassigned column (c(j)==0).
while (C(j)~=0)
% Advance lj and j in zero list.
lj=j;
j=-A(i,lj);
% Stop if we hit end of list.
if (j==0)
break;
end
end
if (j~=0)
% We found a zero in an unassigned column.
% Assign row i to column j.
C(j)=i;
% Remove A(i,j) from unassigned zero list.
A(i,lj)=A(i,j);
% Update next/last unassigned zero pointers.
NZ(i)=-A(i,j);
LZ(i)=lj;
% Indicate A(i,j) is an assigned zero.
A(i,j)=0;
else
% We found no zero in an unassigned column.
% Check all zeros in this row.
lj=n+1;
j=-A(i,lj);
% Check all zeros in this row for a suitable zero in another row.
while (j~=0)
% Check the in the row assigned to this column.
r=C(j);
% Pick up last/next pointers.
lm=LZ(r);
m=NZ(r);
% Check all unchecked zeros in free list of this row.
while (m~=0)
% Stop if we find an unassigned column.
if (C(m)==0)
break;
end
% Advance one step in list.
lm=m;
m=-A(r,lm);
end
if (m==0)
% We failed on row r. Continue with next zero on row i.
lj=j;
j=-A(i,lj);
else
% We found a zero in an unassigned column.
% Replace zero at (r,m) in unassigned list with zero at (r,j)
A(r,lm)=-j;
A(r,j)=A(r,m);
% Update last/next pointers in row r.
NZ(r)=-A(r,m);
LZ(r)=j;
% Mark A(r,m) as an assigned zero in the matrix . . .
A(r,m)=0;
% ...and in the assignment vector.
C(m)=r;
% Remove A(i,j) from unassigned list.
A(i,lj)=A(i,j);
% Update last/next pointers in row r.
NZ(i)=-A(i,j);
LZ(i)=lj;
% Mark A(r,m) as an assigned zero in the matrix . . .
A(i,j)=0;
% ...and in the assignment vector.
C(j)=i;
% Stop search.
break;
end
end
end
end
% Create vector with list of unassigned rows.
% Mark all rows have assignment.
r=zeros(1,n);
rows=C(C~=0);
r(rows)=rows;
empty=find(r==0);
% Create vector with linked list of unassigned rows.
U=zeros(1,n+1);
U([n+1 empty])=[empty 0];
function [A,C,U]=hmflip(A,C,LC,LR,U,l,r)
%HMFLIP Flip assignment state of all zeros along a path.
%
%[A,C,U]=hmflip(A,C,LC,LR,U,l,r)
%Input:
%A - the cost matrix.
%C - the assignment vector.
%LC - the column label vector.
%LR - the row label vector.
%U - the
%r,l - position of last zero in path.
%Output:
%A - updated cost matrix.
%C - updated assignment vector.
%U - updated unassigned row list vector.
% v1.0 96-06-14. Niclas Borlin, [email protected].
n=size(A,1);
while (1)
% Move assignment in column l to row r.
C(l)=r;
% Find zero to be removed from zero list..
% Find zero before this.
m=find(A(r,:)==-l);
% Link past this zero.
A(r,m)=A(r,l);
A(r,l)=0;
% If this was the first zero of the path..
if (LR(r)<0)
...remove row from unassigned row list and return.
U(n+1)=U(r);
U(r)=0;
return;
else
% Move back in this row along the path and get column of next zero.
l=LR(r);
% Insert zero at (r,l) first in zero list.
A(r,l)=A(r,n+1);
A(r,n+1)=-l;
% Continue back along the column to get row of next zero in path.
r=LC(l);
end
end
function [A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)
%HMREDUCE Reduce parts of cost matrix in the Hungerian method.
%
%[A,CH,RH]=hmreduce(A,CH,RH,LC,LR,SLC,SLR)
%Input:
%A - Cost matrix.
%CH - vector of column of 'next zeros' in each row.
%RH - vector with list of unexplored rows.
%LC - column labels.
%RC - row labels.
%SLC - set of column labels.
%SLR - set of row labels.
%
%Output:
%A - Reduced cost matrix.
%CH - Updated vector of 'next zeros' in each row.
%RH - Updated vector of unexplored rows.
% v1.0 96-06-14. Niclas Borlin, [email protected].
n=size(A,1);
% Find which rows are covered, i.e. unlabelled.
coveredRows=LR==0;
% Find which columns are covered, i.e. labelled.
coveredCols=LC~=0;
r=find(~coveredRows);
c=find(~coveredCols);
% Get minimum of uncovered elements.
m=min(min(A(r,c)));
% Subtract minimum from all uncovered elements.
A(r,c)=A(r,c)-m;
% Check all uncovered columns..
for j=c
% ...and uncovered rows in path order..
for i=SLR
% If this is a (new) zero..
if (A(i,j)==0)
% If the row is not in unexplored list..
if (RH(i)==0)
% ...insert it first in unexplored list.
RH(i)=RH(n+1);
RH(n+1)=i;
% Mark this zero as "next free" in this row.
CH(i)=j;
end
% Find last unassigned zero on row I.
row=A(i,:);
colsInList=-row(row<0);
if (length(colsInList)==0)
% No zeros in the list.
l=n+1;
else
l=colsInList(row(colsInList)==0);
end
% Append this zero to end of list.
A(i,l)=-j;
end
end
end
% Add minimum to all doubly covered elements.
r=find(coveredRows);
c=find(coveredCols);
% Take care of the zeros we will remove.
[i,j]=find(A(r,c)<=0);
i=r(i);
j=c(j);
for k=1:length(i)
% Find zero before this in this row.
lj=find(A(i(k),:)==-j(k));
% Link past it.
A(i(k),lj)=A(i(k),j(k));
% Mark it as assigned.
A(i(k),j(k))=0;
end
A(r,c)=A(r,c)+m; |
github | panji530/EDSC-master | dataProjection.m | .m | EDSC-master/dataProjection.m | 733 | utf_8 | 608c1dd2735280c008ffa8c973aff3d2 | %--------------------------------------------------------------------------
% This function takes the D x N data matrix with columns indicating
% different data points and project the D dimensional data into a r
% dimensional subspace using PCA.
% X: D x N matrix of N data points
% r: dimension of the PCA projection, if r = 0, then no projection
% Xp: r x N matrix of N projectred data points
%--------------------------------------------------------------------------
% Copyright @ Ehsan Elhamifar, 2012
%--------------------------------------------------------------------------
function Xp = DataProjection(X,r)
if (nargin < 2)
r = 0;
end
if (r == 0)
Xp = X;
else
[U,~,~] = svd(X,0);
Xp = U(:,1:r)' * X;
end
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | chuongtrinh.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/chuongtrinh.m | 4,326 | utf_8 | 9aa6e0fba6419280402c840c53ddc448 | function varargout = chuongtrinh(varargin)
% CHUONGTRINH MATLAB code for chuongtrinh.fig
% CHUONGTRINH, by itself, creates a new CHUONGTRINH or raises the existing
% singleton*.
%
% H = CHUONGTRINH returns the handle to a new CHUONGTRINH or the handle to
% the existing singleton*.
%
% CHUONGTRINH('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHUONGTRINH.M with the given input arguments.
%
% CHUONGTRINH('Property','Value',...) creates a new CHUONGTRINH or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before chuongtrinh_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to chuongtrinh_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 chuongtrinh
% Last Modified by GUIDE v2.5 29-Aug-2017 10:44:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @chuongtrinh_OpeningFcn, ...
'gui_OutputFcn', @chuongtrinh_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 chuongtrinh is made visible.
function chuongtrinh_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 chuongtrinh (see VARARGIN)
% Choose default command line output for chuongtrinh
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
addpath('./params/');
addpath('./libs/');
addpath('./libsvm-master/matlab');
start_i=imread('xinchonanh.png');
axes(handles.axes1);
imshow(start_i);
% UIWAIT makes chuongtrinh wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = chuongtrinh_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 btnChonanh.
function btnChonanh_Callback(hObject, eventdata, handles)
% hObject handle to btnChonanh (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('.\image','Xin vui long chon anh...');
I=imread([pathname,filename]);
imshow(I);
assignin('base','I',I)
% --- Executes on button press in btnNhandang.
function btnNhandang_Callback(hObject, eventdata, handles)
% hObject handle to btnNhandang (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
evalin('base','nhandien');
% --- Executes on button press in btnthoat.
function btnthoat_Callback(hObject, eventdata, handles)
% hObject handle to btnthoat (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close all
% --- Executes on button press in btntrain.
function btntrain_Callback(hObject, eventdata, handles)
% hObject handle to btntrain (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
eval('train');
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | plot_DETcurve.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/plot_DETcurve.m | 5,510 | utf_8 | 6c913ccc7db9a1ed012aa94ead1116cd | function plot_DETcurve(models, model_names,pos_path, neg_path)
% PLOT_DETCURVE function to compute de DET plot given a set of models
%
% INPUT:
% models: SVM models to test (as a row vector)
% model_names: names of the models to use it in the DET_plot legends
% (as cell array)
% pos/neg path: path to pos/neg images
%
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: 09-Nov-2013 22:45:23 $
%$ Revision : 1.04 $
%% FILENAME : performance.m
% if paths not specified by parameters
if nargin < 3
pos_path = uigetdir('.\images','Select positive test image path');
neg_path = uigetdir('.\images','Select negative test image path');
if isa(neg_path,'double') || isa(pos_path,'double')
cprintf('Errors','Invalid paths...\nexiting...\n\n')
return
end
end
det_figure_handler = figure('name','DET curves');
set(det_figure_handler,'Visible','off');
det_plot_handlers = zeros(1,max(size(models)));
color = ['b','r','g','y'];
for m_index=1:max(size(models))
hold on;
model = models(m_index);
% getting classification scores
[p_scores, n_scores] = get_scores(model,pos_path,neg_path);
% Plot scores distribution as a Histogram
positives = max(size(p_scores));
negatives = max(size(n_scores));
scores = zeros(min(positives, negatives),2);
for i=1:size(scores)
scores(i,1) = p_scores(i);
scores(i,2) = n_scores(i);
end
figure('name', sprintf('model %s scores distribution',model_names{m_index})); hist(scores);
% Compute Pmiss and Pfa from experimental detection output scores
[P_miss,P_fppw] = Compute_DET(p_scores,n_scores);
% Plot the detection error trade-off
figure(det_figure_handler);
thick = 2;
det_plot_handler = Plot_DET(P_miss,P_fppw,color(m_index)', thick);
det_plot_handlers(m_index) = det_plot_handler;
% Plot the optimum point for the detector
C_miss = 1;
C_fppw = 1;
P_target = 0.5;
Set_DCF(C_miss,C_fppw,P_target);
[DCF_opt, Popt_miss, Popt_fa] = Min_DCF(P_miss,P_fppw);
fprintf('Optimal Decision Cost Function for %s = %d\n',model_names{m_index},DCF_opt)
Plot_DET (Popt_miss,Popt_fa,'ko');
end
legend(det_plot_handlers, model_names);
end
function [p_scores, n_scores] = get_scores(model,pos_path, neg_path)
% Tests a (lib)SVM classifier from the specified images paths
%
% ok: number of correct classifications
% ko: number of wrong classifications
% positive / negative images_path: paths of the images to test
% model: SVMmodel to use.
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: 2013/11/09 $
%$ Revision: 1.2 $
[positive_images, negative_images] = get_files(-1,-1,{pos_path,neg_path});
total_pos_windows = numel(positive_images);
total_neg_windows = numel(negative_images);
%% Init the svm test variables
params = get_params('det_plot_params');
chunk_size = params.chunk_size;
desc_size = params.desc_size;
params = get_params('window_params');
im_h_size = params.height;
im_w_size = params.width;
im_c_depth = params.color_depth;
% ====================================================================
%% Reading all POSITIVE images
% (64x128 images)
% ====================================================================
% SVM scores
p_scores = zeros(total_pos_windows,1);
i = 0;
while i < numel(positive_images)
%% window obtainment
this_chunk = min(chunk_size,numel(positive_images)-i);
windows = uint8(zeros(im_h_size,im_w_size,im_c_depth,this_chunk));
hogs = zeros(this_chunk, desc_size);
labels = ones(size(hogs,1),1);
for l=1:this_chunk
I = imread(positive_images(i+1).name);
windows(:,:,:,l) = get_window(I,im_w_size,im_h_size,'center');
hogs(l,:) = compute_HOG(windows(:,:,:,l),8,2,9);
i = i+1;
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
[~, ~, scores] = ...
svmpredict(labels, hogs, model, '-b 0');
p_scores(i-this_chunk+1:i,:) = scores(:,:);
end
% ====================================================================
%% Reading all NEGATIVE images
% (64x128 windows)
% ====================================================================
n_scores = zeros(total_neg_windows,1);
i = 0;
while i < numel(negative_images)
%% window obtainment
this_chunk = min(chunk_size,numel(negative_images)-i);
windows = uint8(zeros(im_h_size,im_w_size,im_c_depth,this_chunk));
hogs = zeros(this_chunk, desc_size);
labels = ones(size(hogs,1),1)*(-1);
for l=1:this_chunk
I = imread(negative_images(i+1).name);
windows(:,:,:,l) = get_window(I,im_w_size,im_h_size,[1,1]);
hogs(l,:) = compute_HOG(windows(:,:,:,l),8,2,9);
i = i+1;
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
[~, ~, scores] = ...
svmpredict(labels, hogs, model, '-b 0');
n_scores(i-this_chunk+1:i,:) = scores(:,:);
end
end
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | draw_sliding_window.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/draw_sliding_window.m | 3,630 | utf_8 | 2577c102d36999695fc68a9d8324fe2e | function draw_sliding_window(I, model)
% DRAW_SLIDING_WINDOW function that given an image and a model scans
% exhaustively over a scale-space pyramid the image for pedestrians
% drawing the sliding detection window and the confidence probability.
%
% INPUT:
% model: model to test
% I: image to scan
%
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: - $
%$ Revision : 1.00 $
%% FILENAME : draw_sliding_window.m
% Testing if param file exists in the params directory
if exist(['params',filesep,'detect_and_draw.params'],'file')
test_params = load(['params',filesep,'detect_and_draw.params'],'-ascii');
% Testing if param file exists in the current directory
elseif exist('detect_and_draw.params','file')
test_params = load('detect_and_draw.params','-ascii');
% Dialog to select param file
else
[param_file,PathName,~] = uigetfile('*.params','Select parameter file');
if ~isa(param_file,'double')
test_params = load([PathName,filesep,param_file],'-ascii');
else
cprintf('Errors','Missing param file...\nexiting...\n\n');
return
end
end
%% wiring up the param vars
th = test_params(1);
scale = test_params(2);
hog_size = test_params(3);
stride = test_params(4);
% fprintf('Threshold=%f\n',th)
% fprintf('Scale=%f\n',scale)
% fprintf('Descriptor size=%f\n',hog_size)
% fprintf('Window stride=%f\n',stride)
%% color definitions
red = uint8([255,0,0]);
green = uint8([0,255,0]);
%% shape inserters
ok_shapeInserter = ...
vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',green);
ko_shapeInserter = ...
vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',red);
ti = tic;
fprintf('\nbegining the pyramid hog extraction...\n')
[hogs, ~, wxl, coordinates] = get_pyramid_hogs(I, hog_size, scale, stride);
tf = toc(ti);
fprintf('time to extract %d hogs: %d\n', size(hogs,1), tf);
%% refer coordinates to the original image... (Level0)
% for each window in every level...
ind = 1;
for l=1:size(wxl,2)
ws= wxl(l);
for w=1:ws
% compute original coordinates in Level0 image
factor = (scale^(l-1));
coordinates(1,ind) = floor(coordinates(1,ind) * factor);
coordinates(2,ind) = floor(coordinates(2,ind) * factor);
ind = ind + 1;
end
end
%% SVM prediction for all windows...
[predict_labels, ~, probs] = ...
svmpredict(zeros(size(hogs,1),1), hogs, model, '-b 1');
% draw in the original image the detecction window
% red: not detected
% green: detected
for i=1:numel(predict_labels)
[level, ~] = get_window_indices(wxl, i);
% figure('name', sprintf('level %d detection', level));
x = coordinates(1,i);
y = coordinates(2,i);
factor = (scale^(level-1));
rectangle = int32([x,y,64*factor,128*factor]);
if predict_labels(i) == 1 && probs(i) > th
% J = step(ok_shapeInserter, I, rectangle);
% J = insertText(J, [x,y], probs(i), 'FontSize',9,'BoxColor', 'green');
% imshow(J);
% figure(gcf);
%pause(0.5);
disp('ok');
else
disp('mok');
J = step(ko_shapeInserter, I, rectangle);
imshow(J);
figure(gcf);
end
end
% closing all figures...
% close all
end
%% Aux func. to get the level and window number given a linear index
function [level, num_window] = get_window_indices(wxl, w_linear_index)
accum_windows = 0;
for i=1:size(wxl,2)
accum_windows = accum_windows + wxl(i);
if w_linear_index <= accum_windows
level = i;
num_window = accum_windows - w_linear_index;
break
end
end
end |
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | compute_level0_coordinates.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/compute_level0_coordinates.m | 1,067 | utf_8 | d65b971929cc232aad3dc34827e93fe2 |
%% Aux function to compute the windows coordiantes at level 0 pyramid image
function [bb_size, new_cords] = compute_level0_coordinates(wxl, coordinates, inds, scale)
% Consts
bb_width = 64;
bb_height = 128;
% Vars
new_cords = zeros(size(inds,2),2);
bb_size = zeros(size(inds,2),2);
% for each positive window index...
for i=1:size(inds,2)
% linear index of the window
ind = inds(i);
% find the positive window original level
level = 0;
while ind > sum(wxl(1:level))
level = level + 1;
end
% fprintf('Match found at level %d\n', level);
% compute original coordinates in Level0 image
factor = (scale^(level-1));
new_cords(i,1) = floor(coordinates(i,1) * factor);
new_cords(i,2) = floor(coordinates(i,2) * factor);
% Bounding Box resizing?
bb_size(i,1) = ceil(bb_height*factor);
bb_size(i,2) = ceil(bb_width*factor);
end
end |
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | test_svm.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/test_svm.m | 11,053 | utf_8 | 9bfbc961a2df8136aa2b0eb74f485b1d | function statistics = test_svm(model,paths)
% TEST_SVM Tests a (lib)SVM classifier from the specified images paths
%
% INPUT:
% model: SVMmodel to use
% threshold: positive confidence threshold
% paths: positive / negative images_path to test
% //
% windows, descriptor and test parameter configuration is read from their
% corresponding paramteter files. If not found a window prompts for them.
%
% OUTPUT:
% statistics: ok, ko, false_pos, false_neg, true_pos, true_neg
% fppw and miss_rate metrics
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: 2013/11/09 $
%$ Revision: 1.05 $
%% svm testing parameters
get_test_params();
% path stuff
if nargin < 2
positive_images_path = uigetdir('images','Select positive image folder');
negative_images_path = uigetdir('images','Select negative image folder');
if safe
images_path = uigetdir('images','Select base image path');
end
if isa(positive_images_path,'double') || ...
isa(negative_images_path,'double')
cprintf('Errors','Invalid paths...\nexiting...\n\n')
return
end
else
positive_images_path = paths{1};
negative_images_path = paths{2};
if safe
images_path = paths{3};
end
end
%% getting images to test from the specified folders
paths = {positive_images_path,negative_images_path};
[positive_images, negative_images] = get_files(pos_instances,neg_instances, paths);
% ====================================================================
%% Reading all POSITIVE images & computing the descriptor
% (64x128 images)
% ====================================================================
%% Computing HOG descriptor for all images (in chunks)
pos_start_time = tic;
false_negatives = 0;
true_positives = 0;
i = 0;
while i < numel(positive_images)
%% window obtainment
this_chunk = min(pos_chunk_size,numel(positive_images)-i);
windows = uint8(zeros(height,width,depth,this_chunk));
hogs = zeros(this_chunk, descriptor_size);
labels = ones(size(hogs,1),1);
for l=1:this_chunk
I = imread(positive_images(i+1).name);
windows(:,:,:,l) = get_window(I,width,height, 'center');
hogs(l,:) = compute_HOG(windows(:,:,:,l),cell_size,block_size,n_bins);
i = i+1;
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
[predict_labels, ~, probs] = ...
svmpredict(labels, hogs, model, '-b 1');
%% counting and copying
for l=1:size(predict_labels)
predict_label = predict_labels(l);
if probs(l,1) >= 0.1
ok = ok + 1;
true_positives = true_positives + 1;
else
ko = ko + 1;
false_negatives = false_negatives + 1;
% saving hard image for further retrain
if safe
[~, name, ext] = fileparts(positive_images(i).name);
saving_path = [images_path,'/hard_examples/false_neg/',...
name,...
'_n_wind_',num2str(l), ext];
% writting image
imwrite(windows(:,:,:,l), saving_path);
end
end
end
end
% hog extraction elapsed time
pos_elapsed_time = toc(pos_start_time);
fprintf('Elapsed time to classify positive images: %f seconds.\n',pos_elapsed_time);
% ====================================================================
%% Reading all NEGATIVE images & computing the descriptor
% Exhaustive search for hard examples
% (space-scaled 64x128 windows)
% ====================================================================
num_neg_images = size(negative_images,1);
if strcmp(neg_method, 'pyramid')
num_neg_windows = ...
get_negative_windows_count(negative_images);
elseif strcmp(neg_method, 'windows')
num_neg_windows = num_neg_images*neg_chunk_size;
end
fprintf('testing with %d negative images and %d negative windows\n', num_neg_images,num_neg_windows);
%% Computing HOG descriptor for all images (in chunks)
neg_start_time = tic;
false_positives = 0;
true_negatives = 0;
i = 0;
while i < numel(negative_images)
%% window obtaintion
% All pyramid HOGS
if strcmp(neg_method, 'pyramid')
I = imread(negative_images(i+1).name);
%% temporal
[h,w,~] = size(I);
if max(h,w) >= 160
ratio = max(96/w,160/h);
I = imresize(I,ratio);
end
%% fin temporal
[hogs, windows, wxl] = get_pyramid_hogs(I, descriptor_size, scale, stride);
labels = ones(size(hogs,1),1).*(-1);
i = i+1;
% random window HOG
elseif strcmp(neg_method,'windows')
this_chunk = min(neg_chunk_size, numel(negative_images)-i);
windows = uint8(zeros(height,width,depth,this_chunk));
hogs = zeros(this_chunk, descriptor_size);
labels = ones(size(hogs,1),1).*(-1);
for l=1:this_chunk
I = imread(negative_images(i+1).name);
windows(:,:,:,l) = get_window(I,width,height, 'center');
hogs(l,:) = compute_HOG(windows(:,:,:,l),cell_size,block_size,n_bins);
i = i+1;
end
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
[predict_labels, ~, probs] = ...
svmpredict(labels, hogs, model, '-b 1');
%% updating statistics
for l=1:size(predict_labels)
predict_label = predict_labels(l);
if probs(l,1) < 0.1
ok = ok + 1;
true_negatives = true_negatives + 1;
else
ko = ko + 1;
false_positives = false_positives + 1;
if safe
% saving hard image for further retrain
[~, name, ext] = fileparts(negative_images(i).name);
if strcmp(neg_method, 'pyramid')
[level, num_image] = get_window_indices(wxl, l);
saving_path = [images_path,'/hard_examples/false_pos/',...
name,...
'_l',num2str(level),...
'_w',num2str(num_image),ext];
else
saving_path = [images_path,'/hard_examples/false_pos/',...
name,...
'_n_wind_',num2str(l), ext];
end
% writting image
imwrite(windows(:,:,:,l), saving_path);
end
end
end
end
% hog extraction elapsed time
neg_elapsed_time = toc(neg_start_time);
fprintf('Elapsed time to classify negative images: %f seconds.\n',neg_elapsed_time);
%% Printing gloabl results
precision = true_positives/(true_positives+false_positives);
recall = true_positives/(true_positives+false_negatives);
fprintf('oks: %d \n',ok)
fprintf('kos: %d \n',ko)
fprintf('false positives: %d \n',false_positives)
fprintf('false negatives: %d \n',false_negatives)
fprintf('true positives: %d \n',true_positives)
fprintf('true negatives: %d \n',true_negatives)
fprintf('mis rate: %d \n',false_negatives / (true_positives + false_negatives))
fprintf('fppw: %d \n',false_positives / (ok + ko))
fprintf('Precision: %d \n',precision)
fprintf('Recall: %d \n',recall)
fprintf('F score: %d \n',2*((precision*recall)/(precision+recall)))
% preparing values to return
statistics = containers.Map;
statistics('oks') = ok;
statistics('kos') = ok;
statistics('fp') = false_positives;
statistics('tp') = true_positives;
statistics('fn') = false_negatives;
statistics('tn') = true_negatives;
statistics('miss_rate') = false_negatives / (true_positives + false_negatives);
statistics('fppw') = false_positives / (ok + ko);
statistics('precision') = precision;
statistics('recall') = recall;
statistics('fscore') = 2*((precision*recall)/(precision+recall));
% ---------------------------------------------------------------------
%% Aux function to obtain the test parameters
% ---------------------------------------------------------------------
function get_test_params()
test_params = get_params('test_svm_params');
pos_chunk_size = test_params.pos_chunk_size;
neg_chunk_size = test_params.neg_chunk_size;
scale = test_params.scale;
stride = test_params.stride;
threshold = test_params.threshold;
neg_method = test_params.neg_window_method;
safe = test_params.safe;
neg_instances = test_params.neg_instances;
pos_instances = test_params.pos_instances;
w_params = get_params('window_params');
depth = w_params.color_depth;
width = w_params.width;
height = w_params.height;
desc_params = get_params('desc_params');
cell_size = desc_params.cell_size;
block_size = desc_params.block_size;
n_bins = desc_params.n_bins;
desp = 1;
n_v_cells = floor(height/cell_size);
n_h_cells = floor(width/cell_size);
hist_size = block_size*block_size*n_bins;
descriptor_size = hist_size*(n_v_cells-block_size+desp)*(n_h_cells-block_size+desp);
ok = 0;
ko = 0;
end
end
%% Aux function to know how many windows we'll have...
function count = get_negative_windows_count(negative_images)
% computing number of levels in the pyramid
count = 0;
for i=1:numel(negative_images)
I = imread(negative_images(i).name);
%% temporal
[h,w,~] = size(I);
if max(h,w) >= 160
ratio = max(96/w,160/h);
I = imresize(I,ratio);
end
%% fin temporal
[~, windows] = get_pyramid_dimensions(I);
count = count + windows;
end
end
%% Aux function to know how the windows indices...
function [level, num_window] = get_window_indices(wxl, w_linear_index)
accum_windows = 0;
for i=1:size(wxl,2)
accum_windows = accum_windows + wxl(i);
if w_linear_index <= accum_windows
level = i;
num_window = accum_windows - w_linear_index;
break
end
end
end
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | test_svm_PCA.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/test_svm_PCA.m | 11,226 | utf_8 | 515c2df08059e5339874b04bb212cf82 | function statistics = test_svm_PCA(model,Ureduce, paths)
% TEST_SVM_PCA Tests a (lib)SVM classifier from the specified images paths
% reducing first each hog matrix to a dimensionality reduced
% version.
%
% INPUT:
% model: SVMmodel to use
% threshold: positive confidence threshold
% paths: positive / negative images_path to test
% //
% windows, descriptor and test parameter configuration is read from their
% corresponding paramteter files. If not found a window prompts for them.
%
% OUTPUT:
% statistics: ok, ko, false_pos, false_neg, true_pos, true_neg
% fppw and miss_rate metrics
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: 2013/11/09 $
%$ Revision: 1.05 $
%% svm testing parameters
get_test_params();
% path stuff
if nargin < 3
positive_images_path = uigetdir('images','Select positive image folder');
negative_images_path = uigetdir('images','Select negative image folder');
if safe
images_path = uigetdir('images','Select base image path');
end
if isa(positive_images_path,'double') || ...
isa(negative_images_path,'double')
cprintf('Errors','Invalid paths...\nexiting...\n\n')
return
end
else
positive_images_path = paths{1};
negative_images_path = paths{2};
if safe
images_path = paths{3};
end
end
%% getting images to test from the specified folders
paths = {positive_images_path,negative_images_path};
[positive_images, negative_images] = get_files(pos_instances,neg_instances, paths);
% ====================================================================
%% Reading all POSITIVE images & computing the descriptor
% (64x128 images)
% ====================================================================
%% Computing HOG descriptor for all images (in chunks)
pos_start_time = tic;
false_negatives = 0;
true_positives = 0;
i = 0;
while i < numel(positive_images)
%% window obtainment
this_chunk = min(pos_chunk_size,numel(positive_images)-i);
windows = uint8(zeros(height,width,depth,this_chunk));
hogs = zeros(this_chunk, descriptor_size);
labels = ones(size(hogs,1),1);
for l=1:this_chunk
I = imread(positive_images(i+1).name);
windows(:,:,:,l) = get_window(I,width,height, 'center');
hogs(l,:) = compute_HOG(windows(:,:,:,l),cell_size,block_size,n_bins);
i = i+1;
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
hogs = hogs*Ureduce;
[predict_labels, ~, probs] = ...
svmpredict(labels, hogs, model, '-b 1');
%% counting and copying
for l=1:size(predict_labels)
predict_label = predict_labels(l);
if probs(l,1) >= 0.1
ok = ok + 1;
true_positives = true_positives + 1;
else
ko = ko + 1;
false_negatives = false_negatives + 1;
% saving hard image for further retrain
if safe
[~, name, ext] = fileparts(positive_images(i).name);
saving_path = [images_path,'/hard_examples/false_neg/',...
name,...
'_n_wind_',num2str(l), ext];
% writting image
imwrite(windows(:,:,:,l), saving_path);
end
end
end
end
% hog extraction elapsed time
pos_elapsed_time = toc(pos_start_time);
fprintf('Elapsed time to classify positive images: %f seconds.\n',pos_elapsed_time);
% ====================================================================
%% Reading all NEGATIVE images & computing the descriptor
% Exhaustive search for hard examples
% (space-scaled 64x128 windows)
% ====================================================================
num_neg_images = size(negative_images,1);
if strcmp(neg_method, 'pyramid')
num_neg_windows = ...
get_negative_windows_count(negative_images);
elseif strcmp(neg_method, 'windows')
num_neg_windows = num_neg_images*neg_chunk_size;
end
fprintf('testing with %d negative images and %d negative windows\n', num_neg_images,num_neg_windows);
%% Computing HOG descriptor for all images (in chunks)
neg_start_time = tic;
false_positives = 0;
true_negatives = 0;
i = 0;
while i < numel(negative_images)
%% window obtaintion
% All pyramid HOGS
if strcmp(neg_method, 'pyramid')
I = imread(negative_images(i+1).name);
%% temporal
[h,w,~] = size(I);
if max(h,w) >= 160
ratio = max(96/w,160/h);
I = imresize(I,ratio);
end
%% fin temporal
[hogs, windows, wxl] = get_pyramid_hogs(I, descriptor_size, scale, stride);
labels = ones(size(hogs,1),1).*(-1);
i = i+1;
% random window HOG
elseif strcmp(neg_method,'windows')
this_chunk = min(neg_chunk_size, numel(negative_images)-i);
windows = uint8(zeros(height,width,depth,this_chunk));
hogs = zeros(this_chunk, descriptor_size);
labels = ones(size(hogs,1),1).*(-1);
for l=1:this_chunk
I = imread(negative_images(i+1).name);
windows(:,:,:,l) = get_window(I,width,height, 'center');
hogs(l,:) = compute_HOG(windows(:,:,:,l),cell_size,block_size,n_bins);
i = i+1;
end
end
% just for fixing GUI freezing due to unic thread MatLab issue
drawnow;
%% prediction
hogs = hogs*Ureduce;
[predict_labels, ~, probs] = ...
svmpredict(labels, hogs, model, '-b 1');
%% updating statistics
for l=1:size(predict_labels)
predict_label = predict_labels(l);
if probs(l,1) < 0.1
ok = ok + 1;
true_negatives = true_negatives + 1;
else
ko = ko + 1;
false_positives = false_positives + 1;
if safe
% saving hard image for further retrain
[~, name, ext] = fileparts(negative_images(i).name);
if strcmp(neg_method, 'pyramid')
[level, num_image] = get_window_indices(wxl, l);
saving_path = [images_path,'/hard_examples/false_pos/',...
name,...
'_l',num2str(level),...
'_w',num2str(num_image),ext];
else
saving_path = [images_path,'/hard_examples/false_pos/',...
name,...
'_n_wind_',num2str(l), ext];
end
% writting image
imwrite(windows(:,:,:,l), saving_path);
end
end
end
end
% hog extraction elapsed time
neg_elapsed_time = toc(neg_start_time);
fprintf('Elapsed time to classify negative images: %f seconds.\n',neg_elapsed_time);
%% Printing gloabl results
precision = true_positives/(true_positives+false_positives);
recall = true_positives/(true_positives+false_negatives);
fprintf('oks: %d \n',ok)
fprintf('kos: %d \n',ko)
fprintf('false positives: %d \n',false_positives)
fprintf('false negatives: %d \n',false_negatives)
fprintf('true positives: %d \n',true_positives)
fprintf('true negatives: %d \n',true_negatives)
fprintf('mis rate: %d \n',false_negatives / (true_positives + false_negatives))
fprintf('fppw: %d \n',false_positives / (ok + ko))
fprintf('Precision: %d \n',precision)
fprintf('Recall: %d \n',recall)
fprintf('F score: %d \n',2*((precision*recall)/(precision+recall)))
% preparing values to return
statistics = containers.Map;
statistics('oks') = ok;
statistics('kos') = ok;
statistics('fp') = false_positives;
statistics('tp') = true_positives;
statistics('fn') = false_negatives;
statistics('tn') = true_negatives;
statistics('miss_rate') = false_negatives / (true_positives + false_negatives);
statistics('fppw') = false_positives / (ok + ko);
statistics('precision') = precision;
statistics('recall') = recall;
statistics('fscore') = 2*((precision*recall)/(precision+recall));
% ---------------------------------------------------------------------
%% Aux function to obtain the test parameters
% ---------------------------------------------------------------------
function get_test_params()
test_params = get_params('test_svm_params');
pos_chunk_size = test_params.pos_chunk_size;
neg_chunk_size = test_params.neg_chunk_size;
scale = test_params.scale;
stride = test_params.stride;
threshold = test_params.threshold;
neg_method = test_params.neg_window_method;
safe = test_params.safe;
neg_instances = test_params.neg_instances;
pos_instances = test_params.pos_instances;
w_params = get_params('window_params');
depth = w_params.color_depth;
width = w_params.width;
height = w_params.height;
desc_params = get_params('desc_params');
cell_size = desc_params.cell_size;
block_size = desc_params.block_size;
n_bins = desc_params.n_bins;
desp = 1;
n_v_cells = floor(height/cell_size);
n_h_cells = floor(width/cell_size);
hist_size = block_size*block_size*n_bins;
descriptor_size = hist_size*(n_v_cells-block_size+desp)*(n_h_cells-block_size+desp);
ok = 0;
ko = 0;
end
end
%% Aux function to know how many windows we'll have...
function count = get_negative_windows_count(negative_images)
% computing number of levels in the pyramid
count = 0;
for i=1:numel(negative_images)
I = imread(negative_images(i).name);
%% temporal
[h,w,~] = size(I);
if max(h,w) >= 160
ratio = max(96/w,160/h);
I = imresize(I,ratio);
end
%% fin temporal
[~, windows] = get_pyramid_dimensions(I);
count = count + windows;
end
end
%% Aux function to know how the windows indices...
function [level, num_window] = get_window_indices(wxl, w_linear_index)
accum_windows = 0;
for i=1:size(wxl,2)
accum_windows = accum_windows + wxl(i);
if w_linear_index <= accum_windows
level = i;
num_window = accum_windows - w_linear_index;
break
end
end
end
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | non_max_suppression.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/non_max_suppression.m | 1,983 | utf_8 | f929c2cfe27c04ea18291377d6a6c143 | function max_indices = non_max_suppression(coords, probs, bb_sizes)
% NON_MAX_SUPRESION applies non maximum suppression to get the
% most confident detections over a proximity area.
% Input: window coordiantes, window classification probabilities and
% window size referenced to the level 0 pyramid layer.
% Output: the most confident window indices
%$ Author: Jose Marcos Rodriguez $
%$ Date: 23-Nov-2013 12:37:16 $
%$ Revision : 1.00 $
%% FILENAME : non_max_supresion.m
MIN_DIST = 1024;
MAX_AREA = 128*64/6;
max_indices = [];
m = size(coords,1);
indices = 1:m;
% while we have nearby windows not suppressed...
while size(indices, 2) > 1
nearby_window_indices = indices(1);
% for all remaining indices...
for i=2:size(indices,2)
% we search the nearby windows
d = distance(coords(indices(1),:), coords(indices(i),:));
if d < MIN_DIST
nearby_window_indices = [nearby_window_indices, indices(i)];
end
area = overlap(coords(indices(1),:), coords(indices(i),:), bb_sizes(indices(i),:));
if area > MAX_AREA
nearby_window_indices = [nearby_window_indices, indices(i)];
end
end
% from the nearby windows we only keep the most confident one
nearby_probs = probs(nearby_window_indices,1);
max_indx = nearby_window_indices(max(nearby_probs) == nearby_probs);
max_indices = [max_indices, max_indx];
% removing from indices all the treated ones
for k=1:size(nearby_window_indices,2)
indices = indices(indices ~= nearby_window_indices(k));
end
end
end
function d = distance(coords1, coords2)
d = sum((coords1-coords2).^2);
end
function overlapping_area = overlap(coords1, coords2, bb_size2)
delta = coords1-coords2;
delta_x = delta(1);
delta_y = delta(2);
h = bb_size2(1);
w = bb_size2(2);
overlapping_area = w*h - abs(delta_x*w) - abs(delta_y*h) + abs(delta_x*delta_y);
end
|
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | static_detector.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/static_detector.m | 5,315 | utf_8 | c2e656c452e2addd5dc511b90b999441 | function static_detector(I,model)
% STATIC_DETECTOR given a folder containing PNG or JPG images applies
% the specified libSVM model to scan through every image
% for pedestrians in a sliding window basis.
%
% All the parameters are hard coded to guaratee independence from
% external files, assuming once this function in run the whole set of
% parameters are well known and no further experimentation is needed.
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: 05-Dec-2013 23:09:05 $
%$ Revision : 1.00 $
%% FILENAME : static_detector.m
%% VARS
hog_size = 3780;
scale = 1.2;
stride = 8;
show_all = false;
draw_all = false;
%% color definitions
green = uint8([0,255,0]);
yellow = uint8([255,255,0]);
%% shape inserters
ok_shapeInserter = ...
vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',green);
other_shapeInserter = ...
vision.ShapeInserter('BorderColor','Custom','CustomBorderColor',yellow);
%images_path = uigetdir('.\..','Select image folder');
%% image reading
% jpgs = rdir(strcat(images_path,filesep,'*.jpg'));
% pngs = rdir(strcat(images_path,filesep,'*.png'));
% images = [jpgs, pngs];
% num_images = size(images,1);
%for i=1:num_images
%fprintf('-------------------------------------------\n')
%disp(images(i).name);
%I = imread(images(i).name);
%% Reescale
[h,w,~] = size(I);
rscale = min(w/96, h/160);
I = imresize(I, 1.2/rscale);
%% HOG extraction for all image windows
ti = tic;
fprintf('\nbegining the pyramid hog extraction...\n')
[hogs, windows, wxl, coordinates] = get_pyramid_hogs(I, hog_size, scale, stride);
tf = toc(ti);
fprintf('time to extract %d hogs: %d\n', size(hogs,1), tf);
%% SVM prediction for all windows...
[predict_labels, ~, probs] = ...
svmpredict(zeros(size(hogs,1),1), hogs, model, '-b 1');
%% filtering only positives windows instances
% index of positives windows
range = 1:max(size(predict_labels));
pos_indxs = range(predict_labels == 1);
%pos_indxs = range(probs(1) >= 0.8);
% positive match information
coordinates = coordinates';
coordinates = coordinates(pos_indxs,:);
probs = probs(pos_indxs,:);
%% Computing level 0 coordinates for drawing
[bb_size, l0_coordinates] = compute_level0_coordinates(wxl, coordinates, pos_indxs, scale);
%% Showing all positive windows in separate figures
if show_all
windows = windows(:,:,:,pos_indxs);
for w=1:size(pos_indxs,2)
figure('name',sprintf('x=%d, y=%d', l0_coordinates(w,1),l0_coordinates(w,2)));
% figure('name',sprintf('x=%d, y=%d', bb_size(w,1),bb_size(w,2)));
ii = insertText(windows(:,:,:,w), [1,1], probs(w), 'FontSize',9,'BoxColor', 'green');
imshow(ii)
end
end
%% Drawing detections over the original image
%draw = I;
shape_inserter = other_shapeInserter;
if ~draw_all
shape_inserter = ok_shapeInserter;
%% non-max-suppression!
max_indxs = non_max_suppression(l0_coordinates, probs, bb_size);
pos_indxs = pos_indxs(max_indxs);
l0_coordinates = l0_coordinates(max_indxs,:);
bb_size = bb_size(max_indxs, :);
probs = probs(max_indxs,:);
end
draw = I;
for w=1:size(pos_indxs,2)
%% Drawing the rectangle on the original image
x = l0_coordinates(w,1);
y = l0_coordinates(w,2);
% Rectangle conf
bb_height = bb_size(w,1);
bb_width = bb_size(w,2);
rectangle = int32([x,y,bb_width,bb_height]);
draw = step(shape_inserter, draw, rectangle);
draw = insertText(draw, [x,y+bb_height], probs(w), 'FontSize',9,'BoxColor', 'green');
end
% Showing image with all the detection boxes
imshow(draw);
figure(gcf);
% pause;
%end
end
%% Aux function to compute the windows coordiantes at level 0 pyramid image
function [bb_size, new_cords] = compute_level0_coordinates(wxl, coordinates, inds, scale)
% Consts
bb_width = 64;
bb_height = 128;
% Vars
new_cords = zeros(size(inds,2),2);
bb_size = zeros(size(inds,2),2);
% for each positive window index...
for i=1:size(inds,2)
% linear index of the window
ind = inds(i);
% find the positive window original level
level = 0;
while ind > sum(wxl(1:level))
level = level + 1;
end
% fprintf('Match found at level %d\n', level);
% compute original coordinates in Level0 image
factor = (scale^(level-1));
new_cords(i,1) = floor(coordinates(i,1) * factor);
new_cords(i,2) = floor(coordinates(i,2) * factor);
% Bounding Box resizing?
bb_size(i,1) = ceil(bb_height*factor);
bb_size(i,2) = ceil(bb_width*factor);
end
end |
github | voquocduy/Pedestrian-Detection-using-Hog-Svm-Matab-master | get_negative_windows.m | .m | Pedestrian-Detection-using-Hog-Svm-Matab-master/get_negative_windows.m | 1,915 | utf_8 | ecdfa7fe0e0ffad38158346f78fed842 |
function get_negative_windows(num_random_windows, num_images)
% GET_NEGATIVE_WINDOWS retrieves random windows from the original negative
% image set and saves the window in the specified
% folder when prompted.
% INPUT:
% num_random_windows: random window samples per image
% num_images: number of images from where to sample windows.
%
%$ Author: Jose Marcos Rodriguez $
%$ Date: N/D $
%$ Revision : 1.00 $
%% FILENAME : get_negative_windows.m
% Paths
negative_images_path = uigetdir('.\images','Select original images path');
windows_dst_path = uigetdir('.\images','Select destination path');
if isa(negative_images_path,'double') || isa(windows_dst_path,'double')
cprintf('Errors','Invalid paths...\nexiting...\n\n')
return
end
negative_images = dir(negative_images_path);
negative_images = negative_images(3:end);
if num_images < 1
fprintf('\ngetting all available images\n')
num_images = numel(negative_images);
elseif num_images > numel(negative_images)
fprintf('not enought images...\ngetting al available images\n')
num_images = numel(negative_images);
end
for i=1:num_images
for nrw = 1:num_random_windows
% getting random window from negative image
file_name = ...
strcat(negative_images_path,filesep,negative_images(i).name);
I = imread(file_name);
random_image_window = get_window(I,64,128, 'random');
% making saving path
[~, name, ext] = fileparts(file_name);
file_saving_name = ...
strcat(windows_dst_path, filesep,strcat(name,'_',sprintf('%02d',nrw)),ext);
% saving image...
imwrite(random_image_window, file_saving_name);
end
end
|
github | SkoltechRobotics/pcl-master | plot_camera_poses.m | .m | pcl-master/gpu/kinfu/tools/plot_camera_poses.m | 3,407 | utf_8 | d210c150da98c3f4667f2c1e8d4eb6d2 | % Copyright (c) 2014-, Open Perception, Inc.
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions
% are met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above
% copyright notice, this list of conditions and the following
% disclaimer in the documentation and/or other materials provided
% with the distribution.
% * Neither the name of the copyright holder(s) nor the names of its
% contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
% "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
% COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
% INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
% BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
% CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
% ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
% Author: Marco Paladini <[email protected]>
% sample octave script to load camera poses from file and plot them
% example usage: run 'pcl_kinfu_app -save_pose camera.csv' to save
% camera poses in a 'camera.csv' file
% run octave and cd into the directory where this script resides
% and call plot_camera_poses('<path-to-camera.csv-file>')
function plot_camera_poses(filename)
poses=load(filename);
%% show data on a 2D graph
h=figure();
plot(poses,'*-');
legend('x','y','z','qw','qx','qy','qz');
%% show data as 3D axis
h=figure();
for n=1:size(poses,1)
t=poses(n,1:3);
q=poses(n,4:7);
r=q2rot(q);
coord(h,r,t);
end
octave_axis_equal(h);
%% prevent Octave from quitting if called from the command line
input('Press enter to continue');
end
function coord(h,r,t)
figure(h);
hold on;
c={'r','g','b'};
p=0.1*[1 0 0;0 1 0;0 0 1];
for n=1:3
a=r*p(n,:)';
plot3([t(1),t(1)+a(1)], [t(2),t(2)+a(2)], [t(3),t(3)+a(3)], 'color', c{n});
end
end
function R=q2rot(q)
% conversion code from http://en.wikipedia.org/wiki/Rotation_matrix%Quaternion
Nq = q(1)^2 + q(2)^2 + q(3)^2 + q(4)^2;
if Nq>0; s=2/Nq; else s=0; end
X = q(2)*s; Y = q(3)*s; Z = q(4)*s;
wX = q(1)*X; wY = q(1)*Y; wZ = q(1)*Z;
xX = q(2)*X; xY = q(2)*Y; xZ = q(2)*Z;
yY = q(3)*Y; yZ = q(3)*Z; zZ = q(4)*Z;
R=[ 1.0-(yY+zZ) xY-wZ xZ+wY ;
xY+wZ 1.0-(xX+zZ) yZ-wX ;
xZ-wY yZ+wX 1.0-(xX+yY) ];
end
function octave_axis_equal(h)
% workaround for axis auto not working in 3d
% tanks http://octave.1599824.n4.nabble.com/axis-equal-help-tp1636701p1636702.html
figure(h);
xl = get (gca, 'xlim');
yl = get (gca, 'ylim');
zl = get (gca, 'zlim');
span = max ([diff(xl), diff(yl), diff(zl)]);
xlim (mean (xl) + span*[-0.5, 0.5])
ylim (mean (yl) + span*[-0.5, 0.5])
zlim (mean (zl) + span*[-0.5, 0.5])
end
|
github | LarsonLab/UTEMRI_Brain-master | precon_3dute_pfile_bartv300_allec.m | .m | UTEMRI_Brain-master/ImageReconstruction/precon_3dute_pfile_bartv300_allec.m | 13,757 | utf_8 | 78e61bbb10ca3b8c81f5817eb027c508 | function [im, header] = precon_3dute_pfile_bartv300_allec(pfile, ...
coils, undersamp, ...
skip, freq_shift, echoes,reg_coe, skip_calib_coil, cc_coil, rNecho,ind_echo_recon, espirit_recon);
% [im, header, rhuser, data, data_grid] = recon_3dute_pfile(pfile,
% coils, undersamp, skip, freq_shift, echoes)
%
% Reconstructs 3D UTE PR image acquired with half-projections and
% ramp sampling from pfile only. Reads in scan parameters from pfile.
% INPUTS:
% pfile - points to a scanner raw data file
% either use Pfile 'PXXXXX.7', or, for multiple files, can also be
% 'filename01', where the number increases (can use rename_pfiles.x to appropriately rename)
% use a cell array of the first Pfiles for averaging
% coils (optional) - can select which coils to reconstruct
% undersamp (optional) - [undersamp_dc, undersamp_imsize]. Undersampling ratios for
% density compensation and/or reconstructed image size
% (default is [1.0 1.0])
% skip (optional) - shifts readout by this number of points. Can
% be positive or negative
% freq_shift (optional) - demodulates by this frequency (Hz) to correct for bulk frequency miscalibrations
% echoes (optional) - can select which echoes to reconstruct
% rNecho - real number of echo
% ind_echo_recon - recon each individual echo sequentially
% espirit_recon - do espirit recon or just nufft
% OUTPUTS:
% im - 3d image
% header - header data from pfile
% data - raw projection data
% data_grid - gridded data
%
% Peder Larson 7/28/2008, 6/24/2011
% pcao has some name conflictions for rawloadX_cp (in the src dir) vs. rawloadX and
% rawheadX_cp (in the src dir) vs. rawheadX
if ~isdeployed
addpath /home/pcao/src/bart-0.2.07/matlab/
addpath /home/pcao/src/bart-0.3.01/matlab/
addpath /home/plarson/matlab/3DUTE-recon
% addpath /netopt/share/ese/ESE_DV26.0_R01/tools/matlab/read_MR/
end
disp(pfile)
header = read_MR_headers(pfile); % <<< DCM >>> 20180312
if (nargin < 2)
coils = [];
end
if (nargin < 3) || (isempty(undersamp))
undersamp = 1/header.rdb_hdr.user26;
undersamp_dc = undersamp; undersamp_imsize = undersamp;
elseif length(undersamp) == 1
undersamp_dc = undersamp; undersamp_imsize = undersamp;
else
undersamp_dc = undersamp(1); undersamp_imsize = undersamp(2);
end
if (nargin < 4) || (isempty(skip))
skip = 0;
end
if (nargin < 5) || (isempty(freq_shift))
freq_shift = 0;
end
if (nargin < 6) || (isempty(echoes))
Necho = header.rdb_hdr.nechoes; % <<< DCM >>> 20180312
echoes = 1:Necho;
else
Necho = length(echoes(:));
end
% if isempty(coils)
% Ncoils = (header.rdb_hdr.dab(2)-header.rdb_hdr.dab(1))+1; % <<< DCM >>> 20180312
% coils = 1:Ncoils;
% else
Ncoils = length(coils(:));
% end
if (nargin < 7) || (isempty(reg_coe))
reg_coe = '-r0.05';
end
if (nargin < 12) || (isempty(espirit_recon))
espirit_recon = 1;
end
zeropad_factor = 1;
% <<< DCM >>> 20180312 -- KLUDGE ... add all echoes and slices
%frsize = header.rdb_hdr.da_xres; % <<< DCM >>> 20180312
%nframes = header.rdb_hdr.da_yres -1 ; % <<< DCM >>> 20180312 -- possibly off by one because of "baseline" scan
%nslices = header.rdb_hdr.nslices; % <<< DCM >>> 20180312
frsize = header.rdb_hdr.frame_size;%header2.frsize;
nframes = header.rdb_hdr.nframes;%header2.nframes;
nslices = header.rdb_hdr.nslices;%header2.nslices;
nfphases = header.image.fphase;
data = read_MR_rawdata(pfile,'db', 1:nfphases, echoes, 1:nslices,coils); % <<< DCM >>> 20180312 -- replaced rawloadX_cp
data = squeeze(data);
disp('READ DATA SIZE: ')
disp(size(data))
Nramp = header.rdb_hdr.user11;%rhuser(12);
spres = header.rdb_hdr.user1;%rhuser(2);
resz_scale = header.rdb_hdr.user2; %rhuser(3);
FOV = [header.rdb_hdr.user16, header.rdb_hdr.user17, header.rdb_hdr.user18]; %rhuser(17:19).';
Nprojections = header.rdb_hdr.user9;%rhuser(10);
acqs = header.rdb_hdr.user19;%rhuser(20);
shift = [header.rdb_hdr.user20, header.rdb_hdr.user21,0] / spres; %[rhuser(21:22);0].'/spres;
imsize = FOV*10/spres * zeropad_factor / undersamp_imsize;
final_imsize=round(imsize);
a = 1.375; W = 5; S = calc_kerneldensity(1e-4, a);
gridsize = round(a*imsize);
% For extracting iamges within FOV
rnum = gridsize(1); cnum = gridsize(2); snum = gridsize(3);
ru_skip = ceil((rnum-final_imsize(1))/2); rd_skip = rnum - final_imsize(1)-ru_skip;
cu_skip = ceil((cnum-final_imsize(2))/2); cd_skip = cnum - final_imsize(2)-cu_skip;
su_skip = ceil((snum-final_imsize(3))/2); sd_skip = snum - final_imsize(3)-su_skip;
% frsize = size(data,1);
% nframes = size(data,2);
% Necho = size(data,3);
% nslices = size(data,4);
% Ncoils = size(data,5);
if nframes*nslices >= Nprojections
% data is now frsize, 2*ceil(Nprojections/(Nslices*2)) echoes,
% Nslices, Ncoils
if Nprojections*2 < nframes*nslices
% storing extra echos in slices
data = cat(3, data(:,:,:,1:nslices/2,:), data(:,:,:,nslices/2+[1:nslices/2],:));
nslices = nslices/2;
Necho = 2*Necho; % num_utes?
echoes = 1:Necho;
end
% <<< DCM >>> 20180312 -- reshape and permute the data (interleaved readouts corrected)
data = permute(data, [2 1 4 3 5]); %pcao changed coil and echo dimensions
reordered_projections = [[1:2:nslices],[2:2:nslices]];
fprintf('DEBUG STUFF: \n');
disp(size(data));
%disp(reordered_projections);
fprintf('frsize = %d, nframes = %d, nslices= %d, Necho = %d, Ncoils = %d; product = %d\n', frsize, nframes, nslices, Necho, Ncoils, frsize*nframes*nslices*Necho*Ncoils);
fprintf('END DEBUG STUFF\n');
data = data(:, :, reordered_projections, :);
data = reshape(data, [frsize nframes*nslices Necho Ncoils]);
data = data(:,1:Nprojections,:,:);
if Nprojections*2 < nframes*nslices
%determine and set the real Number of echo, pcao20170214
if (nargin < 10) || (isempty(rNecho) || (rNecho < 1))
sum_nonzero_echo = squeeze(sum(sum(sum(abs(data),1),2),4))> 0;
Necho = sum(sum_nonzero_echo);
else
Necho = rNecho;
end
echoes = 1:Necho;
data = data(:,:,1:Necho,:);
end
else
% legacy recon code
data = read_multiple_pfiles(pfile);
end
% apply different frequency demodulation
if freq_shift ~= 0
dt = 1/(2*header.rdb_hdr.bw*1e3);
t = [0:frsize-1].' * dt;
Sdata = size(data);
data = data .* repmat( exp(-i*2*pi*freq_shift*t), [1 Sdata(2:end)]);
end
% Determine trajectory
[theta, phi, kmax, dcf] = calc_3dpr_ellipse(FOV*10, spres, spres*resz_scale);
x = cos(phi) .* sin(theta) .* kmax;
y = sin(phi) .* sin(theta) .* kmax;
z = cos(theta) .* kmax;
kscale = 0.5 / max(abs(kmax(:)));
x = kscale * x;
y = kscale * y;
z = kscale * z;
% skip samples?
if skip > 0
frsize = frsize - skip;
data = data(1+skip:end,:,:,:);
% elseif skip < 0
% frsize = frsize - skip;
% data = [repmat(data(1,:,:,:,:), [-skip 1 1 1 1]); data];
end
[ksp, dcf_all] = calc_pr_ksp_dcf([x(:),y(:),z(:)],Nramp,frsize,dcf,undersamp_dc);
clear x; clear y; clear z;
clear theta; clear phi; clear dcf;
clear kmax;
% ksp((frsize * Nprojections + 1):end,:) = [];
% dcf_all(:,(Nprojections + 1):end) = [];
if skip < 0
data = data(1:end+skip,:,:,:);
dcf_new = dcf_all(1-skip:end,:);
dcf_new(1,:) = sum(dcf_all(1:1-skip,:),1); % add density of central skipped points
dcf_all = dcf_new;
clear dcf_new
ksp_new = zeros((frsize+skip)*Nprojections,3);
for n = 1:Nprojections
ksp_new([1:frsize+skip] + (n-1)*(frsize+skip),:) = ...
ksp([1-skip:frsize] + (n-1)*frsize,:);
end
ksp = ksp_new;
clear ksp_new
% frsize = frsize + skip; % not necessary to change
end
if (nargin < 8) || (isempty(skip_calib_coil))
skip_calib_coil = 0;%skip the coil calibration
end
if (nargin < 9) || (isempty(cc_coil))
cc_coil = 0; % the coil compression
end
if cc_coil && (length(coils) > cc_coil) %do coil compression
disp('Coil compression')
data(:,:,:,1:cc_coil) = bart(sprintf('cc -r12 -P%d -S',cc_coil), data);
% clear data;
% data = cc_data;
% clear cc_data;
coils = 1:cc_coil;
skip_calib_coil = 0;%cannot skip the sensitivity measurement
data(:,:,:,(cc_coil +1):end) = [];
end
ktraj_all=reshape(ksp,[frsize Nprojections 3]);
ktraj(1,:,:)=ktraj_all(:,:,1)*imsize(1);
ktraj(2,:,:)=ktraj_all(:,:,2)*imsize(2);
ktraj(3,:,:)=ktraj_all(:,:,3)*imsize(3);
tot_npts=frsize*Nprojections;
% dcf_all2(1,:,:)=dcf_all;
% dcf_all2(2,:,:)=dcf_all;
% dcf_all2(3,:,:)=dcf_all;
% clear dcf_all;
% dcf_all = dcf_all2;
for e = 1:length(echoes)
disp(['Preparing reconstructing echo ' int2str(e) '...'])
for Ic = 1:length(coils)
% disp([' Reconstructing coil ' int2str(coils(Ic)) '...'])
% tic
data_c = squeeze(data(:,:,e,Ic));
data_pc(:,Ic) = data_c(:).*exp(j*2*pi*(ksp(:,1)*shift(1) + ksp(:,2)*shift(2) + ksp(:,3)*shift(3)));
end
clear data_c;
if e == echoes
clear data; clear ksp;
end
data_pc = conj(data_pc);
tic
if ~espirit_recon
disp([' Reconstructing echo ' int2str(e) '...'])
im(:,:,:,:,e)=squeeze(bart('nufft -a -p', reshape(dcf_all,[1 tot_npts]), reshape(ktraj, [3 tot_npts]), reshape(data_pc,[1 tot_npts 1 length(coils)])));
else
root_dir = pwd;
list = exist([root_dir '/smap_m1.mat'], 'file');
if e == 1
if ~skip_calib_coil || ~list
disp('unfft to generate calibration k-space')
% name = ['/data/larson/brain_uT2/2016-04-27_7T-vounteer/tmpfftec' int2str(echoes)];
im_under=bart('nufft -a -p', reshape(dcf_all,[1 tot_npts]), reshape(ktraj, [3 tot_npts]), reshape(data_pc,[1 tot_npts 1 length(coils)]));
k_calb=bart('fft -u 7',im_under);
k_calb = bart(sprintf('crop 0 %d', 2*round(size(k_calb,1)*0.2)),k_calb);
k_calb = bart(sprintf('crop 1 %d', 2*round(size(k_calb,2)*0.2)),k_calb);
k_calb = bart(sprintf('crop 2 %d', 2*round(size(k_calb,3)*0.2)),k_calb);
k_calb_zerop = padarray(k_calb, round([size(im_under)/2-size(k_calb)/2]));
clear im_under; clear k_calb;
smap_m1=bart('ecalib -k4 -r12 -m1 -c0.80', k_calb_zerop); %two sets sensitivity maps are needed here, as tested on the /data/vig2/UTE_ZTE/3dute/brain/20150506_TEphase
% figure, imshow3(abs(squeeze(smap_m1(:,:,2,:))));
clear k_calb_zerop;
% if ~isdeployed
save('smap_m1.mat','smap_m1');
% end
else
load smap_m1.mat
end
end
smapall(:,:,:,:,1,e) = smap_m1;
dataall(:,:,:,:,1,e) = reshape(data_pc,[1 tot_npts 1 length(coils)]);
ktrjall(:,:,1,1,1,e) = reshape(ktraj, [3 tot_npts]);
decfall(:,:,1,1,1,e) = reshape(dcf_all,[1 tot_npts]);
end
toc
end
if espirit_recon
clear data
disp('Reconstructing all echos ')
%try add ' -o' scale *; add -n turn off random shift; add -I to choose
%iterative thresholding; move -l1 to reg_coe
% recon_l1 = bartv207(['nusense -I -o -n ' reg_coe ' -p'], reshape(dcf_all,[1 tot_npts]), reshape(ktraj, [3 tot_npts]), reshape(data_pc,[1 tot_npts 1 length(coils)]),smap_m1);
bartcmd = ['pics ' reg_coe];
bartaddcmd{1} = '-p ';
bartaddcmd{2} = '-t ';
bartaddcmd{3} = ' ';
bartaddcmd{4} = ' ';
if nargin < 11 || (isempty(cc_coil))
ind_echo_recon = 0;
end
if ind_echo_recon
for e = 1:length(echoes)
disp([' Individual reconstructing echo ' int2str(e) '...'])
recon_l1(:,:,:,1,1,e) = bartv301addcmd(bartcmd, bartaddcmd, decfall(:,:,1,1,1,e), ktrjall(:,:,1,1,1,e), dataall(:,:,:,:,1,e),smapall(:,:,:,:,1,e));
end
else
recon_l1 = bartv301addcmd(bartcmd, bartaddcmd, decfall, ktrjall, dataall,smapall);
end
im = squeeze(recon_l1); %somehow recon has two sets of data, like corespond to two sets of sensitivity maps
clear recon_l1
end
return
function data = read_multiple_pfiles(pfile)
% legacy code for reading multiple pfile data
MAX_FRAMES = 16384;
if ~iscell(pfile)
temp = pfile;
pfile = cell(1);
pfile{1} = temp;
end
nex = length(pfile);
[data1, header, rhuser] = rawloadX(pfile{1}, [0:MAX_FRAMES],1,1);
Nprojections = rhuser(10);
acqs = rhuser(20);
frsize = size(data1,1);
Ncoils = size(data1,5);
data = zeros(frsize, Nprojections, Necho, Ncoils);
for n = 1:nex
for a = 1:acqs
pfile_a = parse_pfile(pfile{1}, a);
disp(['Reading ' pfile_a '...'])
tic
[data1] = rawloadX(pfile_a, [0:MAX_FRAMES],1,1);
toc
data(:, [MAX_FRAMES*(a-1)+1:min(Nprojections, MAX_FRAMES*a)], :,:) = ...
data(:, [MAX_FRAMES*(a-1)+1:min(Nprojections, MAX_FRAMES*a)], :,:) + ...
squeeze(data1(:, 1:min(Nprojections - (a-1)*MAX_FRAMES,MAX_FRAMES),:,1,:));
clear data1;
end
end
return
function pfile_name = parse_pfile(pfilestring, acq)
% determine if PXXXXX.7 filename or other
if strcmp(pfilestring(end-1:end), '.7')
pfile_num = sscanf(pfilestring(end-6:end-2),'%d');
pfile_path = pfilestring(1:end-8);
pfile_name = sprintf('%sP%05d.7', pfile_path, pfile_num + acq-1);
else
pfile_num = sscanf(pfilestring(end-1:end),'%d');
if isempty(pfile_num) % just single pfile
pfile_name = pfilestring;
else
pfile_path = pfilestring(1:end-2);
pfile_name = sprintf('%s%02d', pfile_path, pfile_num + acq-1);
end
end
return
|
github | LarsonLab/UTEMRI_Brain-master | ute_dicom.m | .m | UTEMRI_Brain-master/ImageReconstruction/ute_dicom.m | 3,971 | utf_8 | 3ad8fd96e99a55aeb5c47fbaf7ba76f0 | function ute_dicom(finalImage, pfile_name, output_image, image_option, scaleFactor, seriesNumberOffset)
% Convert matlab 3D matrix to dicom for UTE sequences
% resolution is fixed in the recon - FOV/readout(from scanner), isotropic
% matrix size is determined in the recon
% Inputs:
% finalImage: 3D image matrix
% pfile_name: original pfile name
% output_image: output directory
% image_option: 1 for both phase and magnitude, 0(offset) mag only
% scaleFactor: scale image matrix
% seriesNumber: output series number
%
% August, 2018, Xucheng Zhu, Nikhil Deveshwar
if nargin<4
image_option = 0;
end
addpath(genpath('../util'));
addpath(genpath('../orchestra-sdk-1.7-1.matlab'));
Isize = size(finalImage);
pfile = GERecon('Pfile.Load', pfile_name);
pfile.header = GERecon('Pfile.Header', pfile);
pfile.phases = numel(finalImage(1,1,1,1,:));
pfile.xRes = size(finalImage,1);
pfile.yRes = size(finalImage,2);
pfile.slices = size(finalImage,3);
pfile.echoes = size(finalImage,4);
% calc real res(isotropic,axial)
corners = GERecon('Pfile.Corners', 1);
orientation = GERecon('Pfile.Orientation', 1);
outCorners = GERecon('Orient', corners, orientation);
% res = abs(outCorners.UpperRight(2)-outCorners.UpperLeft(2))/Isize(3);
res2 = 2;
scale = Isize/Isize(3);
scale2 = [1, 1e-6, 1];
corners.LowerLeft = corners.LowerLeft.*scale2;
corners.UpperLeft = corners.UpperLeft.*scale2;
corners.UpperRight = corners.UpperRight.*scale2;
info = GERecon('Pfile.Info', 1);
% % NEED TO CONFIRM orientation/corners based on slice number
% % HERE IS HOW this is done without the "corners" adjustment shown
% % above:
% sliceInfo.pass = 1;
% sliceInfo.sliceInPass = s;
% info = GERecon('Pfile.Info', 1);
% orientation = info.Orientation; corners = info.Corners;
% X = repmat(int16(0), [96 86 1 94]);
X = zeros(96, 86, 1, 94);
seriesDescription = ['UTE T2 - ', output_image];
seriesNumber = pfile.header.SeriesData.se_no * 100 + seriesNumberOffset;
for s = flip(1:pfile.slices)
for e = 1:pfile.echoes
for p = 1:pfile.phases
mag_t =flip(double(finalImage(:,:,s,e,p) * scaleFactor));
% figure;imshow(mag_t);title('mag_t');
% mag_t2 = GERecon('Orient', mag_t, orientation);
imageNumber = ImageNumber(s, e, p, pfile);
filename = ['DICOMs_' output_image, '/image_',num2str(imageNumber) '.dcm'];
GERecon('Dicom.Write', filename, mag_t, imageNumber, orientation, corners, seriesNumber, seriesDescription);
if image_option~=0
phase_t = flip(flip(single(angle(finalImage(:,:,s,e,p))).',1),2);
%phase_t = GERecon('Orient', phase_t, orientation);
filename = [output_dir,'DICOMS/phase_',num2str(imageNumber) '.dcm'];
GERecon('Dicom.Write', filename, phase_t, imageNumber, orientation, corners);
end
[X(:,:,1,s),map] = dicomread(filename);
end
end
% sliceInfo.pass = 1
% sliceInfo.sliceInPass = s
% info = GERecon('Pfile.Info', 1)
% Get corners and orientation for next slice location?
corners.LowerLeft(3) = corners.LowerLeft(3) + res2;
corners.UpperLeft(3) = corners.UpperLeft(3) + res2;
corners.UpperRight(3) = corners.UpperRight(3) + res2;
% Check header settings in Horos to ensure pixel spacing value is
% correct relative to slice thickness
end
disp([output_image, ' generated.']);
% figure;montage(X(:,:,1,:),map);title(output_image);
end
function number = ImageNumber(slice, echo, phase, pfile)
% Image numbering scheme:
% P0S0E0, P0S0E1, ... P0S0En, P0S1E0, P0S1E1, ... P0S1En, ... P0SnEn, ...
% P1S0E0, P1S0E1, ... PnSnEn
slicesPerPhase = pfile.slices * pfile.echoes;
number = (phase-1) * slicesPerPhase + (slice-1) * pfile.echoes + (echo-1) + 1;
end
|
github | LarsonLab/UTEMRI_Brain-master | get_TE.m | .m | UTEMRI_Brain-master/ImageReconstruction/get_TE.m | 1,517 | utf_8 | d8688efc7a911afd02528f7c5f87b3b3 | %% Import data from text file.
% Script for importing data from the following text file:
%
% /data/larson/brain_uT2/2017-09-29_3T-volunteer/multi_utes.dat
%
% To extend the code to different selected data or a different text file,
% generate a function instead of a script.
% Auto-generated by MATLAB on 2017/09/29 16:08:36
%% Initialize variables.
function TE = get_TE(filename)
%filename = 'multi_utes.dat';
delimiter = ' ';
startRow = 3;
%% Format string for each line of text:
% column1: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%*s%*s%[^\n\r]';
%% Open the text file.
fileID = fopen(filename,'r');
%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'HeaderLines' ,startRow-1, 'ReturnOnError', false);
%% Close the text file.
fclose(fileID);
%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.
%% Allocate imported array to column variable names
TE = dataArray{:, 1};
TE = TE';
%% Clear temporary variables
clearvars filename delimiter startRow formatSpec fileID dataArray ans; |
github | longcw/pytorch-faster-rcnn-master | voc_eval.m | .m | pytorch-faster-rcnn-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 | dkouzoup/hanging-chain-acado-master | plot_partial_condensing.m | .m | hanging-chain-acado-master/code/utils/plot_partial_condensing.m | 1,721 | utf_8 | 306d4177769297aab60fa87db66c8a40 | function FHANDLE = plot_partial_condensing(logs)
%% process data
solver = logs{1}.solver(1:strfind(logs{1}.solver,'_')-1);
NMASS = size(logs, 1);
BS = size(logs,2);
FS = 24;
CPUTIMES = zeros(NMASS, BS);
BLOCKSIZE = zeros(NMASS, BS);
for ii = 1:NMASS
for jj = 1:BS
if ~contains(logs{ii, jj}.solver, solver)
error('log of different solver detected')
end
CPUTIMES(ii, jj) = max(logs{ii, jj}.cputime - logs{ii, jj}.simtime);
BLOCKSIZE(ii, jj) = str2double(logs{ii, jj}.solver(strfind(logs{ii, jj}.solver, '_B')+2:end));
end
end
SPEEDUPS = 1./(CPUTIMES./repmat(CPUTIMES(:,1), 1, BS));
BLOCKSIZE(BLOCKSIZE == 0) = 1;
%% plot
FHANDLE = figure;
legends = {};
for ii = 1:NMASS
MARKER = set_up_marker(logs{ii, 1}.Nmass);
plot(BLOCKSIZE(ii,:), SPEEDUPS(ii,:), 'Marker', MARKER, 'MarkerSize', 12, 'color', 'k', 'Linewidth',1.5, 'LineStyle', '-');
hold on
legends{end+1} = ['$n_{\mathrm{m}} = ' num2str(logs{ii, 1}.Nmass) '$'];
end
grid on
set(gca, 'fontsize',FS);
xlabel('Block size $M$', 'interpreter','latex', 'fontsize',FS);
ylabel('Speedup', 'interpreter','latex', 'fontsize',FS);
set(gca,'TickLabelInterpreter','latex')
title(['Partial condensing with \texttt{' solver '}'],'interpreter','latex', 'fontsize',FS);
l = legend(legends);
l.Interpreter = 'latex';
l.Location = 'northeast';
xlim([BLOCKSIZE(1,1) BLOCKSIZE(1,end)]);
WIDE = 0;
if WIDE
FHANDLE.Position = [100 300 1200 500];
else
FHANDLE.Position = [100 300 600 500];
end
end
function marker = set_up_marker(nmasses)
if nmasses == 3
marker = 'o';
elseif nmasses == 4
marker = '>';
elseif nmasses == 5
marker = 'h';
else
marker = '.';
end
end
|
github | dkouzoup/hanging-chain-acado-master | plot_logs.m | .m | hanging-chain-acado-master/code/utils/plot_logs.m | 4,222 | utf_8 | 76a079fac6d034835eeb007d55e22c64 | function [FHANDLE] = plot_logs(logs, FADED, LOGSCALE, FHANDLE, xlims, ylims)
% PLOT_LOGS plot performance of QP solvers as a function of prediction
% horizon N.
%
% INPUTS:
%
% logs logged data from simulation (cell array)
% FADED set to true to plot solver curves faded (boolean)
% FHANDLE pass existing figure handle to get multiple logs in on plot
if nargin < 6
ylims = [0 130];
end
if nargin < 5
xlims = [10 100];
end
FS = 24;
%% default values for inputs
if nargin < 4 || isempty(FHANDLE)
FHANDLE = figure;
end
if nargin < 3 || isempty(LOGSCALE)
LOGSCALE = false;
end
if nargin < 2 || isempty(FADED)
FADED = false;
end
if FADED
alpha = 0.3;
style = '--';
else
alpha = 1.0;
style = '-';
end
color = [0 0 0 alpha];
%% process data
solver = 'undefined';
nexp = length(logs);
kk = 0; % will contain number of different solvers in log cell array
for ii = 1:nexp
if ~strcmp(solver,logs{ii}.solver)
kk = kk+1;
solver = logs{ii}.solver;
data(kk).x = [];
data(kk).y = [];
data(kk).marker = set_up_marker(solver);
data(kk).solver = set_up_solver_name(solver);
end
data(kk).x = [data(kk).x logs{ii}.N];
data(kk).y = [data(kk).y logs{ii}.cputime - logs{ii}.simtime];
end
%% plot timings
figure(FHANDLE);
if ~LOGSCALE
for kk = 1:length(data)
plot(data(kk).x, 1e3*(max(data(kk).y)), ...
'Marker', data(kk).marker, 'MarkerSize', 12, 'MarkerEdgeColor', [1-alpha 1-alpha 1-alpha], ...
'Color', color, 'Linewidth',1.5, 'LineStyle', style);
hold on
end
grid on
set_up_plot(data, false, FS);
xlim(xlims)
ylim(ylims)
else
for kk = 1:length(data)
loglog(data(kk).x, 1e3*max(data(kk).y), ...
'Marker', data(kk).marker, 'MarkerSize', 12, 'MarkerEdgeColor', [1-alpha 1-alpha 1-alpha], ...
'Color', color, 'linewidth',1.5, 'LineStyle', style);
hold on
end
grid on
set_up_plot(data, true, FS);
xlim(xlims)
ylim(ylims)
% title('Worst case CPU time in closed-loop','interpreter','latex', 'fontsize', FS)
end
FHANDLE.Position = [100 300 600 500];
end
function set_up_plot(data, LOGPLOT, FS)
set(gca, 'fontsize',FS);
xlabel('Prediction horizon $N$', 'interpreter','latex', 'fontsize',FS);
ylabel('CPU time $(\mathrm{ms})$', 'interpreter','latex', 'fontsize',FS);
set(gca,'TickLabelInterpreter','latex')
if ~LOGPLOT
hLegend = findobj(gcf, 'Type', 'Legend');
if isempty(hLegend)
l = legend(data.solver);
l.Interpreter = 'latex';
l.Location = 'northwest';
else
for ii = 1:length(data)
hLegend.String{end-ii+1} = data(end-ii+1).solver;
end
end
end
if data(1).x(end) > data(1).x(1)
xlim([data(1).x(1) data(1).x(end)])
end
end
function marker = set_up_marker(solver)
if strcmp(solver, 'qpOASES_N2')
marker = '^';
elseif strcmp(solver, 'qpOASES_N3')
marker = 'v';
elseif strcmp(solver, 'FORCES')
marker = 's';
elseif strcmp(solver, 'qpDUNES') || strcmp(solver, 'qpDUNES_B0')
marker = 'p';
elseif strcmp(solver, 'HPMPC') || strcmp(solver, 'HPMPC_B0')
marker = '*';
elseif contains(solver, 'HPMPC_B')
marker = 'x';
elseif contains(solver, 'qpDUNES_B')
marker = 'd';
else
marker = 'o';
end
end
function solver_name_latex = set_up_solver_name(solver)
solver_name_latex = solver;
solver_name_latex(solver_name_latex == '_') = ' ';
if contains(solver_name_latex, 'qpOASES')
solver_name_latex = replace(solver_name_latex, 'N', 'C$N^');
solver_name_latex(end+1) = '$';
end
if strcmp(solver_name_latex, 'HPMPC B0')
solver_name_latex = 'HPMPC';
end
if strcmp(solver_name_latex, 'qpDUNES B0')
solver_name_latex = 'qpDUNES';
end
if contains(solver_name_latex, 'HPMPC B') || contains(solver_name_latex, 'qpDUNES B')
solver_name_latex = [solver_name_latex(1:strfind(solver_name_latex, 'B')-1) 'PC'];
% solver_name_latex = replace(solver_name_latex, 'B', 'B$_{');
% solver_name_latex(end+1:end+2) = '}$';
end
end |
github | shane-nichols/smn-thesis-master | muellerData.m | .m | smn-thesis-master/muellerData.m | 52,836 | utf_8 | c342735994beb5434aef01012c5eb83e | classdef (InferiorClasses = {?matlab.graphics.axis.Axes}) muellerData
properties
Label % string
Value % 4,4,M,N,... array of Mueller matrix values
ErValue % 4,4,M,N,... array of Mueller matrix error values
Size % size of Value
Dims % cell array of length ndims(Value)-2 containing arrays of length M,N,...
DimNames % cell array of strings with names of a dimensions M,N,...
HV % M,N,... array of detector high voltage values (4PEM specific)
DC % M,N,... array of waveform DC values (4PEM specific)
reflection
end
methods
function obj = muellerData(value) % Class Constructor
obj.Size = size(value);
obj.Value = value;
obj.Label = '';
end
function varargout = subsref(obj,s) % overload subsref for custom indexing
switch s(1).type
case '()'
if length(obj) == 1 % positional indexing of object properties
if length(s(1).subs) ~= length(obj.Size)
error('Error. Size of object and requested index are not equal');
end
if length(s) == 1
varargout = {objSubset(obj,s)};
else
varargout = {builtin('subsref',objSubset(obj,s(1)),s(2:end))};
end
else
if length(s) == 1
varargout = {builtin('subsref',obj,s)}; % index object array
else
obj = builtin('subsref',obj,s(1));
if numel(obj) == 1
varargout = {builtin('subsref',obj,s(2:end))};
else
temp = builtin('subsref',obj(1),s(2:end));
if isa(temp,'muellerData')
for k=2:numel(obj)
temp(k) = builtin('subsref',obj(k),s(2:end));
end
else
temp = {temp};
for k=2:numel(obj)
temp{k} = builtin('subsref',obj(k),s(2:end));
end
end
varargout = {temp};
end
end
end
case '{}'
if length(obj) == 1
if length(s(1).subs) ~= length(obj.Size)
error('Error. Size of object and requested index are not equal');
end
if length(s) == 1
s = dims2index(obj,s);
varargout = {objSubset(obj,s)};
else
s(1) = dims2index(obj,s(1));
varargout = {builtin('subsref',objSubset(obj,s(1)),s(2:end))};
end
else
if any(arrayfun(@(x) length(s(1).subs) ~= length(x.Size),obj))
error('Error. Size of object and requested index are not equal');
end
if length(s) == 1
temp = obj;
for k=1:numel(obj)
subs = dims2index(obj(k),s);
temp(k) = objSubset(obj(k),subs);
varargout = {temp};
end
else
subs = dims2index(obj(1),s(1));
temp = builtin('subsref',objSubset(obj(1),subs),s(2:end));
if isa(temp,'muellerData')
for k=2:numel(obj)
subs = dims2index(obj(k),s(1));
temp(k) = builtin('subsref',objSubset(obj(k),subs),s(2:end));
end
else
temp = {temp};
for k=2:numel(obj)
subs = dims2index(obj(k),s(1));
temp{k} = builtin('subsref',objSubset(obj(k),subs),s(2:end));
end
end
varargout = {temp};
end
end
case '.'
if length(obj) > 1
temp = builtin('subsref',obj(1),s);
if isa(temp,'muellerData')
for k=2:numel(obj)
temp(k) = builtin('subsref',obj(k),s);
end
else
temp = {temp};
for k=2:numel(obj)
temp{k} = builtin('subsref',obj(k),s);
end
end
varargout = {temp};
else
varargout = {builtin('subsref',obj,s)};
end
end
end
function n = numArgumentsFromSubscript(~,~,~)
n = 1; % I don't like multiple outputs =P
end
function obj = merge(obj1,obj2) % merge two objects
if ~(length(obj1.Size) == length(obj2.Size))
error(['Objects not compatible with merge.'....
' Length of obj.Size must be equal for objects.'])
end
if isempty(obj1.Dims) || isempty(obj2.Dims)
error('Objects not compatible with merge. Dims must be defined.')
end
idx = find(cell2mat(cellfun(@isequal,obj1.Dims,obj2.Dims,'uniformoutput',0))==0);
if length(idx) > 1 || ~isempty(intersect(obj1.Dims{idx},obj2.Dims{idx}))
error('Objects not compatible with merge. Dims must differ in 1 element only.')
end
idx2 = length(obj1.Size) - length(obj1.Dims) + idx;
obj = muellerData(cat(idx2,obj1.Value,obj2.Value));
if ~isempty(obj1.ErValue) && ~isempty(obj2.ErValue)
obj.ErValue = cat(idx2,obj1.ErValue,obj2.ErValue);
end
if ~isempty(obj1.HV) && ~isempty(obj2.HV)
obj.HV = cat(idx,obj1.HV,obj2.HV);
end
if ~isempty(obj1.DC) && ~isempty(obj2.DC)
obj.DC = cat(idx,obj1.DC,obj2.DC);
end
obj.Dims = obj1.Dims;
obj.Dims{idx} = [obj1.Dims{idx} , obj2.Dims{idx}];
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
end
function obj = squeeze(obj)
obj.Value = squeeze(obj.Value);
obj.ErValue = squeeze(obj.ErValue);
obj.Size = size(obj.Value);
if ~isempty(obj.Dims)
logicalIdx = cellfun(@(x) ~isscalar(x),obj.Dims);
obj.Dims = obj.Dims(logicalIdx);
if ~isempty(obj.DimNames)
obj.DimNames = obj.DimNames(logicalIdx);
end
end
obj.HV = squeeze(obj.HV);
obj.DC = squeeze(obj.DC);
end
function obj = plus(obj1,obj2) % overloading of + for muellerData.
% to call, use: obj1 + obj2
% Dims and DimNames and reflection are copied from obj1
% It doesn't make sense to define HV and DC
if isa(obj1,'muellerData') && isa(obj2,'muellerData')
if isequal(obj1.Size,obj2.Size)
obj = muellerData(obj1.Value + obj2.Value);
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 + obj2 for muellerData. obj.Size must be equal for objects.')
end
elseif isa(obj1,'muellerData') && isscalar(obj2)
obj = obj1;
obj.Value = obj.Value + obj2;
elseif isa(obj2,'muellerData') && isscalar(obj1)
obj = obj2;
obj.Value = obj.Value + obj1;
end
end
function obj = minus(obj1,obj2) % overloading of - for muellerData.
if isequal(obj1.Size,obj2.Size)
obj = muellerData(obj1.Value - obj2.Value);
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 - obj2 for muellerData. obj.Size must be equal for objects.')
end
end
function obj = times(obj1,obj2) % overloading of .* for muellerData.
if isequal(obj1.Size,obj2.Size)
obj = muellerData(obj1.Value .* obj2.Value);
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 .* obj2 for muellerData. obj.Size must be equal for objects.')
end
end
function obj = rdivide(obj1,obj2) % overloading of ./ for muellerData.
if isequal(obj1.Size,obj2.Size)
obj = muellerData(obj1.Value ./ obj2.Value);
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 ./ obj2 for muellerData. obj.Size must be equal for objects.')
end
end
function obj = mtimes(obj1,obj2) % overloading of * for muellerData.
ck1 = isa(obj1, 'muellerData');
ck2 = isa(obj2, 'muellerData');
if ck1 && ck2
if ndims(obj2.Value) > ndims(obj1.Value)
obj = obj2;
else
obj = obj1;
end
obj.Value = multiprod(obj1.Value, obj2.Value, [1 2], [1 2]);
elseif ck1
obj = obj1;
obj.Value = multiprod(obj1.Value, obj2, [1 2], [1 2]);
else
obj = obj2;
obj.Value = multiprod(obj1, obj2.Value, [1 2], [1 2]);
end
% if isequal(obj1.Size,obj2.Size)
% val1 = shapeDown(obj1.Value);
% val2 = shapeDown(obj2.Value);
% for i=1:size(val1,3); val1(:,:,i) = val1(:,:,i)*val2(:,:,i); end
% obj = muellerData(shapeUp(val1,obj1.Size));
% obj.Dims = obj1.Dims;
% obj.DimNames = obj1.DimNames;
% obj.reflection = obj1.reflection;
% else
% error('Error in obj1 ./ obj2 for muellerData. obj.Size must be equal for objects.')
% end
end
function obj = mrdivide(obj1,obj2) % overloading of / for muellerData.
if isequal(obj1.Size,obj2.Size)
val1 = shapeDown(obj1.Value);
val2 = shapeDown(obj2.Value);
for i=1:size(val1,3); val1(:,:,i) = val1(:,:,i)/val2(:,:,i); end
obj = muellerData(shapeUp(val1,obj1.Size));
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 ./ obj2 for muellerData. obj.Size must be equal for objects.')
end
end
function obj = mldivide(obj1,obj2) % overloading of \ for muellerData.
if isequal(obj1.Size,obj2.Size)
val1 = shapeDown(obj1.Value);
val2 = shapeDown(obj2.Value);
for i=1:size(val1,3); val1(:,:,i) = val1(:,:,i) \ val2(:,:,i); end
obj = muellerData(shapeUp(val1,obj1.Size));
obj.Dims = obj1.Dims;
obj.DimNames = obj1.DimNames;
obj.reflection = obj1.reflection;
else
error('Error in obj1 ./ obj2 for muellerData. obj.Size must be equal for objects.')
end
end
function handles = plot(varargin)
handles = prePlot(varargin{:});
end
function handles = subplot(varargin)
% Example: % obj.subplot( {'lb','lbp','cb';'ld','ldp','cd'} , 'legend','none' )
[obj,funcs] = varargin{:};
figure
M = size(funcs,1);
N = size(funcs,2);
funcs = funcs(:);
handles = gobjects(1,M*N);
for idx=1:M*N
ax = subplot(M,N,idx);
fn = str2func(funcs{idx});
handles(idx) = plot(fn(obj),'handle',ax,varargin{3:end},...
'title',[', ',upper(funcs{idx})]);
end
end
function handles = print(varargin)
filePath = varargin{2}; % extract the filepath
[pathStr,name] = fileparts(filePath);
filePath = [pathStr,'/',varargin{1}.Label,name];
handles = prePlot(varargin{[1,3:end]}); % make the figure
print(gcf,filePath,'-depsc'); % print figure as .eps file
end
% Calls to static methods on obj.Value, returns new class instance %
function obj = optProp(obj)
obj.Value = obj.s_optProp(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lm(varargin)
obj = varargin{1};
if nargin == 1
obj.Value = obj.s_lm(obj.Value);
else
obj.Value = obj.s_lm(obj.Value,varargin{2});
end
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = logm(obj)
obj.Value = obj.s_logm(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lu(obj)
obj = obj.logm;
g = diag([-1 1 1 1]);
for n=1:size(obj.Value,3)
obj.Value(:,:,n) = (obj.Value(:,:,n) + g*obj.Value(:,:,n).'*g)/2;
end
end
function obj = lm2(obj)
obj = obj.logm;
g = diag([-1 1 1 1]);
for n=1:size(obj.Value,3)
obj.Value(:,:,n) = (obj.Value(:,:,n) - g*obj.Value(:,:,n).'*g)/2;
end
end
function obj = expm(obj)
obj.Value = obj.s_expm(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lb(obj)
obj.Value = obj.s_lb(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = ld(obj)
obj.Value = obj.s_ld(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lbp(obj)
obj.Value = obj.s_lbp(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = ldp(obj)
obj.Value = obj.s_ldp(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = cb(obj)
obj.Value = obj.s_cb(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = cd(obj)
obj.Value = obj.s_cd(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = a(obj)
obj.Value = obj.s_a(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = a_aniso(obj)
obj.Value = obj.s_a_aniso(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = a_iso(obj)
obj.Value = obj.s_a_iso(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = ldmag(obj)
obj.Value = obj.s_ldmag(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = ldang(obj)
obj.Value = obj.s_ldang(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lbang(obj)
obj.Value = obj.s_lbang(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lbmag(obj)
obj.Value = obj.s_lbmag(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = di(obj)
obj.Value = obj.s_di(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = jones(obj)
obj.Value = obj.s_jones(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = nearestjones(obj)
obj.Value = obj.s_nearestjones(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = mfilter(obj)
obj.Value = obj.s_mfilter(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = covar(obj)
obj.Value = obj.s_covar(obj.Value);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = mrotate(obj,angle_rad)
obj.Value = obj.s_mrotate(obj.Value,angle_rad);
obj.ErValue = [];
obj.Size = size(obj.Value);
end
function obj = lm2optProp(obj)
% [LB;LD;LBp;LDp;CB;CD;A]
lm = obj.Value;
sz = size(lm);
lm = shapeDown(lm);
val(1,:) = lm(4,3,:);
val(2,:) = -lm(1,2,:);
val(3,:) = lm(2,4,:);
val(4,:) = -lm(1,3,:);
val(5,:) = lm(2,3,:);
val(6,:) = lm(1,4,:);
val(7,:) = -lm(1,1,:);
obj.Value = shapeUp(val, sz);
end
end
methods(Static)
% value = obj.Value
function r = s_optProp(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
L=1i.*O.*( J(1,1,:) - J(2,2,:) );
Lp=1i.*O.*( J(1,2,:) + J(2,1,:) );
C=O.*( J(1,2,:) - J(2,1,:) );
LB=real(L);
LD=-imag(L);
LBp=real(Lp);
LDp=-imag(Lp);
CB=real(C);
CD=-imag(C);
A = -2*real(log(1./K)); % mean absorption
r = shapeUp(squeeze([LB;LD;LBp;LDp;CB;CD;A]),sz);
end
function value = s_lm(varargin)
value = varargin{1};
sz = size(value);
if nargin == 1
value = shapeDown(value);
%J = nearestJones(value);
J = MJ2J(value);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2);
O = (T.*K)./(sin(T));
L=1i.*O.*( J(1,1,:) - J(2,2,:) );
Lp=1i.*O.*( J(1,2,:) + J(2,1,:) );
C=O.*( J(1,2,:) - J(2,1,:) );
LB=real(L);
LD=-imag(L);
LBp=real(Lp);
LDp=-imag(Lp);
CB=real(C);
CD=-imag(C);
A = 2*real(log(1./K)); % mean absorption
value = shapeUp([A,-LD,-LDp,CD ; -LD,A,CB,LBp ; -LDp,-CB,A,-LB ; CD,-LBp,LB,A],sz);
else
n_int = varargin{2};
value = reshape(value,4,4,size(value,3),[]);
for j = 1:size(value,4)
M = value(:,:,:,j);
M = flip(M,3);
J = nearestJones(M);
K=(J(1,1,1).*J(2,2,1) - J(1,2,1)*J(2,1,1)).^(-1/2);
T=2*acos((K.*(J(1,1,1) + J(2,2,1)))./2);
O=(T+2*pi*n_int).*K./(sin(T/2)*2);
N = size(J,3);
L = zeros(1,N);
Lp = zeros(1,N);
C = zeros(1,N);
A = zeros(1,N);
L(1) = 1i.*O.*(J(1,1,1) - J(2,2,1));
Lp(1) = 1i.*O.*(J(1,2,1) + J(2,1,1));
C(1) = O.*(J(1,2,1) - J(2,1,1));
A(1) = 2*real(log(1./K));
n = n_int;
for i = 2:N
if n==0 || n==-1
n_ar = [0,-1,1,-2,2];
else
n_ar = [n-1,-n,n,-(n+1),n+1];
end
K=(J(1,1,i).*J(2,2,i) - J(1,2,i)*J(2,1,i)).^(-1/2);
T=2*acos((K.*(J(1,1,i) + J(2,2,i)))./2);
O=(T+2*pi*n_ar).*K./(sin(T/2)*2);
l = 1i.*O.*(J(1,1,i) - J(2,2,i));
lp = 1i.*O.*(J(1,2,i) + J(2,1,i));
c = O.*(J(1,2,i) - J(2,1,i));
diffs = sum([L(i-1)-l;Lp(i-1)-lp;C(i-1)-c],1);
[~,I] = min(diffs);
L(i) = l(I);
Lp(i) = lp(I);
C(i) = c(I);
n = n_ar(I);
A(i) = 2*real(log(1./K));
end
LB=reshape(real(L),1,1,[]);
LD=reshape(-imag(L),1,1,[]);
LBp=reshape(real(Lp),1,1,[]);
LDp=reshape(-imag(Lp),1,1,[]);
CB=reshape(real(C),1,1,[]);
CD=reshape(-imag(C),1,1,[]);
A = reshape(A,1,1,[]);
value(:,:,:,j) = ...
flip([A,-LD,-LDp,CD ; -LD,A,CB,LBp ; -LDp,-CB,A,-LB ; CD,-LBp,LB,A],3);
end
value = reshape(value,sz);
end
end
function r = s_logm(value) % log of Mueller matrix with filtering
sz = size(value);
value = shapeDown(value);
Mfiltered = filterM(value);
r = shapeUp(zeros(size(Mfiltered)),sz);
for n=1:size(value,3); r(:,:,n) = logm(Mfiltered(:,:,n)); end
end
function r = s_expm(r) % log of Mueller matrix with filtering
sz = size(r);
r = shapeDown(r);
for n=1:size(r,3); r(:,:,n) = expm(r(:,:,n)); end
r = shapeUp(r,sz);
end
function r = s_lb(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = real(1i.*r.*( J(1,1,:) - J(2,2,:) ));
r = shapeUp(r,sz);
end % 0,90 linear retardance
function r = s_ld(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = -imag(1i.*r.*( J(1,1,:) - J(2,2,:) ));
r = shapeUp(r,sz);
end % 0,90 linear extinction
function r = s_lbp(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = real(1i.*r.*( J(1,2,:) + J(2,1,:) ));
r = shapeUp(r,sz);
end % 45,-45 linear retardance
function r = s_ldp(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = -imag(1i.*r.*( J(1,2,:) + J(2,1,:) ));
r = shapeUp(r,sz);
end % 45,-45 linear extinction
function r = s_cb(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = real(r.*( J(1,2,:) - J(2,1,:) ));
r = shapeUp(r,sz);
end % circular retardance
function r = s_cd(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = jonesAnisotropy(J);
r = -imag(r.*( J(1,2,:) - J(2,1,:) ));
r = shapeUp(r,sz);
end % circular extinction
function r = s_a(value) % total mean extinction
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
r = -2*real(log( ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(1/2) ));
r = shapeUp(r,sz);
end
function r = s_a_aniso(value) % anisotropic part of the mean extinction
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
CD = -imag(O.*( J(1,2,:) - J(2,1,:) ));
r = shapeUp(sqrt(LD.^2 + LDp.^2 + CD.^2),sz); % not same as imag(2*T) !
end
function r = s_a_iso(value) % isotropic part of the mean extinction
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
CD = -imag(O.*( J(1,2,:) - J(2,1,:) ));
r = shapeUp(-2*real(log(1./K)) - sqrt(LD.^2 + LDp.^2 + CD.^2),sz);
end
function r = s_ldmag(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
O = jonesAnisotropy(J);
LD = imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
r = shapeUp(sqrt(LD.^2 + LDp.^2),sz);
end
function r = s_ldang(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
O = jonesAnisotropy(J);
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
r = shapeUp(atan2(LDp , LD)./2,sz);
%out = out + pi*(out < 0);
end
function r = s_lbang(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
O = jonesAnisotropy(J);
LB = real(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LBp = real(1i.*O.*( J(1,2,:) + J(2,1,:) ));
r = atan2(LBp , LB)./2;
r = shapeUp(r + pi*(r < 0),sz);
end
function r = s_lbmag(value)
sz = size(value);
value = shapeDown(value);
J = nearestJones(value);
O = jonesAnisotropy(J);
LB = real(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LBp = real(1i.*O.*( J(1,2,:) + J(2,1,:) ));
r = shapeUp(sqrt(LB.^2 + LBp.^2),sz);
end
function r = s_di(value) % Depolarization Index
sz = size(value);
value = shapeDown(value);
r = shapeUp((sqrt(squeeze(sum(sum(value.^2,1),2))./squeeze(value(1,1,:)).^2-1)./sqrt(3)).',sz);
end
function r = s_jones(value) % Jones matrix of a Mueller-Jones matrix
sz = size(value);
value = shapeDown(value);
r = shapeUp(MJ2J(value),sz);
end
function r = s_nearestjones(value)
sz = size(value);
value = shapeDown(value);
r = nearestJones(value); % Jones matrix
% next line just phases the Jones matrix so that the
% imaginary part of J(1,1) = 0. i.e., it matches case 'jones'
for n=1:size(r,3); r(:,:,n) = exp( -1i*angle(r(1,1,n)) ) * r(:,:,n); end
r = shapeUp(r,sz);
end
function r = s_mfilter(value) % closest physical Mueller matrix
sz = size(value);
value = shapeDown(value);
r = shapeUp(filterM(value),sz);
end
function r = s_covar(value) % Mueller to Cloude covariance
sz = size(value);
value = shapeDown(value);
r = shapeUp(M2Cov(value),sz);
end
function r = plotter(varargin)
r = linePlot(varargin{:});
end
function r = s_mrotate(M,theta)
% M is a Mueller matrix array of any dimension. The first two dimension
% must be the Mueller matrix elements. MMout is a Mueller array with the
% same dimension as the input array.
% October 17, 2016: sign of theta changed so +LB transforms to +LB' with
% theta = pi/4.
sz = size(M);
M = shapeDown(M);
r = M;
theta=-2*theta;
C2=cos(theta);
S2=sin(theta);
r(1,2,:) = M(1,2,:)*C2 + M(1,3,:)*S2;
r(1,3,:) = M(1,3,:)*C2 - M(1,2,:)*S2;
r(2,1,:) = M(2,1,:)*C2 + M(3,1,:)*S2;
r(3,1,:) = M(3,1,:)*C2 - M(2,1,:)*S2;
r(2,4,:) = M(2,4,:)*C2 + M(3,4,:)*S2;
r(3,4,:) = M(3,4,:)*C2 - M(2,4,:)*S2;
r(4,2,:) = M(4,2,:)*C2 + M(4,3,:)*S2;
r(4,3,:) = M(4,3,:)*C2 - M(4,2,:)*S2;
r(2,2,:) = C2*(M(3,2,:)*S2 + M(2,2,:)*C2) + S2*(M(3,3,:)*S2 + M(2,3,:)*C2);
r(2,3,:) = C2*(M(3,3,:)*S2 + M(2,3,:)*C2) - S2*(M(3,2,:)*S2 + M(2,2,:)*C2);
r(3,2,:) = -C2*(M(2,2,:)*S2 - M(3,2,:)*C2) - S2*(M(2,3,:)*S2 - M(3,3,:)*C2);
r(3,3,:) = S2*(M(2,2,:)*S2 - M(3,2,:)*C2) - C2*(M(2,3,:)*S2 - M(3,3,:)*C2);
r = shapeUp(r,sz);
end
function fig = mergeAxes(h,sz)
h = h(:);
set(h,'Units','Pixels');
p = get(h,'Position');
ti = get(h,'TightInset');
extents = ...
cellfun(@(p,ti) [ti(1) + ti(3) + p(3) , ti(2) + ti(4) + p(4)],p,ti,'uniformoutput',0);
extents = max(cell2mat(extents));
[I,J] = ind2sub(sz,1:length(h));
hspace = 10;
vspace = 10;
figSz = (flip(sz)).*[hspace,vspace] + flip(sz).*extents ;
fig = figure('Units','Pixels','Position',[0, 0, figSz(1), figSz(2)] );
for i=1:length(h)
os1 = p{i}(1) - ti{i}(1);
os2 = p{i}(2) - ti{i}(2);
obj = h(i).Parent.Children;
set(obj,'Units','Pixels');
pos = get(obj,'Position');
obj = copyobj(obj,fig);
if length(obj) == 1
pos = pos + [J(i) * hspace + (J(i) - 1) * extents(1) - os1 ,...
(sz(1)-I(i)) * vspace + (sz(1)-I(i)) * extents(2) - os2 ,...
0,0];
obj.Position = pos;
else
for j=1:length(obj)
temp = pos{j} + ...
[(J(i)-1) * hspace + (J(i) - 1) * extents(1) - os1 ,...
(sz(1)-I(i)) * vspace + (sz(1)-I(i)) * extents(2) - os2 ,...
0,0];
obj(j).Position = temp;
end
end
end
end
end
end
% LOCAL FUNCTIONS
% =========================================================================
function s = dims2index(obj,s) % for indexing with Dims
if isempty(obj.Dims)
error('Error. obj.Dims not defined.');
end
sz = length(s.subs) - length(obj.Dims);
for i=1:length(obj.Dims)
if s.subs{i+sz} ~= ':'
[X,I] = sort(obj.Dims{i}); % added this to allow unsorted Dims
indices = unique(round(fracIndex(X,s.subs{i+sz})),'first');
s.subs{i+sz} = I(indices);
end
end
end
function obj = objSubset(obj,s) % obj parsing
obj.Value = obj.Value(s.subs{:});
obj.Size = size(obj.Value);
if ~isempty(obj.ErValue)
obj.ErValue = obj.ErValue(s.subs{:});
end
obj.DimNames = obj.DimNames;
lsubs = length(s.subs) + 1;
if ~isempty(obj.HV)
obj.HV = obj.HV(s.subs{(lsubs-sum(size(obj.HV) ~= 1)):end});
end
if ~isempty(obj.DC)
obj.DC = obj.DC(s.subs{(lsubs-sum(size(obj.DC) ~= 1)):end});
end
if ~isempty(obj.Dims)
sz = lsubs - length(obj.Dims) - 1;
for i=1:length(obj.Dims)
obj.Dims{i} = obj.Dims{i}(s.subs{i+sz});
end
end
end
function out = shapeDown(out)
if ndims(out) > 3 % reshape array into 4,4,N
out = reshape(out,4,4,[]);
end
end % reshape
function out = shapeUp(out,sz) % overly complicated reshaping
sz2 = size(out);
if length(sz)>=3 % reshape to match input dimensions
out = reshape(out,[sz2(1:(length(sz2)-1)),sz(3:length(sz))]);
end
sz2 = size(out);
if sz2(1) == 1 % remove leading singletons if necessary
if sz2(2) == 1
out = shiftdim(out,2); % out = reshape(out,sz2(3:end));
else
out = shiftdim(out,1); %out = reshape(out,sz2(2:end));
end
end
end
function J = MJ2J(M) % Mueller-Jones to Jones
J(1,1,:) = ((M(1,1,:)+M(1,2,:)+M(2,1,:)+M(2,2,:))/2).^(1/2);
k = 1./(2.*J(1,1,:));
J(1,2,:) = k.*(M(1,3,:)+M(2,3,:)-1i.*(M(1,4,:)+M(2,4,:)));
J(2,1,:) = k.*(M(3,1,:)+M(3,2,:)+1i.*(M(4,1,:)+M(4,2,:)));
J(2,2,:) = k.*(M(3,3,:)+M(4,4,:)+1i.*(M(4,3,:)-M(3,4,:)));
end
function C = M2Cov(M) % Mueller to Cloude covariance
C(1,1,:) = M(1,1,:) + M(1,2,:) + M(2,1,:) + M(2,2,:);
C(1,2,:) = M(1,3,:) + M(1,4,:)*1i + M(2,3,:) + M(2,4,:)*1i;
C(1,3,:) = M(3,1,:) + M(3,2,:) - M(4,1,:)*1i - M(4,2,:)*1i;
C(1,4,:) = M(3,3,:) + M(3,4,:)*1i - M(4,3,:)*1i + M(4,4,:);
C(2,1,:) = M(1,3,:) - M(1,4,:)*1i + M(2,3,:) - M(2,4,:)*1i;
C(2,2,:) = M(1,1,:) - M(1,2,:) + M(2,1,:) - M(2,2,:);
C(2,3,:) = M(3,3,:) - M(3,4,:)*1i - M(4,3,:)*1i - M(4,4,:);
C(2,4,:) = M(3,1,:) - M(3,2,:) - M(4,1,:)*1i + M(4,2,:)*1i;
C(3,1,:) = M(3,1,:) + M(3,2,:) + M(4,1,:)*1i + M(4,2,:)*1i;
C(3,2,:) = M(3,3,:) + M(3,4,:)*1i + M(4,3,:)*1i - M(4,4,:);
C(3,3,:) = M(1,1,:) + M(1,2,:) - M(2,1,:) - M(2,2,:);
C(3,4,:) = M(1,3,:) + M(1,4,:)*1i - M(2,3,:) - M(2,4,:)*1i;
C(4,1,:) = M(3,3,:) - M(3,4,:)*1i + M(4,3,:)*1i + M(4,4,:);
C(4,2,:) = M(3,1,:) - M(3,2,:) + M(4,1,:)*1i - M(4,2,:)*1i;
C(4,3,:) = M(1,3,:) - M(1,4,:)*1i - M(2,3,:) + M(2,4,:)*1i;
C(4,4,:) = M(1,1,:) - M(1,2,:) - M(2,1,:) + M(2,2,:);
C = C./2;
end
function M = Cov2M(C) % Cloude covariance to Mueller
M(1,1,:) = C(1,1,:) + C(2,2,:) + C(3,3,:) + C(4,4,:);
M(1,2,:) = C(1,1,:) - C(2,2,:) + C(3,3,:) - C(4,4,:);
M(1,3,:) = C(1,2,:) + C(2,1,:) + C(3,4,:) + C(4,3,:);
M(1,4,:) = ( -C(1,2,:) + C(2,1,:) - C(3,4,:) + C(4,3,:) )*1i;
M(2,1,:) = C(1,1,:) + C(2,2,:) - C(3,3,:) - C(4,4,:);
M(2,2,:) = C(1,1,:) - C(2,2,:) - C(3,3,:) + C(4,4,:);
M(2,3,:) = C(1,2,:) + C(2,1,:) - C(3,4,:) - C(4,3,:);
M(2,4,:) = ( -C(1,2,:) + C(2,1,:) + C(3,4,:) - C(4,3,:) )*1i;
M(3,1,:) = C(1,3,:) + C(2,4,:) + C(3,1,:) + C(4,2,:);
M(3,2,:) = C(1,3,:) - C(2,4,:) + C(3,1,:) - C(4,2,:);
M(3,3,:) = C(1,4,:) + C(2,3,:) + C(3,2,:) + C(4,1,:);
M(3,4,:) = ( -C(1,4,:) + C(2,3,:) - C(3,2,:) + C(4,1,:) )*1i;
M(4,1,:) = ( C(1,3,:) + C(2,4,:) - C(3,1,:) - C(4,2,:) )*1i;
M(4,2,:) = ( C(1,3,:) - C(2,4,:) - C(3,1,:) + C(4,2,:) )*1i;
M(4,3,:) = ( C(1,4,:) + C(2,3,:) - C(3,2,:) - C(4,1,:) )*1i;
M(4,4,:) = C(1,4,:) - C(2,3,:) - C(3,2,:) + C(4,1,:);
M = real(M)./2;
end
function J = nearestJones(M)
C = M2Cov(M);
J = zeros(2,2,size(C,3));
for n=1:size(C,3)
[V,D] = eig(C(:,:,n),'vector');
[~,mx] = max(D);
J(:,:,n) = sqrt(D(mx))*reshape(V(:,mx),2,2).';
end
end
function M = filterM(M) % M to nearest physical M
C_raw = M2Cov(M);
C = zeros(size(C_raw));
for n=1:size(C_raw,3)
[V,D] = eig(C_raw(:,:,n),'vector');
list = find(D > 0.00001).';
idx = 0;
temp = zeros(4,4,length(list));
for j = list
idx = idx + 1;
temp(:,:,idx) = D(j)*V(:,j)*V(:,j)';
end
C(:,:,n) = sum(temp,3);
end
M = Cov2M(C);
end
function O = jonesAnisotropy(J)
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2);
O = (T.*K)./(sin(T));
end
function fracIndx = fracIndex(X,y) %fractional index
% X: 1xN array of increasing values
% y: array of values in the range of X
% fracIndx is an array the length of y that contains the fractional
% index of the y values in array X.
% e.g., X = [2,4,6]; y = [4,5]; gives, fracIndx = [2,2.5];
fracIndx = zeros(1,length(y));
for idx = 1:length(y)
if y(idx) >= X(length(X))
fracIndx(idx) = length(X);
elseif y(idx) <= X(1)
fracIndx(idx) = 1;
else
a = find(X <= y(idx));
a = a(length(a));
b = find(X > y(idx));
b = b(1);
fracIndx(idx) = a+(y(idx)-X(a))/(X(b)-X(a));
end
end
end
function handles = prePlot(varargin)
obj = varargin{1};
if all(obj.Size(1:2) == 4)
plotTool = @MMplot;
else
plotTool = @linePlot;
end
if ~isempty(obj.Label)
if any(strcmpi('title',varargin))
idx = find(strcmpi('title',varargin)) + 1;
varargin{idx} = [obj.Label, ' ',varargin{idx}];
else
sz = length(varargin);
varargin{sz+1} = 'title';
varargin{sz+2} = obj.Label;
end
end
if ~any(strcmpi('legend',varargin))
if length(obj.Dims) >= 2 && ~isempty(obj.Dims{2})
if length(obj.Dims) >= 3 && ~isempty(obj.Dims{3})
idx = 1;
Labels = cell(1,length(obj.Dims{2})*length(obj.Dims{3}));
for i=1:length(obj.Dims{2})
for j=1:length(obj.Dims{3})
Labels{idx} = [num2str(obj.Dims{2}(i)),' ; ',num2str(obj.Dims{3}(j))];
idx = idx + 1;
end
end
LabelNames = [obj.DimNames{2},' ; ',obj.DimNames{3}];
else
Labels = obj.Dims{2};
LabelNames = obj.DimNames{2};
end
sz = length(varargin);
varargin{sz+1} = 'legend';
varargin{sz+2} = {LabelNames,Labels};
end
end
handles = plotTool(obj.Dims{1},obj.Value,obj.ErValue,varargin{2:end});
end
function handles = MMplot(Lam,MMdata,MMerror,varargin)
% Mueller matrix 2D plotting utility
% Makes a 4 x 4 array of 2-D line plots with full control over line and
% axes properties.
% Outputs: [1 x 16] array of axis handles
%
% Required positional inputs:
% Lam: [1 x n] array of wavelengths (X-axis)
% MMdata: [4 x 4 x n x ...] Mueller matrix array
% Optional positional inputs:
% LineSpec: string containing a valid lineSpec. Type "doc LineSpec" in
% command window for more info. Default is "-", a solid line.
% Optional Name-Value pairs inputs:
% ev: bool. converts X axis to eV. e.g., 'ev',true
% handles: [1 x 16] array of plot handles. New handles are created if not given.
% limY: scalar numeric. limits how small the range of the y-axes can be.
% fontsize: sets font-size. Default is 12 pts. Changing the fontsize
% of existing plots is not recommended. (Set on first call).
% lineNV: a 1D cell array containing Name-Value pair arguments valid for
% Chart Line Properties.
% axNV: a 1D cell array containing Name-Value pairs arguments valid for
% Axes Properties.
% size: Size of the figure in pixels given as a two element vector [X Y].
% A warning is issued if the requested size is larger than the screen
% size minus the height of the OSX status bar (on my machine).
% Default size is [1000 700].
% title: string containing a title to place at the top of the figure.
% legend: two-element cell array. First element is a string to use for
% title of the legend. Second element is either a numeric array
% containing values to use for labels of each plot, or a cell array
% of strings to use as labels. Only set legend on last call, or just
% write all plots at once (better).
% vSpace: Adds extra space vertical between plots, in pixels
% borderFactor: Increases white space around plots. This value is a
% multiple of the largest line width on the plots.
p = inputParser;
% input validation functions
valFun1 = @(x) ischar(x) && ...
all(~strcmpi(x,{'ev','handles','lineNV','limY','fontsize','axNV','size',...
'title','legend','vSpace','borderFactor'}));
valFun2 = @(x) isscalar(x)&&isnumeric(x);
% setup input scheme
addRequired(p,'Lam',@isnumeric);
addRequired(p,'MMdata',@isnumeric);
addRequired(p,'MMerror',@isnumeric);
addOptional(p,'LineSpec','-',valFun1)
addParameter(p,'ev',false,@islogical)
addParameter(p,'handles',gobjects(1,16), @(x) all(ishandle(x)))
addParameter(p,'limY',0,valFun2)
addParameter(p,'fontsize',12,valFun2)
addParameter(p,'axNV',{},@iscell)
addParameter(p,'lineNV',{},@iscell)
addParameter(p,'size',[1000 700],@(x) length(x) == 2 && isnumeric(x))
addParameter(p,'title','',@ischar)
addParameter(p,'legend',{},@(x) iscell(x) || strcmp(x,'none'))
addParameter(p,'vSpace',0,@isscalar)
addParameter(p,'borderFactor',0,@isscalar)
parse(p,Lam,MMdata,MMerror,varargin{:}) %parse inputs
% create new figure if no valid handles were given
handles = p.Results.handles;
if any(strcmpi('handles',p.UsingDefaults))
% Determine how large to make the figure window, according to the screensize.
scrsz = get(0,'screensize');
figPos = [1 5 p.Results.size];
if figPos(3) > scrsz(3)
figPos(3) = scrsz(3);
warning(['Figure horizontal dimension set to the maximum value of ',...
num2str(figPos(3)),' pixels.'])
end
if figPos(4) > (scrsz(4) - 99) % 99 pixels is the height of the OSX status bar on my machine
figPos(4) = (scrsz(4) - 99);
warning(['Figure vertical dimension set to the maximum value of ',...
num2str(figPos(4)),' pixels.'])
end
h_fig = figure('position',figPos,'units','pixels'); %create figure
xLabel = uicontrol('style','text','BackgroundColor','w',...
'units','pixels','FontSize',p.Results.fontsize,...
'tag','xLabelObject'); % create x-label
if p.Results.ev == true
set(xLabel,'String','Energy (eV)');
else
set(xLabel,'String','Wavelength (nm)');
end
xLabel_sz = get(xLabel,'extent');
set(xLabel,'Position',[(figPos(3) - xLabel_sz(3) )./2, 0, xLabel_sz(3), xLabel_sz(4)]);
if ~isempty(p.Results.title) % create title if given
figTitle = uicontrol('style','text','BackgroundColor','w',...
'units','pixels','FontSize',p.Results.fontsize,...
'tag','titleObject');
set(figTitle,'String',p.Results.title)
figTitle_sz = get(figTitle,'extent');
set(figTitle,'Position',[( figPos(3) - figTitle_sz(3) )./2,...
( figPos(4) - figTitle_sz(4) ), figTitle_sz(3), figTitle_sz(4)]);
end
% determine the horizontal extent of y-axis marker labels
dummy = uicontrol('style','text','fontsize',p.Results.fontsize,'units','pixels');
set(dummy,'String','-0.000');
yAxSz = get(dummy,'extent');
delete(dummy)
plotSzX = figPos(3)/4 - yAxSz(3) - yAxSz(3)./5; % X size of plot area in pixels
plotSzY = ( figPos(4) - 4*yAxSz(4) )/4 - 6 - p.Results.vSpace; % Y size of plot area in pixels
for i=1:4
for j=1:4
plotPos = [ ( (plotSzX + yAxSz(3) + 3)*(j-1) + yAxSz(3) +5)./figPos(3) ,...
((plotSzY + yAxSz(4)./2 + p.Results.vSpace)*(4-i)+yAxSz(4)*2 + 3)./figPos(4),...
plotSzX./figPos(3), plotSzY./figPos(4)];
hand = subplot('Position',plotPos);
hold(hand,'on')
box(hand,'on')
if i ~= 4
set(hand,'XTickLabel',[]) % keep X lables only for bottom row
end
handles(j+4*(i-1)) = hand;
end
end
else
h_fig = get(handles(1),'parent');
figPos = get(h_fig,'Position');
end
%plot data and set Line properties.
if p.Results.ev == true; Lam = 1239.8./Lam; end
if isempty(MMerror)
for j = 1:4
for k = 1:4
plot(handles(k+4*(j-1)),Lam,squeeze(MMdata(j,k,:,:)),...
p.Results.LineSpec,p.Results.lineNV{:})
end
end
else
for j = 1:4
for k = 1:4
errorbar(handles(k+4*(j-1)),Lam,squeeze(MMdata(j,k,:,:)),...
squeeze(MMerror(j,k,:,:)),...
p.Results.LineSpec,'CapSize',0,p.Results.lineNV{:})
end
end
end
% set Axes properties
axis(handles,'tight'); % first, axes are set to tight
if ~isempty(p.Results.axNV)
for j=1:16; set(handles(j),p.Results.axNV{:}); end
end
if p.Results.limY ~= 0 % modify axes bounds if limY is set
lim = p.Results.limY;
for j=1:16
Ylim = get(handles(j),'YLim');
if (Ylim(2) - Ylim(1)) < lim
avg = (Ylim(2) + Ylim(1))./2;
Ylim(2) = avg + lim/2;
Ylim(1) = avg - lim/2;
set(handles(j),'Ylim',Ylim);
end
end
end
% Adjust plot limits so that lines do not overlap axis borders.
% *** If you like to use Markers, then perhaps change 'lineWidth' to 'MarkerSize'
lineHandle = get(handles(1),'children');
lineWidth = zeros(size(lineHandle));
for j = 1:length(lineHandle)
lineWidth(j) = get(lineHandle(j),'lineWidth');
end
lineWidth = max(lineWidth)*p.Results.borderFactor;
plotPos = get(handles(1),'Position');
for j=1:16
xlim = get(handles(j),'xLim');
ylim = get(handles(j),'yLim');
xStep = (xlim(2) - xlim(1))/plotPos(3)/figPos(3)*lineWidth/2;
yStep = (ylim(2) - ylim(1))/plotPos(4)/figPos(3)*lineWidth;
set(handles(j),'XLim',[xlim(1)-xStep,xlim(2)+xStep]);
set(handles(j),'YLim',[ylim(1)-yStep,ylim(2)+yStep]);
end
% set font size of all graphics objects if fontsize was passed
if ~any(strcmpi('fontsize',p.UsingDefaults))
set(get(gcf,'children'),'FontSize',p.Results.fontsize);
end
% optionally create legend (this will increase the width of the figure!)
if ~any(strcmpi('legend',p.UsingDefaults))
if iscell(p.Results.legend)
Labels = p.Results.legend{2};
if isnumeric(Labels)
Labels = cellfun(@(x) num2str(x),num2cell(Labels),'uniformoutput',0);
end
pos = zeros(4,16);
for i=1:16
set(handles(i),'units','pixels');
pos(:,i) = get(handles(i),'Position');
end
lgd = legend(handles(4),Labels,'location','northeastoutside');
set(lgd,'units','pixels','fontsize',p.Results.fontsize);
title(lgd,p.Results.legend{1},'FontSize',p.Results.fontsize);
lgd_pos = get(lgd,'Position');
h_fig.Position = h_fig.Position + [0 0 lgd_pos(3) 0];
for i=1:16
set(handles(i),'Position',pos(:,i));
end
end
end
end
function handle = linePlot(X,Y,YEr,varargin)
% this program just makes line-plots easier. Documentation is similar to
% the MMplot program, except that this only makes 1 plot not a 4x4 plot array.
% EXAMPLE:
%
% plotStuff = {...
% 'size',[700,500],...
% 'fontsize',16,...
% 'title','Title of Graph',...
% 'xLabel','X Axis',...
% 'yLabel','Y Axis',...
% 'limy',0.1,...
% 'lineNV',{'lineWidth',2},...
% 'axNV',{'XGrid','on','YGrid','on'}...
% };
%
% h = plotter(Lam,MMgetp(MM1,'ld'),'b',plotStuff{:});
% plotter(Lam,MMgetp(MM1,'ldp'),'r',plotStuff{:},'handle',h);
%
% or
%
% h = plotter(Lam,[MMgetp(MM1,'ld') ; MMgetp(MM1,'ldp')],plotStuff{:});
p = inputParser;
% input validation functions
valFun1 = @(x) ischar(x) && ...
all(~strcmpi(x,...
{'handle','lineNV','limY','fontsize','axNV','size','title','xLabel',...
'yLabel','legend','legendLocation'}));
valFun2 = @(x) isscalar(x)&&isnumeric(x);
% setup input scheme
addRequired(p,'X',@isnumeric);
addRequired(p,'Y',@isnumeric);
addRequired(p,'YEr',@isnumeric);
addOptional(p,'LineSpec','-',valFun1)
addParameter(p,'handle',gobjects(1), @ishandle);
addParameter(p,'limY',0,valFun2)
addParameter(p,'fontsize',12,valFun2)
addParameter(p,'axNV',{},@iscell)
addParameter(p,'lineNV',{},@iscell)
addParameter(p,'size',[700 500],@(x) length(x) == 2 && isnumeric(x))
addParameter(p,'title','',@ischar)
addParameter(p,'xLabel','',@ischar)
addParameter(p,'yLabel','',@ischar)
addParameter(p,'legend',{},@(x) iscell(x) || strcmp(x,'none'))
addParameter(p,'legendLocation','northeastoutside',@ischar)
parse(p,X,Y,YEr,varargin{:}) %parse inputs
% create new figure if no valid handles were given
if any(strcmpi('handle',p.UsingDefaults))
% Determine how large to make the figure window, according to the screensize.
scrsz = get(0,'screensize');
figPos = [1 5 p.Results.size];
if figPos(3) > scrsz(3)
figPos(3) = scrsz(3);
warning(['Figure horizontal dimension set to the maximum value of ',...
num2str(figPos(3)),' pixels.'])
end
if figPos(4) > (scrsz(4) - 99) % 99 pixels is the height of the OSX status bar on my machine
figPos(4) = (scrsz(4) - 99);
warning(['Figure vertical dimension set to the maximum value of ',...
num2str(figPos(4)),' pixels.'])
end
h_fig = figure('position',figPos,'units','pixels'); %create figure
handle = axes;
hold(handle,'on')
box(handle,'on')
else
handle = p.Results.handle;
h_fig = get(handle,'parent');
figPos = get(h_fig,'Position');
end
% plot line and set Line Properties
plot(handle,X,Y(:,:),p.Results.LineSpec,p.Results.lineNV{:})
% set Axes properties
axis(handle,'tight'); % first, axes are set to tight
if ~isempty(p.Results.axNV)
set(handle,p.Results.axNV{:});
end
if p.Results.limY ~= 0 % modify axes bounds if limY is set
lim = p.Results.limY;
Ylim = get(handle,'YLim');
if (Ylim(2) - Ylim(1)) < lim
avg = (Ylim(2) + Ylim(1))./2;
Ylim(2) = avg + lim/2;
Ylim(1) = avg - lim/2;
set(handle,'Ylim',Ylim);
end
end
% Adjust plot limits so that lines do not overlap axis borders.
lineHandle = get(handle,'children');
lineWidth = zeros(size(lineHandle));
for j = 1:length(lineHandle)
if strcmp(get(lineHandle(j),'Marker'),'none')
lineWidth(j) = get(lineHandle(j),'LineWidth');
else
lineWidth(j) = get(lineHandle(j),'MarkerSize');
end
end
lineWidth = max(lineWidth);
plotPos = get(handle,'Position');
xlim = get(handle,'xLim');
ylim = get(handle,'yLim');
xStep = (xlim(2) - xlim(1))/plotPos(3)/figPos(3)*lineWidth/2;
yStep = (ylim(2) - ylim(1))/plotPos(4)/figPos(3)*lineWidth;
set(handle,'XLim',[xlim(1)-xStep,xlim(2)+xStep]);
set(handle,'YLim',[ylim(1)-yStep,ylim(2)+yStep]);
% add the labels if passed
if ~any(strcmpi('title',p.UsingDefaults))
title(p.Results.title,'FontSize',p.Results.fontsize,'FontWeight','normal');
end
if ~any(strcmpi('xLabel',p.UsingDefaults))
xlabel(p.Results.xLabel,'FontSize',p.Results.fontsize);
end
if ~any(strcmpi('yLabel',p.UsingDefaults))
ylabel(p.Results.yLabel,'FontSize',p.Results.fontsize);
end
% set font size of all graphics objects if fontsize was passed
if ~any(strcmpi('fontsize',p.UsingDefaults))
set(get(gcf,'children'),'FontSize',p.Results.fontsize);
end
% optionally create legend (this will increase the width of the figure!)
if ~any(strcmpi('legend',p.UsingDefaults))
if iscell(p.Results.legend)
Labels = p.Results.legend{2};
if isnumeric(Labels)
Labels = cellfun(@(x) num2str(x),num2cell(Labels),'uniformoutput',0);
end
set(handle,'units','pixels');
pos = get(handle,'Position');
lgd = legend(handle,Labels,'location',p.Results.legendLocation);
set(lgd,'units','pixels','fontsize',p.Results.fontsize);
title(lgd,p.Results.legend{1},'FontSize',p.Results.fontsize);
if ~isempty(regexp(p.Results.legendLocation,'.outside','ONCE'))
lgd_pos = get(lgd,'Position');
h_fig.Position = h_fig.Position + [0 0 lgd_pos(3) 0];
set(handle,'Position',pos);
end
end
end
end
% ========================================================================= |
github | shane-nichols/smn-thesis-master | MPlot3D.m | .m | smn-thesis-master/MPlot3D.m | 15,677 | utf_8 | 1a8b8381948165ef6054487ebde73297 | classdef (InferiorClasses = {?matlab.graphics.axis.Axes}) MPlot3D < handle
properties
uniquezero = true
palette = 'HotCold Bright'
gs = 0
width
fontsize = 14
limz = 1e-3
norm = true
hSpacing = 3;
vSpacing = 3;
cbw = 10;
end
properties (SetAccess = protected)
figHandle
axesHandles = gobjects(4);
colorbarHandles = gobjects(4);
end
properties (Hidden)
maskHandles
end
methods
function obj = MPlot3D(varargin)
obj.figHandle = figure;
obj.width = getFigWidth;
plot(obj,varargin{:});
end
function plot(obj,data,varargin)
% \\ Required positional input:
% data: [4,4,X,Y] array. X and Y are horizontal and vertical plot
% dimensions.
% \\ Optional Name-Value pairs that set object properties
% 'uniquezero', logical: make zero white or black in colormaps
% Default is true.
% 'palette', string: name of a colormap, including custom
% ones in local function colPalette
% Default is 'Fireice'
% 'gs', [min max]: GlobalScale. plot limits of all Z-scales between min, max.
% If not given, each MM element maps to its own min and max value.
% Only 1 colorbar is drawn with GlobalScale is set
% 'fontsize', scalar: Size of font in colorbars
% 'width', scalar: Width of figure in inches. Height is
% computed automatically to ensure no streching of plots (figure can go
% off page, in which case, reduce value of 'width'. Default is %60 of
% the monitor or with dual displays of different size, who knowns...
% 'limz', scalar: limits how small the range of the z-axes can be.
% 'hSpacing', scalar: sets the horizontal space between plots in pixels
% 'vSpacing', scalar: sets the vertical space between plots in pixels
% 'cbw', scalar: Colorbar width in pixels.
p = inputParser;
% setup input scheme
addRequired(p,'obj',@(x) isa(x,'MPlot3D'))
addRequired(p,'data',@(x) isnumeric(x) && ndims(x) == 4)
addParameter(p,'norm',obj.norm,@(x) x == 1 || x == 0)
addParameter(p,'uniquezero',obj.uniquezero,@(x) x == 1 || x == 0)
addParameter(p,'palette',obj.palette,@(x) ischar(x) )
addParameter(p,'limz',obj.limz,@(x) isscalar(x)&&isnumeric(x))
addParameter(p,'fontsize',obj.fontsize,@(x) isscalar(x)&&isnumeric(x))
addParameter(p,'width',obj.width,@(x) isscalar(x) && isnumeric(x)) % inches
addParameter(p,'gs',obj.gs,@(x) length(x) == 2 && isnumeric(x))
addParameter(p,'hSpacing',obj.hSpacing,@isscalar)
addParameter(p,'vSpacing',obj.vSpacing,@isscalar)
addParameter(p,'cbw',obj.cbw,@isscalar)
parse(p,obj,data,varargin{:}) %parse inputs
sz = size(data);
obj.norm = p.Results.norm;
obj.uniquezero = p.Results.uniquezero;
obj.palette = p.Results.palette;
obj.gs = p.Results.gs;
obj.limz = p.Results.limz;
obj.fontsize = p.Results.fontsize;
obj.width = p.Results.width;
obj.hSpacing = p.Results.hSpacing;
obj.vSpacing = p.Results.vSpacing;
obj.cbw = p.Results.cbw;
% normalize and replace NaN with 0 if obj.norm is set
if obj.norm
data = data ./ data(1,1,:,:);
data(isnan(data)) = 0;
end
dummy = uicontrol('style', 'text', 'fontsize', obj.fontsize, 'units', 'pixels');
set(dummy,'String', '-0.000');
cblbextents = get(dummy, 'extent');
cblbsz = cblbextents(3); % colorbar label size
delete(dummy)
figWidth = (obj.width) * obj.figHandle.Parent.ScreenPixelsPerInch;
if obj.gs==0
plotW = (figWidth - 9*obj.vSpacing-4*(obj.cbw + cblbsz))/4;
plotH = sz(3)/sz(4)*plotW;
figHeight = plotH*4+5*obj.hSpacing;
totalPlotWidth = obj.vSpacing*2+obj.cbw+cblbsz+plotW;
plotPosFun = @(j,k) [ (obj.vSpacing+(k-1)*totalPlotWidth)/figWidth...
,(obj.hSpacing+(4-j)*(plotH+obj.hSpacing))/figHeight,...
plotW/figWidth,...
plotH/figHeight];
set(obj.figHandle,'Position',[0,0,figWidth,figHeight],'units','pixels');
for j=1:4
for k=1:4
if isgraphics(obj.axesHandles(j,k))
subplot(obj.axesHandles(j,k), ...
'position',plotPosFun(j,k),'units','pixels');
else
obj.axesHandles(j,k) = ...
subplot('position',plotPosFun(j,k),'units','pixels');
end
clim = [min(min(data(j,k,:,:))),max(max(data(j,k,:,:)))];
if obj.limz ~= 0 % modify axes bounds if limz is set
if (clim(2) - clim(1)) < obj.limz
avg = (clim(2) + clim(1))./2;
clim(2) = avg + obj.limz/2;
clim(1) = avg - obj.limz/2;
end
end
pos = get(obj.axesHandles(j,k),'Position');
imagesc(squeeze(data(j,k,:,:)),'Parent',obj.axesHandles(j,k),clim)
axis(obj.axesHandles(j,k),'off')
colormap(obj.axesHandles(j,k),makeColormap(clim,obj.uniquezero,obj.palette))
obj.colorbarHandles(j,k) = colorbar(obj.axesHandles(j,k),'units','pixels',...
'Position',[pos(1)+pos(3)+obj.vSpacing,pos(2)+cblbextents(4)/4,...
obj.cbw,pos(4)-cblbextents(4)/2],...
'fontsize',obj.fontsize);
end
end
if any(strcmp('nonorm', p.UsingDefaults))
obj.axesHandles(1,1).CLim = [0 1];
end
else
plotW = (figWidth - 6*obj.vSpacing - 2*obj.cbw - cblbsz)/4;
plotH = sz(3)/sz(4)*plotW;
figHeight = plotH*4+5*obj.hSpacing;
plotPosFun = @(j,k) [ (obj.vSpacing+(k-1)*(plotW+obj.vSpacing))/figWidth,...
(obj.hSpacing+(4-j)*(plotH+obj.hSpacing))/figHeight,...
plotW/figWidth,...
plotH/figHeight];
set(obj.figHandle,'Position',[0,0,figWidth,figHeight],'units','pixels');
for j=1:4
for k=1:4
if isgraphics(obj.axesHandles(j,k))
subplot(obj.axesHandles(j,k),...
'position',plotPosFun(j,k),'units','pixels');
else
obj.axesHandles(j,k) = ...
subplot('position',plotPosFun(j,k),'units','pixels');
end
pos = get(obj.axesHandles(j,k),'Position');
imagesc(squeeze(data(j,k,:,:)),'Parent',obj.axesHandles(j,k),obj.gs)
colormap(obj.axesHandles(j,k),makeColormap(obj.gs,obj.uniquezero,obj.palette))
axis(obj.axesHandles(j,k),'off')
end
end
obj.colorbarHandles(1,4) = colorbar(obj.axesHandles(1,4),'units','pixels',...
'Position',[pos(1)+pos(3)+obj.vSpacing,cblbextents(4)/4+6,...
obj.cbw,figHeight-cblbextents(4)/2-12],...
'fontsize',obj.fontsize);
end
end
function mmdata = getPlotData(obj)
% h: [4,4] array of axis handles
mmdata = zeros([4, 4, size(obj.axesHandles(1,1).Children.CData)], ...
class(obj.axesHandles(1,1).Children.CData));
for j=1:4
for k=1:4
mmdata(j,k,:,:) = obj.axesHandles(j,k).Children.CData;
end
end
end
function replacePlotData(obj,mmdata)
% MMreplace3DplotData replaces the data in 4x4 intensity plots.
% h is a [4,4] array of axis handles
% Data is a 4x4xNxM array. Data size should not be different than data in
% plots.
for j=1:4
for k=1:4
obj.axesHandles(j,k).Children.CData = squeeze(mmdata(j,k,:,:));
end
end
end
function update(obj,varargin)
obj.figHandle.Visible = 'off';
data = getPlotData(obj);
delete(obj.colorbarHandles)
obj.colorbarHandles = gobjects(4);
plot(obj,data,varargin{:});
obj.figHandle.Visible = 'on';
end
function drawMask(obj, i, j)
sz = size(obj.axesHandles(1,1).Children.CData);
h_im = obj.axesHandles(i,j).Children;
e = imellipse(obj.axesHandles(i,j),...
[sz(1)*0.1,sz(2)*0.1,0.8*sz(1),0.8*sz(1)]);
obj.maskHandles = {e,h_im};
end
function setElipse(obj, position)
setPosition(obj.maskHandles{1}, position);
end
function applyMask(obj)
mask = createMask(obj.maskHandles{1}, obj.maskHandles{2});
delete(obj.maskHandles{1})
for j=1:4
for k=1:4
obj.axesHandles(j,k).Children.CData = ...
obj.axesHandles(j,k).Children.CData.*mask;
end
end
end
function applyMaskWithTrim(obj)
mask = createMask(obj.maskHandles{1},obj.maskHandles{2});
pos = obj.maskHandles{1}.getPosition;
pos = [floor(pos(1:2)),ceil(pos(3:4))];
delete(obj.maskHandles{1})
data = zeros(4,4,pos(4),pos(3),'single');
idx = {pos(2):(pos(2)+pos(4)-1),pos(1):(pos(1)+pos(3)-1)};
for j=1:4
for k=1:4
data(j,k,:,:) = ...
obj.axesHandles(j,k).Children.CData(idx{:}).*mask(idx{:});
end
end
plot(obj,data)
end
function print(obj,filepath)
print(obj.figHandle,filepath,'-depsc');
end
function flipX(obj)
replacePlotData(obj, flip(getPlotData(obj), 4));
end
end
end
function width = getFigWidth % sets default width to 60% of display width
scrsz = get(0,'screensize');
width = 0.6*scrsz(3)/get(0,'ScreenPixelsPerInch');
end
function colAr = colPalette(palette)
% these are custom colormaps. A colormap is just a Nx4 matrix. The
% first column are values between 0 and 256 that position a color marker.
% The 2nd, 3rd, and 4th columns are RGB color values. Names of matlab
% colormaps can also be handed to this function.
switch palette
case 'HotCold Bright'
colAr = ...
[0 0 65 220;...
36 0 90 240;...
76 0 253 253;...
128 250 250 250;...
182 255 242 0;...
224 255 127 0;...
256 255 0 0];
case 'HotCold Dark'
colAr = ...
[0 0 253 253;...
36 1 114 239;...
76 0 90 240;...
128 0 0 0;...
182 255 0 0;...
224 255 127 0;...
256 255 242 0];
case 'TwoTone Bright'
colAr = ...
[0 0 0 255;...
128 255 255 255;...
256 255 0 0];
case 'TwoTone Dark'
colAr = ...
[0 0 0 255;...
128 0 0 0;...
256 255 0 0];
case 'Fireice'
%Copyright (c) 2009, Joseph Kirk
%All rights reserved.
clrs = [0.75 1 1; 0 1 1; 0 0 1;...
0 0 0; 1 0 0; 1 1 0; 1 1 0.75];
y = -3:3;
m = 64;
if mod(m,2)
delta = min(1,6/(m-1));
half = (m-1)/2;
yi = delta*(-half:half)';
else
delta = min(1,6/m);
half = m/2;
yi = delta*nonzeros(-half:half);
end
colAr = cat(2,(0:4:255).',255*interp2(1:3,y,clrs,1:3,yi));
case 'Spectral'
colAr = cbrewer('div', 'Spectral', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'RdYlGn'
colAr = cbrewer('div', 'RdYlGn', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'RdYlBu'
colAr = cbrewer('div', 'RdYlBu', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'RdBu'
colAr = cbrewer('div', 'RdBu', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'RdGy'
colAr = cbrewer('div', 'RdGy', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'PuOr'
colAr = cbrewer('div', 'PuOr', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'PRGn'
colAr = cbrewer('div', 'PRGn', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'PiYG'
colAr = cbrewer('div', 'PiYG', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
case 'BrBG'
colAr = cbrewer('div', 'BrBG', 11) .* 255;
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
otherwise
colAr = colormap(palette) .* 255; % to use other colormaps
t1 = linspace(0,256,size(colAr, 1)).';
colAr = [t1, colAr];
end
end
function fracIndx = fracIndex(array,x)
fracIndx = zeros(1,length(x));
for idx = 1:length(x)
if x >= array(end)
fracIndx(idx) = length(array);
elseif x(idx) <= array(1)
fracIndx(idx) = 1;
else
a = find(array <= x(idx));
a = a(length(a));
b = find(array > x(idx));
b = b(1);
fracIndx(idx) = a+(x(idx)-array(a))/(array(b)-array(a));
end
end
end
function cm = makeColormap(clim,b_uniqueZero,palette)
dmin=clim(1);
dmax=clim(2);
if dmax == dmin
dmax=1;
dmin=0;
end
if b_uniqueZero == true
Zscale = zeros(1,256);
if abs(dmin) < abs(dmax)
didx = (dmax - dmin)/(2*dmax);
for idx = 0:255
Zscale(idx+1) = 256 - didx*idx;
end
else
didx = (dmin-dmax)/(2*dmin);
for idx = 0:255
Zscale(idx+1) = idx*didx;
end
Zscale = flip(Zscale);
end
else
Zscale = flip(1:256);
end
colAr = colPalette(palette);
cm = zeros(256,3);
for n = 1:256
x = fracIndex(colAr(:,1),Zscale(n));
cm(n,1) = interp1(colAr(:,2),x);
cm(n,2) = interp1(colAr(:,3),x);
cm(n,3) = interp1(colAr(:,4),x);
end
cm = cm./255;
cm = flip(cm,1);
end
|
github | shane-nichols/smn-thesis-master | genop.m | .m | smn-thesis-master/dependencies/Multiprod_2009/Testing/genop.m | 3,837 | utf_8 | 2c087f1f1c6d8843c6f5198716d04526 | function z = genop(op,x,y)
%GENOP Generalized array operations.
% GENOP(OP, X, Y) applies the function OP to the arguments X and Y where
% singleton dimensions of X and Y have been expanded so that X and Y are
% the same size, but this is done without actually copying any data.
%
% OP must be a function handle to a function that computes an
% element-by-element function of its two arguments.
%
% X and Y can be any numeric arrays where non-singleton dimensions in one
% must correspond to the same or unity size in the other. In other
% words, singleton dimensions in one can be expanded to the size of
% the other, otherwise the size of the dimensions must match.
%
% For example, to subtract the mean from each column, you could use
%
% X2 = X - repmat(mean(X),size(X,1),1);
%
% or, using GENOP,
%
% X2 = genop(@minus,X,mean(X));
%
% where the single row of mean(x) has been logically expanded to match
% the number of rows in X, but without actually copying any data.
%
% GENOP(OP) returns a function handle that can be used like above:
%
% f = genop(@minus);
% X2 = f(X,mean(X));
% written by Douglas M. Schwarz
% email: dmschwarz (at) urgrad (dot) rochester (dot) edu
% 13 March 2006
% This function was inspired by an idea by Urs Schwarz (no relation) and
% the idea for returning a function handle was shamelessly stolen from
% Duane Hanselman.
% Check inputs.
if ~(nargin == 1 || nargin == 3)
error('genop:zeroInputs','1 or 3 arguments required.')
end
if ~isa(op,'function_handle')
error('genop:incorrectOperator','Operator must be a function handle.')
end
if nargin == 1
z = @(x,y) genop(op,x,y);
return
end
% Compute sizes of x and y, possibly extended with ones so they match
% in length.
nd = max(ndims(x),ndims(y));
sx = size(x);
sx(end+1:nd) = 1;
sy = size(y);
sy(end+1:nd) = 1;
dz = sx ~= sy;
dims = find(dz);
num_dims = length(dims);
% Eliminate some simple cases.
if num_dims == 0 || numel(x) == 1 || numel(y) == 1
z = op(x,y);
return
end
% Check for dimensional compatibility of inputs, compute size and class of
% output array and allocate it.
if ~(all(sx(dz) == 1 | sy(dz) == 1))
error('genop:argSizeError','Argument dimensions are not compatible.')
end
sz = max([sx;sy]);
z1 = op(x(1),y(1));
if islogical(z1)
z = repmat(logical(0),sz);
else
z = zeros(sz,class(z1));
end
% The most efficient way to compute the result seems to require that we
% loop through the unmatching dimensions (those where dz = 1), performing
% the operation and assigning to the appropriately indexed output. Since
% we don't know in advance which or how many dimensions don't match we have
% to create the code as a string and then eval it. To see how this works,
% uncomment the disp statement below to display the code before it is
% evaluated. This could all be done with fixed code using subsref and
% subsasgn, but that way seems to be much slower.
% Compute code strings representing the subscripts of x, y and z.
xsub = subgen(sy ~= sz);
ysub = subgen(sx ~= sz);
zsub = subgen(dz);
% Generate the code.
indent = 2; % spaces per indent level
code_cells = cell(1,2*num_dims + 1);
for i = 1:num_dims
code_cells{i} = sprintf('%*sfor i%d = 1:sz(%d)\n',indent*(i-1),'',...
dims([i i]));
code_cells{end-i+1} = sprintf('%*send\n',indent*(i-1),'');
end
code_cells{num_dims+1} = sprintf('%*sz(%s) = op(x(%s),y(%s));\n',...
indent*num_dims,'',zsub,xsub,ysub);
code = [code_cells{:}];
% Evaluate the code.
% disp(code)
eval(code)
function sub = subgen(select_flag)
elements = {':,','i%d,'};
selected_elements = elements(select_flag + 1);
format_str = [selected_elements{:}];
sub = sprintf(format_str(1:end-1),find(select_flag));
|
github | shane-nichols/smn-thesis-master | arraylab133.m | .m | smn-thesis-master/dependencies/Multiprod_2009/Testing/arraylab133.m | 2,056 | utf_8 | 46c91102f1666d2e8a3f0accd7d809ed | function c = arraylab133(a,b,d1,d2)
% Several adjustments to ARRAYLAB13:
% 1) Adjustment used in ARRAYLAB131 was not used here.
% 2) Nested statement used in ARRAYLAB132 was used here.
% 3) PERMUTE in subfunction MBYV was substituted with RESHAPE
% (faster by one order of magnitude!).
ndimsA = ndims(a); % NOTE - Since trailing singletons are removed,
ndimsB = ndims(b); % not always NDIMSB = NDIMSA
NsA = d2 - ndimsA; % Number of added trailing singletons
NsB = d2 - ndimsB;
sizA = [size(a) ones(1,NsA)];
sizB = [size(b) ones(1,NsB)];
p = sizA(d1);
r = sizB(d1);
s = sizB(d2);
% Initializing C
sizC = sizA;
sizC(d2) = s;
c = zeros(sizC);
% Vectorized indices for B and C
Nd = length(sizB);
Bindices = cell(1,Nd); % preallocating (cell array)
for d = 1 : Nd
Bindices{d} = 1:sizB(d);
end
B2size = sizB; B2size([d1 d2]) = [1 r];
B2indices = Bindices;
% B2 will be cloned P times along its singleton dimension D1 (see MBYV).
B2indices([d1 d2]) = [{ones(1, p)} Bindices(d1)]; % "Cloned" index
if sizB(d2) == 1 % PxQ IN A - Rx1 IN B
% A * B
c = mbyv(a, b, B2indices,B2size,d1,d2,p);
else % PxQ IN A - RxS IN B
Cindices = Bindices;
Cindices{d1} = 1:p;
% Building C
for Ncol = 1:s
Bindices{d2} = Ncol; Cindices{d2} = Ncol;
c(Cindices{:}) = mbyv(a, b(Bindices{:}), B2indices,B2size,d1,d2,p);
end
end
function c = mbyv(a, b2, indices, newsize, d1, d2, p)
% This is an adjustment to a subfunction used within MULTIPROD 1.3
% 1 - Transposing: Qx1 matrices in B become 1xQ matrices
b2 = reshape(b2, newsize);
% 3 - Performing dot products along dimension DIM+1
% % NOTE: b(indices{:}) has same size as A
% % NOTE: This nested statement is much faster than two separate ones.
c = sum(a .* b2(indices{:}), d2); |
github | shane-nichols/smn-thesis-master | timing_MX.m | .m | smn-thesis-master/dependencies/Multiprod_2009/Testing/timing_MX.m | 1,472 | utf_8 | 7db26cc2c4954f1026e93f2d0c44139a | function timing_MX
% TIMING_MX Speed of MX as performed by MULTIPROD and by a nested loop.
% TIMING_MX compares the speed of matrix expansion as performed by
% MULTIPROD and an equivalent nested loop. The results are shown in the
% manual (fig. 2).
% Notice that MULTIPROD enables array expansion which generalizes matrix
% expansion to arrays of any size, while the loop tested in this
% function works only for this specific case, and would be much slower
% if it were generalized to N-D arrays.
% Checking whether needed software exists
message = sysrequirements_for_testing('timeit');
if message
disp ' ', error('testing_memory_usage:Missing_subfuncs', message)
end
% Matrix expansion example (fig. 2)
disp ' '
disp 'Timing matrix expansion (see MULTIPROD manual, figure 2)'
disp ' '
a = rand(2, 5);
b = rand(5, 3, 1000, 10);
fprintf ('Size of A: %0.0fx%0.0f\n', size(a))
fprintf ('Size of B: (%0.0fx%0.0f)x%0.0fx%0.0f\n', size(b))
disp ' ', disp 'Please wait...'
disp ' '
f1 = @() loop(a,b);
f2 = @() multiprod(a,b);
t1 = timeit(f1)*1000;
fprintf('LOOP(A, B): %10.4f milliseconds\n', t1)
t2 = timeit(f2)*1000;
fprintf('MULTIPROD(A, B): %10.4f milliseconds\n', t2)
disp ' '
fprintf('MULTIPROD performed matrix expansion %6.0f times faster than a plain loop\n', t1/t2)
disp ' '
function C = loop(A,B)
for i = 1:1000
for j = 1:10
C(:,:,i,j) = A * B(:,:,i,j);
end
end |
github | shane-nichols/smn-thesis-master | timing_matlab_commands.m | .m | smn-thesis-master/dependencies/Multiprod_2009/Testing/timing_matlab_commands.m | 7,975 | utf_8 | 5384e23295d7b37d3318825a1d5c3dfe | function timing_matlab_commands
% TIMING_MATLAB_COMMANDS Testing for speed different MATLAB commands.
%
% Main conclusion: RESHAPE and * (i.e. MTIMES) are very quick!
% Paolo de Leva
% University of Rome, Foro Italico, Rome, Italy
% 2008 Dec 24
clear all
% Checking whether needed software exists
if ~exist('bsxfun', 'builtin')
message = sysrequirements_for_testing('bsxmex', 'timeit');
else
message = sysrequirements_for_testing('timeit');
end
if message
disp ' ', error('timing_matlab_commands:Missing_subfuncs', message)
end
disp ' '
disp '---------------------------------- Experiment 1 ----------------------------------'
N = 10000; P = 3; Q = 3; R = 1;
timing(N,P,Q,R);
disp '---------------------------------- Experiment 2 ----------------------------------'
N = 1000; P = 3; Q = 30; R = 1;
timing(N,P,Q,R);
disp '---------------------------------- Experiment 3 ----------------------------------'
N = 1000; P = 9; Q = 10; R = 3;
timing(N,P,Q,R);
disp '---------------------------------- Experiment 4 ----------------------------------'
N = 100; P = 9; Q = 100; R = 3;
timing(N,P,Q,R);
disp '---------------------------------- Experiment 5 ----------------------------------'
disp ' '
timing2(4, 10000);
timing2(200, 200);
timing2(10000, 4);
disp '---------------------------- Experiment 6 ----------------------------'
disp ' '
a = rand(4096, 4096);
fprintf ('Size of A: %0.0f x %0.0f\n', size(a))
disp ' '
disp ' SUM(A,1) SUM(A,2)'
f1 = @() sum(a, 1);
f2 = @() sum(a, 2);
disp ([timeit(f1), timeit(f2)])
clear all
b = rand(256, 256, 256);
fprintf ('Size of B: %0.0f x %0.0f x %0.0f\n', size(b))
disp ' '
disp ' SUM(B,1) SUM(B,2) SUM(B,3)'
f1 = @() sum(b, 1);
f2 = @() sum(b, 2);
f3 = @() sum(b, 3);
disp ([timeit(f1), timeit(f2), timeit(f3)])
disp '---------------------------- Experiment 7 ----------------------------'
disp ' '
a = rand(101,102,103);
fprintf ('Size of A: %0.0f x %0.0f x %0.0f\n', size(a))
disp ' '
disp 'Moving last dimension to first dimension:'
disp 'PERMUTE(A,[3 2 1]) PERMUTE(A,[3 1 2]) SHIFTDIM(A,2)'
disp '(SWAPPING) (SHIFTING) (SHIFTING)'
f1 = @() permute(a, [3 2 1]);
f2 = @() permute(a, [3 1 2]);
f3 = @() shiftdim(a, 2);
fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)])
disp ' ', disp ' '
a2 = f1(); s = size(a2);
a2 = f2(); s(2,:) = size(a2);
a2 = f3(); s(3,:) = size(a2);
disp (s)
disp 'Moving first dimension to last dimension:'
disp 'PERMUTE(A,[3 2 1]) PERMUTE(A,[2 3 1]) SHIFTDIM(A,1)'
disp '(SWAPPING) (SHIFTING) (SHIFTING)'
f1 = @() permute(a, [3 2 1]);
f2 = @() permute(a, [2 3 1]);
f3 = @() shiftdim(a, 1);
fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)])
disp ' ', disp ' '
a2 = f1(); s = size(a2);
a2 = f2(); s(2,:) = size(a2);
a2 = f3(); s(3,:) = size(a2);
disp (s)
disp ' '
a = rand(21,22,23,24,25);
fprintf ('Size of A: %0.0f x %0.0f x %0.0f x %0.0f x %0.0f\n', size(a))
disp ' '
disp 'Moving 4th dimension to 1st dimension:'
disp 'PERMUTE(A,[4 2 3 1 5]) PERMUTE(A,[4 1 2 3 5]) PERMUTE(A,[4 5 1 2 3])'
disp '(SWAPPING) (PARTIAL SHIFTING) (SHIFTING)'
f1 = @() permute(a, [4 2 3 1 5]);
f2 = @() permute(a, [4 1 2 3 5]);
f3 = @() permute(a, [4 5 1 2 3]);
fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)])
disp ' ', disp ' '
a2 = f1(); s = size(a2);
a2 = f2(); s(2,:) = size(a2);
a2 = f3(); s(3,:) = size(a2);
disp (s)
disp 'Moving 2nd dimension to 5th dimension:'
disp 'PERMUTE(A,[1 5 3 4 2]) PERMUTE(A,[1 3 4 5 2]) PERMUTE(A,[3 4 5 1 2])'
disp '(SWAPPING) (PARTIAL SHIFTING) (SHIFTING)'
f1 = @() permute(a, [1 5 3 4 2]);
f2 = @() permute(a, [1 3 4 5 2]);
f3 = @() permute(a, [3 4 5 1 2]);
fprintf(1, '%8.2g ', [timeit(f1), timeit(f2), timeit(f3)])
disp ' ', disp ' '
a2 = f1(); s = size(a2);
a2 = f2(); s(2,:) = size(a2);
a2 = f3(); s(3,:) = size(a2);
disp (s)
disp '---------------------------- Experiment 8 ----------------------------'
disp ' '
a =rand(101,102,103);
order = [1 2 3];
shape = [101,102,103];
f1 = @() perm(a,order);
f2 = @() ifpermute(a,order);
f3 = @() ifpermute2(a,order);
f4 = @() resh(a,shape);
f5 = @() ifreshape(a,shape);
f6 = @() ifreshape2(a,shape);
disp 'COMPARING STATEMENTS THAT DO NOTHING!'
disp ' '
fprintf ('Size of A: %0.0f x %0.0f x %0.0f\n', size(a))
disp ' '
disp 'ORDER = [1 2 3] % (keeping same order)'
disp 'SHAPE = [101,102,103] % (keeping same shape)'
disp ' '
fprintf (1,'PERMUTE(A,ORDER) .......................................... %0.4g\n', timeit(f1))
fprintf (1,'IF ~ISEQUAL(ORDER,1:LENGTH(ORDER)), A=PERMUTE(A,ORDER); END %0.4g\n', timeit(f2))
fprintf (1,'IF ~ISEQUAL(ORDER,1:3), A=PERMUTE(A,ORDER); END %0.4g\n', timeit(f3))
disp ' '
fprintf (1,'RESHAPE(A,SHAPE) .......................................... %0.4g\n', timeit(f4))
fprintf (1,'IF ~ISEQUAL(SHAPE,SIZE(A)), A=RESHAPE(A,SHAPE); END ....... %0.4g\n', timeit(f5))
fprintf (1,'IF ~ISEQUAL(SHAPE,SHAPE), A=RESHAPE(A,SHAPE); END ....... %0.4g\n', timeit(f5))
disp ' '
function a=perm(a, order)
a=permute(a, order);
function a=resh(a,shape)
a=reshape(a,shape);
function a=ifpermute(a, order)
if ~isequal(order, 1:length(order)), a=permute(a,order); end
function a=ifreshape(a, shape)
if ~isequal(shape, size(a)), a=reshape(a,shape); end
function a=ifpermute2(a, order)
if ~isequal(order, 1:3), a=permute(a,order); end
function a=ifreshape2(a, shape)
if ~isequal(shape, shape), a=reshape(a,shape); end
function timing(N,P,Q,R)
a0 = rand(1, P, Q);
b0 = rand(1, Q, R);
a = a0(ones(1,N),:,:); % Cloning along first dimension
b = b0(ones(1,N),:,:); % Cloning along first dimension
[n1 p q1] = size(a); % reads third dim even if it is 1.
[n2 q2 r] = size(b); % reads third dim even if it is 1.
disp ' '
disp 'Array Size Size Number of elements'
fprintf (1, 'A Nx(PxQ) %0.0f x (%0.0f x %0.0f) %8.0f\n', [n1 p q1 numel(a)])
fprintf (1, 'B Nx(QxR) %0.0f x (%0.0f x %0.0f) %8.0f\n', [n2 q2 r numel(b)])
f1 = @() permute(a, [2 3 1]);
f2 = @() permute(a, [1 3 2]);
f3 = @() permute(a, [2 1 3]);
f4 = @() permute(a, [1 2 3]);
f5 = @() permute(b, [2 3 1]);
f6 = @() permute(b, [1 3 2]);
f7 = @() permute(b, [2 1 3]);
f8 = @() permute(b, [1 2 3]);
disp ' '
disp ' PERMUTE(A,[2 3 1]) PERMUTE(A,[1 3 2]) PERMUTE(A,[2 1 3]) PERMUTE(A,[1 2 3])'
fprintf(1, '%20.5f', [timeit(f1), timeit(f2), timeit(f3), timeit(f4)])
disp ' '
disp ' PERMUTE(B,[2 3 1]) PERMUTE(B,[1 3 2]) PERMUTE(B,[2 1 3]) PERMUTE(B,[1 2 3])'
fprintf(1, '%20.5f', [timeit(f5), timeit(f6), timeit(f7), timeit(f8)])
disp ' '
disp ' '
disp ' RESHAPE(A,[N*P Q]) RESHAPE(B,[N R Q]) RESHAPE(B,[N 1 R Q])'
f1 = @() reshape(a, [N*P Q]);
f2 = @() reshape(b, [N R Q]);
f3 = @() reshape(b, [N 1 R Q]);
fprintf(1, '%20.5f', [timeit(f1), timeit(f2), timeit(f3)])
disp ' '
f1 = @() a .* a;
f2 = @() bsxfun(@times, a, a);
f3 = @() b .* b;
f4 = @() bsxfun(@times, b, b);
disp ' '
disp ' A .* A BSXFUN(@TIMES,A,A)'
fprintf(1, '%20.5f%20.5f\n', [timeit(f1), timeit(f2)])
disp ' B .* B BSXFUN(@TIMES,B,B)'
fprintf(1, '%20.5f%20.5f\n', [timeit(f3), timeit(f4)])
if R==1
disp ' '
disp ' NOTE: If R=1 then RESHAPE(B,[N R Q]) is equivalent to'
disp ' PERMUTE(B,[1 3 2]) but much faster!'
disp ' (at least on my system)'
end
disp ' '
function timing2(P,Q)
a = rand(P, Q);
b = rand(Q, 1);
fprintf ('Size of A: %0.0f x %0.0f\n', size(a))
fprintf ('Size of B: %0.0f x %0.0f\n', size(b))
disp ' '
disp ' A * B TONY''S TRICK BSXFUN'
f1 = @() a * b;
f2 = @() clone_multiply_sum(a, b', P);
f3 = @() sum(bsxfun(@times, a, b'), 2);
fprintf(1, '%13.5f', [timeit(f1), timeit(f2), timeit(f3)])
disp ' '
disp ' '
c = f1() - f2();
d = max(c(:));
if d > eps*20
disp 'There is an unexpected output difference:';
disp (d);
end
function c = clone_multiply_sum(a,b,P)
c = sum(a .* b(ones(1,P),:), 2); |
github | shane-nichols/smn-thesis-master | arraylab13.m | .m | smn-thesis-master/dependencies/Multiprod_2009/Testing/arraylab13.m | 1,913 | utf_8 | 942e4a25270936f264b83f4367d9b7fa | function c = arraylab13(a,b,d1,d2)
% This is the engine used in MULTIPROD 1.3 for these cases:
% PxQ IN A - Rx1 IN B
% PxQ IN A - RxS IN B (slowest)
ndimsA = ndims(a); % NOTE - Since trailing singletons are removed,
ndimsB = ndims(b); % not always NDIMSB = NDIMSA
NsA = d2 - ndimsA; % Number of added trailing singletons
NsB = d2 - ndimsB;
sizA = [size(a) ones(1,NsA)];
sizB = [size(b) ones(1,NsB)];
% Performing products
if sizB(d2) == 1 % PxQ IN A - Rx1 IN B
% A * B
c = mbyv(a, b, d1);
else % PxQ IN A - RxS IN B (least efficient)
p = sizA(d1);
s = sizB(d2);
% Initializing C
sizC = sizA;
sizC(d2) = s;
c = zeros(sizC);
% Vectorized indices for B and C
Nd = length(sizB);
Bindices = cell(1,Nd); % preallocating (cell array)
for d = 1 : Nd
Bindices{d} = 1:sizB(d);
end
Cindices = Bindices;
Cindices{d1} = 1:p;
% Building C
for Ncol = 1:s
Bindices{d2} = Ncol; Cindices{d2} = Ncol;
c(Cindices{:}) = mbyv(a, b(Bindices{:}), d1);
end
end
function c = mbyv(a, b, dim)
% NOTE: This function is part of MULTIPROD 1.3
% 1 - Transposing: Qx1 matrices in B become 1xQ matrices
order = [1:dim-1, dim+1, dim, dim+2:ndims(b)];
b = permute(b, order);
% 2 - Cloning B P times along its singleton dimension DIM.
% Optimized code for B2 = REPMAT(B, [ONES(1,DIM-1), P]).
% INDICES is a cell array containing vectorized indices.
P = size(a, dim);
siz = size(b);
siz = [siz ones(1,dim-length(siz))]; % Ones are added if DIM > NDIMS(B)
Nd = length(siz);
indices = cell(1,Nd); % preallocating
for d = 1 : Nd
indices{d} = 1:siz(d);
end
indices{dim} = ones(1, P); % "Cloned" index for dimension DIM
b2 = b(indices{:}); % B2 has same size as A
% 3 - Performing dot products along dimension DIM+1
c = sum(a .* b2, dim+1); |
github | shane-nichols/smn-thesis-master | materialLib.m | .m | smn-thesis-master/materialLib/materialLib.m | 6,718 | utf_8 | 6395189afc14d401689fa1ea8dc486c6 | function [epsilon,alpha,mu] = materialLib(material, wavelengths, varargin)
% small library of optical functions for anisotropic materials
Nwl = length(wavelengths);
epsilon = zeros(3,3,Nwl);
mu = setDiag(ones(3,Nwl));
alpha = 0;
switch material
case 'rubrene'
data = load('rubreneOptfun.mat');
data = data.filetosave;
eV = (1239.8)./wavelengths;
epsilon = setDiag( ((interp1(data(:,1),data(:,2:4),eV)).^2)' );
case '+EDS'
alpha = zeros(3,3,Nwl);
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 1.06482*lam2./(lam2 - 0.0103027)...
+2.3712*lam2./(lam2 - 92.3287) + 1.2728;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 1.07588*lam2./(lam2 - 0.0101915)...
+2.64847*lam2./(lam2 - 94.8497) + 1.2751;
lam2 = wavelengths.^2;
alpha(1,1,:) = wavelengths.^3*(0.0146441)./(lam2 - 100.202^2).^2;
alpha(3,3,:) = wavelengths.^3*(-0.0301548)./(lam2 - 100^2).^2;
alpha(2,2,:) = alpha(1,1,:);
case '-EDS'
alpha = zeros(3,3,Nwl);
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 1.06482*lam2./(lam2 - 0.0103027)...
+2.3712*lam2./(lam2 - 92.3287) + 1.2728;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 1.07588*lam2./(lam2 - 0.0101915)...
+2.64847*lam2./(lam2 - 94.8497) + 1.2751;
lam2 = wavelengths.^2;
alpha(1,1,:) = wavelengths.^3*(-0.0146441)./(lam2 - 100.202^2).^2;
alpha(3,3,:) = wavelengths.^3*(0.0301548)./(lam2 - 100^2).^2;
alpha(2,2,:) = alpha(1,1,:);
case 'SYEDS'
if nargin > 2
c = varargin{1};
else
c = 3.1547;
end
alpha = zeros(3,3,Nwl);
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 1.06482*lam2./(lam2 - 0.0103027)...
+2.3712*lam2./(lam2 - 92.3287) + 1.2728;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 1.07588*lam2./(lam2 - 0.0101915)...
+2.64847*lam2./(lam2 - 94.8497) + 1.2751;
data = load('SYEDS');
data = data.SYEDS;
data = ((interp1(real(data(1,:)).',[real(data(2,:));imag(data(2,:))].',wavelengths)))';
epsilon(1,1,:) = squeeze(c*(data(1,:) + 1i*data(2,:))) + squeeze(epsilon(1,1,:)).';
lam2 = wavelengths.^2;
alpha(1,1,:) = -wavelengths.^3*(0.0146441)./(lam2 - 100.202^2).^2;
alpha(3,3,:) = -wavelengths.^3*(-0.0301548)./(lam2 - 100^2).^2;
alpha(2,2,:) = alpha(1,1,:);
case '+quartz'
alpha = zeros(3,3,Nwl);
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 1.07044083*lam2./(lam2 - 0.0100585997)...
+1.10202242*lam2./(lam2 - 100) + 1.28604141;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 1.09509924*lam2./(lam2 - 0.0102101864)...
+1.15662475*lam2./(lam2 - 100) + 1.28851804;
lam2 = wavelengths.^2;
alpha(1,1,:) = wavelengths.^3*(0.0198)./(lam2 - 93^2).^2;
alpha(3,3,:) = wavelengths.^3*(-0.0408)./(lam2 - 87^2).^2;
alpha(2,2,:) = alpha(1,1,:);
case '-quartz'
alpha = zeros(3,3,Nwl);
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 1.07044083*lam2./(lam2 - 0.0100585997)...
+1.10202242*lam2./(lam2 - 100) + 1.28604141;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 1.09509924*lam2./(lam2 - 0.0102101864)...
+1.15662475*lam2./(lam2 - 100) + 1.28851804;
lam2 = wavelengths.^2;
alpha(1,1,:) = -wavelengths.^3*(0.0198)./(lam2 - 93^2).^2;
alpha(3,3,:) = -wavelengths.^3*(-0.0408)./(lam2 - 87^2).^2;
alpha(2,2,:) = alpha(1,1,:);
case 'sapphire'
osc1A = [1.4313493,0.65054713,5.3414021];
osc1E = [0.0726631,0.1193242,18.028251].^2;
osc2A = [1.5039759,0.55069141,6.5927379];
osc2E = [0.0740288,0.1216529,20.072248].^2;
lam2 = (wavelengths/1000).^2;
for n = 1:Nwl
epsilon(1,1,n) = sum(lam2(n)*osc1A./(lam2(n) - osc1E))+1;
epsilon(3,3,n) = sum(lam2(n)*osc2A./(lam2(n) - osc2E))+1;
end
epsilon(2,2,:) = epsilon(1,1,:);
case 'aBBO'
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = -lam2*0.0155+0.0184./(lam2 - 0.0179)+2.7405;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = -lam2*0.0044+0.0128./(lam2 - 0.0156)+2.373;
case 'KDPnoG' % potassium acid phthalate without gyration
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = lam2.*13.0052/(lam2 - 400)...
+0.01008956./(lam2 - 0.0129426) + 2.259276;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = lam2.*3.2279924./(lam2 - 400)...
+0.008637494./(lam2 - 0.012281) + 2.132668;
case 'LiNbO3'
osc1A = [2.6734,1.229,12.614];
osc1E = [0.01764,0.05914,474.6];
osc2A = [2.9804,0.5981,8.9543];
osc2E = [0.02047,0.0666,416.08];
lam2 = (wavelengths/1000).^2;
for n = 1:Nwl
epsilon(1,1,n) = sum(lam2(n)*osc1A./(lam2(n) - osc1E))+1;
epsilon(3,3,n) = sum(lam2(n)*osc2A./(lam2(n) - osc2E))+1;
end
epsilon(2,2,:) = epsilon(1,1,:);
case 'KDP'
%This includes epsilon from Zernike (1964) and alpha from
%Konstantinova (2000)
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = (13.00522*lam2./(lam2 - 400))+(0.01008956./(lam2 - 0.0129426))+2.259276;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = (3.2279924*lam2./(lam2 - 400))+(0.008637494./(lam2 - 0.0122810))+2.132668;
lam2 = wavelengths.^2;
alpha = zeros(3,3,Nwl);
alpha(1,2,:) = wavelengths.^3.*(.023)./(lam2 - 10^2).^2;
alpha(2,1,:) = alpha(1,2,:);
case 'KAP'
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = (-0.013296131.*lam2)+(0.037318762./(lam2 - (0.175493731^2)))+2.663434655;
epsilon(2,2,:) = 2.670444937+(0.031617528./(lam2-(0.208293225^2)))-(0.004014395.*lam2);
epsilon(3,3,:) = 2.196073191+(0.015025722./(lam2-(0.190981743^2)))-(0.006100780.*lam2);
case 'TiO2'
lam2 = (wavelengths/1000).^2;
epsilon(1,1,:) = 0.2441./(lam2 - 0.0803)+5.913;
epsilon(2,2,:) = epsilon(1,1,:);
epsilon(3,3,:) = 0.3322./(lam2 - 0.0843)+7.197;
case 'test'
epsilon(1,1,:) = ones(Nwl,1)*(2.2);
epsilon(2,2,:) = ones(Nwl,1)*(2.2);
epsilon(3,3,:) = ones(Nwl,1)*(2.2);
end
end
function out = setDiag(diag)
out = zeros(size(diag, 1), size(diag, 1), size(diag, 2));
for i=1:size(diag, 1)
out(i,i,:) = diag(i,:);
end
end |
github | shane-nichols/smn-thesis-master | MPlot4D.m | .m | smn-thesis-master/misc_utilities/MPlot4D.m | 14,618 | utf_8 | 8b22ef4fe9c79bd9e96465da950b8e1c | classdef (InferiorClasses = {?matlab.graphics.axis.Axes}) MPlot4D < handle
% this is a more powerful but less polished version of MPlot3D. It can
% accept arrays of dimension 5 and make videos that run over the 5th
% dimension. The constructor requires an array xData, which is the physical
% values ascribed to the 5th dimension of Data (usually wavelength).
% These values are put into a text box above the MM plots. I never got
% around to documenting this class...
properties
Data
xData
uniquezero = true
palette = 'Fireice'
gs = 0
width
fontsize = 14
limz = 1e-3
norm = true
hSpacing = 3 %vertical spacing of subplots
vSpacing = 3 % horizonal spacing of subplots
cbw = 10
end
properties (SetAccess = protected)
figHandle
axesHandles = gobjects(4)
colorbarHandles = gobjects(4)
xDataTextBox
end
properties (Hidden)
maskHandles
end
methods
function obj = MPlot4D(data, xData, varargin)
obj.figHandle = figure;
obj.width = getFigWidth;
obj.Data = data;
obj.xData = xData;
plot(obj, xData(1), varargin{:});
end
function parseProperties(obj, varargin)
% Optional Name-Value pairs
% 'uniquezero',logical: make 0 white or black in color palettes
% Default is true.
% 'palette','colPalette': string giving name of a case in colPalette.m
% Default is 'Fireice'
% 'gs',[min max]: GlobalScale, plot limits of all Z-scales between min, max.
% If not given, each MM element maps to its own min and max value.
% Only 1 colorbar is drawn with GlobalScale is set
% 'fontsize',scalar: Size of font in colorbars
% 'width',scalar: Width of figure in inches (but probably not inches). Height is
% computed automatically to ensure no streching of plots (figure can go
% off page, in which case, reduce value of 'width'. Default is %60 of
% monitor on a Mac.
% 'limz',scalar: limits how small the range of the z-axes can be.
% 'hSpacing',scalar: horizontal space between axes, in pixels.
% 'vSpacing',scalar: vertical space between axes, in pixels.
% 'cbw',scalar: Width of the colorbars, in pixels.
p = inputParser;
% setup input scheme
addRequired(p,'obj',@(x) isa(x,'MPlot4D'))
addParameter(p,'norm',obj.norm,@(x) strcmp(x,'nonorm'))
addParameter(p,'uniquezero',obj.uniquezero,@islogical)
addParameter(p,'palette',obj.palette,@ischar)
addParameter(p,'limz',obj.limz,@(x) isscalar(x)&&isnumeric(x))
addParameter(p,'fontsize',obj.fontsize,@(x) isscalar(x)&&isnumeric(x))
addParameter(p,'width',obj.width,@(x) isscalar(x) && isnumeric(x)) % inches
addParameter(p,'gs',obj.gs,@(x) length(x) == 2 && isnumeric(x))
addParameter(p,'hSpacing',obj.hSpacing,@isscalar)
addParameter(p,'vSpacing',obj.vSpacing,@isscalar)
addParameter(p,'cbw',obj.cbw,@isscalar)
parse(p, obj, varargin{:}) %parse inputs
obj.norm = p.Results.norm;
obj.uniquezero = p.Results.uniquezero;
obj.palette = p.Results.palette;
obj.gs = p.Results.gs;
obj.limz = p.Results.limz;
obj.fontsize = p.Results.fontsize;
obj.width = p.Results.width;
obj.hSpacing = p.Results.hSpacing;
obj.vSpacing = p.Results.vSpacing;
obj.cbw = p.Results.cbw;
end
function normalize(obj)
obj.Data = obj.Data ./ obj.Data(1,1,:,:,:);
obj.Data(isnan(obj.Data)) = 0;
end
function plot(obj, xVal, varargin)
if ~isempty(varargin)
parseProperties(obj, varargin{:})
end
dataIndex = round(fracIndex(obj.xData,xVal));
sz = size(obj.Data);
dummy = uicontrol('style', 'text', 'fontsize', obj.fontsize, 'units', 'pixels');
set(dummy,'String', '-0.000');
cblbextents = get(dummy, 'extent');
cblbsz = cblbextents(3); % colorbar label size
delete(dummy)
figWidth = (obj.width) * obj.figHandle.Parent.ScreenPixelsPerInch;
if obj.gs==0
plotW = (figWidth - 9*obj.hSpacing-4*(obj.cbw + cblbsz))/4;
plotH = sz(3)/sz(4)*plotW;
figHeight = plotH*4+5*obj.vSpacing + cblbextents(4);
totalPlotWidth = obj.hSpacing*2+obj.cbw+cblbsz+plotW;
plotPosFun = @(j,k) [ (obj.hSpacing+(k-1)*totalPlotWidth)/figWidth...
,(obj.vSpacing+(4-j)*(plotH+obj.vSpacing))/figHeight,...
plotW/figWidth,...
plotH/figHeight];
set(obj.figHandle,'Position',[0,0,figWidth,figHeight],'units','pixels');
for j=1:4
for k=1:4
obj.axesHandles(j,k) = ...
subplot('position',plotPosFun(j,k),'units','pixels');
clim = [min(min(obj.Data(j,k,:,:,dataIndex))),max(max(obj.Data(j,k,:,:,dataIndex)))];
if obj.limz ~= 0 % modify axes bounds if limz is set
if (clim(2) - clim(1)) < obj.limz
avg = (clim(2) + clim(1))./2;
clim(2) = avg + obj.limz/2;
clim(1) = avg - obj.limz/2;
end
end
pos = get(obj.axesHandles(j,k),'Position');
imagesc(squeeze(obj.Data(j,k,:,:,dataIndex)),'Parent',obj.axesHandles(j,k),clim)
axis(obj.axesHandles(j,k),'off')
colormap(obj.axesHandles(j,k),makeColormap(clim,obj.uniquezero,obj.palette))
obj.colorbarHandles(j,k) = colorbar(obj.axesHandles(j,k),'units','pixels',...
'Position',[pos(1)+pos(3)+obj.hSpacing,pos(2)+cblbextents(4)/4,...
obj.cbw,pos(4)-cblbextents(4)/2],...
'fontsize',obj.fontsize);
end
end
% if any(strcmp('nonorm', p.UsingDefaults))
% obj.axesHandles(1,1).CLim = [0 1];
% end
else
plotW = (figWidth - 6*obj.hSpacing - 2*obj.cbw - cblbsz)/4;
plotH = sz(3)/sz(4)*plotW;
figHeight = plotH*4+5*obj.vSpacing + cblbextents(4);
plotPosFun = @(j,k) [ (obj.hSpacing+(k-1)*(plotW+obj.hSpacing))/figWidth,...
(obj.vSpacing+(4-j)*(plotH+obj.vSpacing))/figHeight,...
plotW/figWidth,...
plotH/figHeight];
set(obj.figHandle,'Position',[0,0,figWidth,figHeight],'units','pixels');
for j=1:4
for k=1:4
obj.axesHandles(j,k) = ...
subplot('position',plotPosFun(j,k),'units','pixels');
pos = get(obj.axesHandles(j,k),'Position');
imagesc(squeeze(obj.Data(j,k,:,:,dataIndex)),'Parent',obj.axesHandles(j,k),obj.gs)
colormap(obj.axesHandles(j,k),makeColormap(obj.gs,obj.uniquezero,obj.palette))
axis(obj.axesHandles(j,k),'off')
end
end
obj.colorbarHandles(1,4) = colorbar(obj.axesHandles(1,4),'units','pixels',...
'Position',[pos(1)+pos(3)+obj.hSpacing, cblbextents(4)/4+6,...
obj.cbw,figHeight-3*cblbextents(4)/2-12],...
'fontsize',obj.fontsize);
end
obj.xDataTextBox = ...
uicontrol('style', 'text', 'fontsize', obj.fontsize, 'units', 'pixels', ...
'position', [figWidth/2-cblbextents(3), figHeight-cblbextents(4), cblbextents(3:4)]);
set(obj.xDataTextBox, 'String', num2str(obj.xData(dataIndex)));
end
function mmdata = getPlotData(obj)
% h: [4,4] array of axis handles
mmdata = zeros([4, 4, size(obj.axesHandles(1,1).Children.CData)], ...
class(obj.axesHandles(1,1).Children.CData));
for j=1:4
for k=1:4
mmdata(j,k,:,:) = obj.axesHandles(j,k).Children.CData;
end
end
end
function replacePlotData(obj, idx)
% MMreplace3DplotData replaces the data in 4x4 intensity plots.
% h is a [4,4] array of axis handles
% Data is a 4x4xNxM array. Data size should not be different than data in
% plots.
if obj.gs == 0
for j=1:4
for k=1:4
obj.axesHandles(j,k).Children.CData = squeeze(obj.Data(j,k,:,:,idx));
clim = [min(min(obj.Data(j,k,:,:,idx))),max(max(obj.Data(j,k,:,:,idx)))];
if obj.limz ~= 0 % modify axes bounds if limz is set
if (clim(2) - clim(1)) < obj.limz
avg = (clim(2) + clim(1))./2;
clim(2) = avg + obj.limz/2;
clim(1) = avg - obj.limz/2;
end
end
obj.axesHandles(j,k).CLim = clim;
colormap(obj.axesHandles(j,k),makeColormap(clim,obj.uniquezero,obj.palette))
end
end
else
for j=1:4
for k=1:4
obj.axesHandles(j,k).Children.CData = squeeze(obj.Data(j,k,:,:,idx));
end
end
end
%
end
function makeAVI(obj, xRange, AVIfilename)
if isempty(obj.xData)
xVals = xRange;
else
[X,I] = sort(obj.xData); % added this to allow unsorted xData
indices = unique(round(fracIndex(X,xRange)),'first');
xVals = I(indices);
end
v = VideoWriter(AVIfilename);
v.FrameRate = 10;
open(v);
for i=xVals
replacePlotData(obj, i)
set(obj.xDataTextBox, 'String', num2str(obj.xData(i)));
writeVideo(v, getframe(obj.figHandle));
end
close(v);
end
function update(obj, varargin)
obj.figHandle.Visible = 'off';
data = getPlotData(obj);
delete(obj.axesHandles);
delete(obj.colorbarHandles)
obj.axesHandles = gobjects(4);
obj.colorbarHandles = gobjects(4);
plot(obj,data,varargin{:});
obj.figHandle.Visible = 'on';
end
end
end
function width = getFigWidth % sets default width to 60% of display width
scrsz = get(0,'screensize');
width = 0.6*scrsz(3)/get(0,'ScreenPixelsPerInch');
end
function colAr = colPalette(palette)
% these are custom color palettes. A palette is just a Nx4 matrix. The
% first column are values between 0 and 256 that position a color marker.
% The 2nd, 3rd, and 4th columns are RGB color values.
switch palette
case 'Rainbow'
colAr = ...
[0 255 0 241;...
36 0 65 220;...
86 0 253 253;...
128 0 255 15;...
171 255 242 0;...
234 255 127 0;...
256 255 0 0];
case 'HotCold Bright'
colAr = ...
[0 0 65 220;...
36 0 90 240;...
76 0 253 253;...
128 250 250 250;...
182 255 242 0;...
224 255 127 0;...
256 255 0 0];
case 'HotCold Dark'
colAr = ...
[0 0 253 253;...
36 1 114 239;...
76 0 90 240;...
128 0 0 0;...
182 255 0 0;...
224 255 127 0;...
256 255 242 0];
case 'TwoTone Bright'
colAr = ...
[0 0 0 255;...
128 255 255 255;...
256 255 0 0];
case 'TwoTone Dark'
colAr = ...
[0 0 0 255;...
128 0 0 0;...
256 255 0 0];
case 'Fireice'
clrs = [0.75 1 1; 0 1 1; 0 0 1;...
0 0 0; 1 0 0; 1 1 0; 1 1 0.75];
y = -3:3;
m = 64;
if mod(m,2)
delta = min(1,6/(m-1));
half = (m-1)/2;
yi = delta*(-half:half)';
else
delta = min(1,6/m);
half = m/2;
yi = delta*nonzeros(-half:half);
end
colAr = cat(2,(0:4:255).',255*interp2(1:3,y,clrs,1:3,yi));
end
end
function fracIndx = fracIndex(array,x)
fracIndx = zeros(1,length(x));
for idx = 1:length(x)
if x(idx) >= array(end)
fracIndx(idx) = length(array);
elseif x(idx) <= array(1)
fracIndx(idx) = 1;
else
a = find(array <= x(idx));
a = a(length(a));
b = find(array > x(idx));
b = b(1);
fracIndx(idx) = a+(x(idx)-array(a))/(array(b)-array(a));
end
end
end
function cm = makeColormap(clim,b_uniqueZero,palette)
dmin=clim(1);
dmax=clim(2);
if dmax == dmin
dmax=1;
dmin=0;
end
if b_uniqueZero == true
Zscale = zeros(1,256);
if abs(dmin) < abs(dmax)
didx = (dmax - dmin)/(2*dmax);
for idx = 0:255
Zscale(idx+1) = 256 - didx*idx;
end
else
didx = (dmin-dmax)/(2*dmin);
for idx = 0:255
Zscale(idx+1) = idx*didx;
end
Zscale = flip(Zscale);
end
else
Zscale = flip(1:256);
end
colAr = colPalette(palette);
cm = zeros(256,3);
for n = 1:256
x = fracIndex(colAr(:,1),Zscale(n));
cm(n,1) = interp1(colAr(:,2),x);
cm(n,2) = interp1(colAr(:,3),x);
cm(n,3) = interp1(colAr(:,4),x);
end
cm = cm./255;
cm = flip(cm,1);
end
|
github | shane-nichols/smn-thesis-master | MMgetp.m | .m | smn-thesis-master/misc_utilities/MMgetp.m | 8,872 | utf_8 | 65bcc2600efa3ab7e9f30ba08f232327 | function out = MMgetp(M,parameter)
% This function contains many parameters that one can compute from a
% Mueller matrix (M). In general, M is assumed to be an
% experimental one. Hence, a Mueller-Jones matrix or even a physical M is
% not assumed. For most parameters, M is first converted to its closest
% Mueller-Jones matrix, or its Nearest Jones matrix.
if ndims(M) > 3 % reshape array into 4,4,N
sz = size(M);
M = reshape(M,4,4,[]);
else
sz = 0;
end
switch lower(parameter)
case 'opt prop'
J = nearestJones(M);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
L=1i.*O.*( J(1,1,:) - J(2,2,:) );
Lp=1i.*O.*( J(1,2,:) + J(2,1,:) );
C=O.*( J(1,2,:) - J(2,1,:) );
LB=real(L);
LD=-imag(L);
LBp=real(Lp);
LDp=-imag(Lp);
CB=real(C);
CD=-imag(C);
A = -2*real(log(1./K)); % mean absorption
out = squeeze([LB;LD;LBp;LDp;CB;CD;A]);
case 'lm'
J = nearestJones(M);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2);
O = (T.*K)./(sin(T));
L=1i.*O.*( J(1,1,:) - J(2,2,:) );
Lp=1i.*O.*( J(1,2,:) + J(2,1,:) );
C=O.*( J(1,2,:) - J(2,1,:) );
LB=real(L);
LD=-imag(L);
LBp=real(Lp);
LDp=-imag(Lp);
CB=real(C);
CD=-imag(C);
A = 2*real(log(1./K)); % mean absorption
out = [A,-LD,-LDp,CD ; -LD,A,CB,LBp ; -LDp,-CB,A,-LB ; CD,-LBp,LB,A];
case 'logm' %log of Mueller matrix with filtering
Mfiltered = filterM(M);
out = zeros(size(M));
for n=1:size(M,3); out(:,:,n) = logm(Mfiltered(:,:,n)); end
case 'expm' %log of Mueller matrix with filtering
out = zeros(size(M));
for n=1:size(M,3); out(:,:,n) = expm(M(:,:,n)); end
case 'lb'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = real(1i.*O.*( J(1,1,:) - J(2,2,:) ));
case 'ld'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
case 'lbp'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = real(1i.*O.*( J(1,2,:) + J(2,1,:) ));
case 'ldp'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
case 'cb'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = real(O.*( J(1,2,:) - J(2,1,:) ));
case 'cd'
J = nearestJones(M);
O = jonesAnisotropy(J);
out = -imag(O.*( J(1,2,:) - J(2,1,:) ));
case 'a' % total mean extinction
J = nearestJones(M);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
out = -2*real(log(1./K));
case 'a_aniso' % anisotropic part of the mean extinction
J = nearestJones(M);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
CD = -imag(O.*( J(1,2,:) - J(2,1,:) ));
out = sqrt(LD.^2 + LDp.^2 + CD.^2); % not same as imag(2*T) !
case 'a_iso' % isotropic part of the mean extinction
J = nearestJones(M);
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2); % 2*T = sqrt(L.^2 + Lp.^2 + C.^2)
O = (T.*K)./(sin(T));
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
CD = -imag(O.*( J(1,2,:) - J(2,1,:) ));
out = -2*real(log(1./K)) - sqrt(LD.^2 + LDp.^2 + CD.^2);
case 'ldmag'
J = nearestJones(M);
O = jonesAnisotropy(J);
LD = imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
out = sqrt(LD.^2 + LDp.^2);
case 'ldang'
J = nearestJones(M);
O = jonesAnisotropy(J);
LD = -imag(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LDp = -imag(1i.*O.*( J(1,2,:) + J(2,1,:) ));
out = atan2(LDp , LD)./2;
%out = out + pi*(out < 0);
case 'lbang'
J = nearestJones(M);
O = jonesAnisotropy(J);
LB = real(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LBp = real(1i.*O.*( J(1,2,:) + J(2,1,:) ));
out = atan2(LBp , LB)./2;
out = out + pi*(out < 0);
case 'lbmag'
J = nearestJones(M);
O = jonesAnisotropy(J);
LB = real(1i.*O.*( J(1,1,:) - J(2,2,:) ));
LBp = real(1i.*O.*( J(1,2,:) + J(2,1,:) ));
out = sqrt(LB.^2 + LBp.^2);
case 'di' % Depolarization Index
out = (sqrt(squeeze(sum(sum(M.^2,1),2))./squeeze(M(1,1,:)).^2-1)./sqrt(3)).';
case 'jones' % Jones matrix of a Mueller-Jones matrix
out = MJ2J(M);
case 'nearestjones'
out = nearestJones(M); % Jones matrix
% next line just phases the Jones matrix so that the
% imaginary part of J(1,1) = 0. i.e., it matches case 'jones'
for n=1:size(out,3); out(:,:,n) = exp( -1i*angle(out(1,1,n)) ) * out(:,:,n); end
case 'covar' % Cloude carvariance matrix
out = M2Cov(M);
case 'covar2m' % Cloude carvariance matrix
out = Cov2M(M);
case 'mfiltered' % closest physical Mueller matrix
out = filterM(M);
end
if size(out,1) == 1 && size(out,2) == 1 %remove extra singletons
out = squeeze(out).';
end
if sz ~= 0 % reshape to match input dimensions
sz2 = size(out);
out = reshape(out,[sz2(1:(length(sz2)-1)),sz(3:length(sz))]);
end
end % end parent function
% \\ LOCAL FUNCTIONS \\
function J = MJ2J(M) % Mueller-Jones to Jones
J(1,1,:) = ((M(1,1,:)+M(1,2,:)+M(2,1,:)+M(2,2,:))/2).^(1/2);
k = 1./(2.*J(1,1,:));
J(1,2,:) = k.*(M(1,3,:)+M(2,3,:)-1i.*(M(1,4,:)+M(2,4,:)));
J(2,1,:) = k.*(M(3,1,:)+M(3,2,:)+1i.*(M(4,1,:)+M(4,2,:)));
J(2,2,:) = k.*(M(3,3,:)+M(4,4,:)+1i.*(M(4,3,:)-M(3,4,:)));
end
function C = M2Cov(M) % Mueller to Cloude covariance
C(1,1,:) = M(1,1,:) + M(1,2,:) + M(2,1,:) + M(2,2,:);
C(1,2,:) = M(1,3,:) + M(1,4,:)*1i + M(2,3,:) + M(2,4,:)*1i;
C(1,3,:) = M(3,1,:) + M(3,2,:) - M(4,1,:)*1i - M(4,2,:)*1i;
C(1,4,:) = M(3,3,:) + M(3,4,:)*1i - M(4,3,:)*1i + M(4,4,:);
C(2,1,:) = M(1,3,:) - M(1,4,:)*1i + M(2,3,:) - M(2,4,:)*1i;
C(2,2,:) = M(1,1,:) - M(1,2,:) + M(2,1,:) - M(2,2,:);
C(2,3,:) = M(3,3,:) - M(3,4,:)*1i - M(4,3,:)*1i - M(4,4,:);
C(2,4,:) = M(3,1,:) - M(3,2,:) - M(4,1,:)*1i + M(4,2,:)*1i;
C(3,1,:) = M(3,1,:) + M(3,2,:) + M(4,1,:)*1i + M(4,2,:)*1i;
C(3,2,:) = M(3,3,:) + M(3,4,:)*1i + M(4,3,:)*1i - M(4,4,:);
C(3,3,:) = M(1,1,:) + M(1,2,:) - M(2,1,:) - M(2,2,:);
C(3,4,:) = M(1,3,:) + M(1,4,:)*1i - M(2,3,:) - M(2,4,:)*1i;
C(4,1,:) = M(3,3,:) - M(3,4,:)*1i + M(4,3,:)*1i + M(4,4,:);
C(4,2,:) = M(3,1,:) - M(3,2,:) + M(4,1,:)*1i - M(4,2,:)*1i;
C(4,3,:) = M(1,3,:) - M(1,4,:)*1i - M(2,3,:) + M(2,4,:)*1i;
C(4,4,:) = M(1,1,:) - M(1,2,:) - M(2,1,:) + M(2,2,:);
C = C./2;
end
function M = Cov2M(C) % Cloude covariance to Mueller
M(1,1,:) = C(1,1,:) + C(2,2,:) + C(3,3,:) + C(4,4,:);
M(1,2,:) = C(1,1,:) - C(2,2,:) + C(3,3,:) - C(4,4,:);
M(1,3,:) = C(1,2,:) + C(2,1,:) + C(3,4,:) + C(4,3,:);
M(1,4,:) = ( -C(1,2,:) + C(2,1,:) - C(3,4,:) + C(4,3,:) )*1i;
M(2,1,:) = C(1,1,:) + C(2,2,:) - C(3,3,:) - C(4,4,:);
M(2,2,:) = C(1,1,:) - C(2,2,:) - C(3,3,:) + C(4,4,:);
M(2,3,:) = C(1,2,:) + C(2,1,:) - C(3,4,:) - C(4,3,:);
M(2,4,:) = ( -C(1,2,:) + C(2,1,:) + C(3,4,:) - C(4,3,:) )*1i;
M(3,1,:) = C(1,3,:) + C(2,4,:) + C(3,1,:) + C(4,2,:);
M(3,2,:) = C(1,3,:) - C(2,4,:) + C(3,1,:) - C(4,2,:);
M(3,3,:) = C(1,4,:) + C(2,3,:) + C(3,2,:) + C(4,1,:);
M(3,4,:) = ( -C(1,4,:) + C(2,3,:) - C(3,2,:) + C(4,1,:) )*1i;
M(4,1,:) = ( C(1,3,:) + C(2,4,:) - C(3,1,:) - C(4,2,:) )*1i;
M(4,2,:) = ( C(1,3,:) - C(2,4,:) - C(3,1,:) + C(4,2,:) )*1i;
M(4,3,:) = ( C(1,4,:) + C(2,3,:) - C(3,2,:) - C(4,1,:) )*1i;
M(4,4,:) = C(1,4,:) - C(2,3,:) - C(3,2,:) + C(4,1,:);
M = real(M)./2;
end
function J = nearestJones(M)
C = M2Cov(M);
J = zeros(2,2,size(C,3));
for n=1:size(C,3)
[V,D] = eig(C(:,:,n),'vector');
[~,mx] = max(D);
J(:,:,n) = sqrt(D(mx))*reshape(V(:,mx),2,2).';
end
end
function Mfiltered = filterM(M) % M to nearest physical M
C_raw = M2Cov(M);
C = zeros(size(C_raw));
for n=1:size(C_raw,3)
[V,D] = eig(C_raw(:,:,n),'vector');
list = find(D > 0.00001).';
idx = 0;
temp = zeros(4,4,length(list));
for j = list
idx = idx + 1;
temp(:,:,idx) = D(j)*V(:,j)*V(:,j)';
end
C(:,:,n) = sum(temp,3);
end
Mfiltered = Cov2M(C);
end
function O = jonesAnisotropy(J)
K = ( J(1,1,:).*J(2,2,:) - J(1,2,:).*J(2,1,:)).^(-1/2);
T = acos( K.*( J(1,1,:) + J(2,2,:) )./2);
O = (T.*K)./(sin(T));
end |
github | shane-nichols/smn-thesis-master | PEMphaseVoltCali.m | .m | smn-thesis-master/misc_utilities/4PEM/PEMphaseVoltCali.m | 1,767 | utf_8 | f8a6fe7fc71e93e6c0a55a006b32a851 | function [p_out,phase_out] = PEMphaseVoltCali(t,f,p)
% p_out = [m,b,s] array of fitting values.
% phase_out = phase of the PEM
% this function demostrates how to find a linear relation relating the
% PEM voltage to the amplitude of modulation.
volts = 0:0.01:2; % create an array of voltages to apply to the PEM
Amps = 0.045 + 2.1*volts; % convert volts to amps using a linear equation.
% the values b = 0.045 and m = 2.1 are what we are
% trying to find.
for i = 1:length(Amps)
I = 100*(1 + 0.95*sin( Amps(i)*sin(2*pi*t*f(1)+p(1)) )); % simulaiton of the waveform with scale factor
% c = 100;
C1 = sum(exp( 1i*2*pi*t*f(1)).*I)./length(t); % get amplitude of C_v1
C2 = sum(exp( 1i*2*pi*t*3*f(1)).*I)./length(t); % get amplitude of C_v2
[phase1(i),mag1(i)] = cart2pol(real(C1),imag(C1)); % convert to mag and phase
[phase2(i),mag2(i)] = cart2pol(real(C2),imag(C2)); % convert to mag and phase
end
% add pi to any phases less than zero, average over the phases, then subtract from
% pi/2.
phase_out = pi/2 - sum(phase1+pi*(phase1<0))./length(phase1)
figure
plot(volts,mag1,volts,mag2) % plot the magnitudes
p0 = [1,0,100]; % define initial parameters vector with slope of 1 and offset of 0
% and scale factor 100 that one can estimate by looking at the plotted data.
% perform non-linear least-square regression to determine parameters.
p_out = lsqcurvefit(@(param,volts)fitMags(param,volts),p0,volts,[mag1;mag2]);
end
function mags_out = fitMags(param,volts) % model function
Amps = volts*param(1)+param(2); % convert volts to amps
mags_out = param(3)*abs([besselj(1,Amps) ; besselj(3,Amps)]); %array to compare to data
end
|
github | Saswati18/projectile_motion_matlab-master | quadDiff.m | .m | projectile_motion_matlab-master/quadDiff.m | 111 | utf_8 | 237d26155a5fb105383e2b0461272448 | %% Equation of motion
function xdot = mo(t, x, u)
% xdotdot = a
xdot = [0 1; 0 0]*x + [0 ; 1]*u ;
end |
github | Saswati18/projectile_motion_matlab-master | mo.m | .m | projectile_motion_matlab-master/mo.m | 117 | utf_8 | 8378ff91202eb369f2cf3029b7a10bea | %% Equation of motion
function xdot = motion(t, x, u)
% xdotdot = a
xdot = [0 1; 0 0].*x + [0 ; 1].*u ;
end |
github | emsr/maths_burkhardt-master | bivnor.m | .m | maths_burkhardt-master/bivnor.m | 4,663 | utf_8 | aeeb07fb4759e7959064b8129dc6a95f | function value = bivnor ( ah, ak, r )
%*****************************************************************************80
%
%% BIVNOR computes the bivariate normal CDF.
%
% Discussion:
%
% BIVNOR computes the probability for two normal variates X and Y
% whose correlation is R, that AH <= X and AK <= Y.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 13 April 2012
%
% Author:
%
% Original FORTRAN77 version by Thomas Donnelly.
% MATLAB version by John Burkardt.
%
% Reference:
%
% Thomas Donnelly,
% Algorithm 462: Bivariate Normal Distribution,
% Communications of the ACM,
% October 1973, Volume 16, Number 10, page 638.
%
% Parameters:
%
% Input, real AH, AK, the lower limits of integration.
%
% Input, real R, the correlation between X and Y.
%
% Output, real VALUE, the bivariate normal CDF.
%
% Local Parameters:
%
% Local, integer IDIG, the number of significant digits
% to the right of the decimal point desired in the answer.
%
idig = 15;
b = 0.0;
gh = gauss ( - ah ) / 2.0;
gk = gauss ( - ak ) / 2.0;
if ( r == 0.0 )
b = 4.00 * gh * gk;
b = max ( b, 0.0 );
b = min ( b, 1.0 );
value = b;
return
end
rr = ( 1.0 + r ) * ( 1.0 - r );
if ( rr < 0.0 )
fprintf ( 1, '\n' );
fprintf ( 1, 'BIVNOR - Fatal error!\n' );
fprintf ( 1, ' 1 < |R|.\n' );
error ( 'BIVNOR - Fatal error!' );
end
if ( rr == 0.0 )
if ( r < 0.0 )
if ( ah + ak < 0.0 )
b = 2.0 * ( gh + gk ) - 1.0;
end
else
if ( ah - ak < 0.0 )
b = 2.0 * gk;
else
b = 2.0 * gh;
end
end
b = max ( b, 0.0 );
b = min ( b, 1.0 );
value = b;
return
end
sqr = sqrt ( rr );
if ( idig == 15 )
con = 2.0 * pi * 1.0E-15 / 2.0;
else
con = pi;
for i = 1 : idig
con = con / 10.0;
end
end
%
% (0,0)
%
if ( ah == 0.0 && ak == 0.0 )
b = 0.25 + 0.5 * asin ( r ) / pi;
b = max ( b, 0.0 );
b = min ( b, 1.0 );
value = b;
return
end
%
% (0,nonzero)
%
if ( ah == 0.0 && ak ~= 0.0 )
b = gk;
wh = -ak;
wk = ( ah / ak - r ) / sqr;
gw = 2.0 * gk;
is = 1;
%
% (nonzero,0)
%
elseif ( ah ~= 0.0 && ak == 0.0 )
b = gh;
wh = -ah;
wk = ( ak / ah - r ) / sqr;
gw = 2.0 * gh;
is = -1;
%
% (nonzero,nonzero)
%
elseif ( ah ~= 0.0 && ak ~= 0.0 )
b = gh + gk;
if ( ah * ak < 0.0 )
b = b - 0.5;
end
wh = - ah;
wk = ( ak / ah - r ) / sqr;
gw = 2.0 * gh;
is = -1;
end
while ( 1 )
sgn = -1.0;
t = 0.0;
if ( wk ~= 0.0 )
if ( abs ( wk ) == 1.0 )
t = wk * gw * ( 1.0 - gw ) / 2.0;
b = b + sgn * t;
else
if ( 1.0 < abs ( wk ) )
sgn = -sgn;
wh = wh * wk;
g2 = gauss ( wh );
wk = 1.0 / wk;
if ( wk < 0.0 )
b = b + 0.5;
end
b = b - ( gw + g2 ) / 2.0 + gw * g2;
end
h2 = wh * wh;
a2 = wk * wk;
h4 = h2 / 2.0;
ex = exp ( - h4 );
w2 = h4 * ex;
ap = 1.0;
s2 = ap - ex;
sp = ap;
s1 = 0.0;
sn = s1;
conex = abs ( con / wk );
while ( 1 )
cn = ap * s2 / ( sn + sp );
s1 = s1 + cn;
if ( abs ( cn ) <= conex )
break
end
sn = sp;
sp = sp + 1.0;
s2 = s2 - w2;
w2 = w2 * h4 / sp;
ap = - ap * a2;
end
t = 0.5 * ( atan ( wk ) - wk * s1 ) / pi;
b = b + sgn * t;
end
end
if ( 0 <= is )
break
end
if ( ak == 0.0 )
break
end
wh = -ak;
wk = ( ah / ak - r ) / sqr;
gw = 2.0 * gk;
is = 1;
end
b = max ( b, 0.0 );
b = min ( b, 1.0 );
value = b;
return
end
function value = gauss ( t )
%*****************************************************************************80
%
%% GAUSS is a univariate lower normal tail area.
%
% Licensing:
%
% This code is distributed under the GNU LGPL license.
%
% Modified:
%
% 13 April 2012
%
% Author:
%
% Original FORTRAN77 version by Thomas Donnelly.
% MATLAB version by John Burkardt.
%
% Reference:
%
% Thomas Donnelly,
% Algorithm 462: Bivariate Normal Distribution,
% Communications of the ACM,
% October 1973, Volume 16, Number 10, page 638.
%
% Parameters:
%
% Input, real T, the evaluation point.
%
% Output, real VALUE, the area of the lower tail of the normal PDF
% from -oo to T.
%
value = ( 1.0 + erf ( t / sqrt ( 2.0 ) ) ) / 2.0;
return
end
|
github | bsxfan/meta-embeddings-master | SGME_MXE.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_MXE.m | 2,114 | utf_8 | 829ff4b78c816bad28ac1dd5db3afbb8 | function [y,back] = SGME_MXE(A,B,D,As,Bs,labels,logPrior)
if nargin==0
test_this();
return;
end
dA = zeros(size(A));
dB = zeros(size(B));
dD = zeros(size(D));
dAs = zeros(size(As));
dBs = zeros(size(Bs));
[LEc,back1] = SGME_logexpectation(A,B,D);
[LEs,back2] = SGME_logexpectation(As,Bs,D);
dLEc = zeros(size(LEc));
dLEs = zeros(size(LEs));
m = length(LEs); % #speakers
n = length(LEc); % #recordings
scal = 1/(n*log(m+1));
logPost = zeros(m+1,1);
logPost(m+1) = logPrior(m+1);
y = 0;
for j=1:n
AA = bsxfun(@plus,As,A(:,j));
BB = bsxfun(@plus,Bs,B(:,j));
[LEboth,back3] = SGME_logexpectation(AA,BB,D);
logPost(1:m) = logPrior(1:m) + LEboth.' - LEs.' - LEc(j);
[yj,back4] = sumlogsoftmax(logPost,labels(j));
y = y - yj;
dlogPost = back4(-1);
dLEs = dLEs - dlogPost(1:m).';
dLEc(j) = dLEc(j) - sum(dlogPost(1:m));
dLEboth = dlogPost(1:m).';
[dAA,dBB,dDj] = back3(dLEboth);
dD = dD + dDj;
dAs = dAs + dAA;
dBs = dBs + dBB;
dA(:,j) = sum(dAA,2);
dB(:,j) = sum(dBB,2);
end
y = y*scal;
back = @(dy) back_this(dy,dA,dB,dD,dAs,dBs);
function [dA,dB,dD,dAs,dBs] = back_this(dy,dA,dB,dD,dAs,dBs)
%[LEc,back1] = SGME_logexpectation(A,B,D);
%[LEs,back2] = SGME_logexpectation(As,Bs,D).';
[dA1,dB1,dD1] = back1(dLEc);
[dAs2,dBs2,dD2] = back2(dLEs);
dA = (dy*scal) * (dA + dA1);
dB = (dy*scal) * (dB + dB1);
dD = (dy*scal) * (dD + dD1 + dD2);
dAs = (dy*scal) * (dAs + dAs2);
dBs = (dy*scal) * (dBs + dBs2);
end
end
function test_this()
m = 3;
n = 5;
dim = 2;
A = randn(dim,n);
As = randn(dim,m);
B = rand(1,n);
Bs = rand(1,m);
D = rand(dim,1);
logPrior = randn(m+1,1);
labels = randi(m,1,n);
f = @(A,B,D,As,Bs) SGME_MXE(A,B,D,As,Bs,labels,logPrior);
testBackprop(f,{A,B,D,As,Bs});
end
|
github | bsxfan/meta-embeddings-master | SGME_train.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_train.m | 2,349 | utf_8 | 875c864d98e47717be58a0d88a2550ab | function model = SGME_train(R,labels,nu,zdim,niters,test)
if nargin==0
test_this();
return;
end
[rdim,n] = size(R);
m = max(labels);
blocks = sparse(labels,1:n,true,m+1,n);
num = find(blocks(:));
%Can we choose maximum likelihood prior parameters, given labels?
%For now: prior expected number of speakers = m
prior = create_PYCRP([],0,m,n);
logPrior = prior.GibbsMatrix(labels);
delta = rdim - zdim;
assert(delta>0);
%initialize
P0 = randn(zdim,rdim);
H0 = randn(delta,rdim);
sqrtd0 = rand(zdim,1);
szP = numel(P0);
szH = numel(H0);
w0 = pack(P0,H0,sqrtd0);
if exist('test','var') && test
testBackprop(@objective,w0);
return;
end
mem = 20;
stpsz0 = 1e-3;
timeout = 5*60;
w = L_BFGS(@objective,w0,niters,timeout,mem,stpsz0);
[P,H,sqrtd] = unpack(w);
d = sqrtd.^2;
model.logexpectation = @(A,b) SGME_logexpectation(A,b,d);
model.extract = @(R) SGME_extract(P,H,nu,R);
model.objective = @(P,H,d) objective(pack(P,H,d));
model.d = d;
function w = pack(P,H,d)
w = [P(:);H(:);d(:)];
end
function [P,H,d] = unpack(w)
at = 1:szP;
P = reshape(w(at),zdim,rdim);
at = szP + (1:szH);
H = reshape(w(at),delta,rdim);
at = szP + szH + (1:zdim);
d = w(at);
end
function [y,back] = objective(w)
[P,H,sqrtd] = unpack(w);
[A,b,back1] = SGME_extract(P,H,nu,R);
d = sqrtd.^2;
[PsL,back2] = SGME_logPsL(A,b,d,blocks,labels,num,logPrior);
y = -PsL;
back = @back_this;
function [dw] = back_this(dy)
%dPsL = -dy;
[dA,db,dd] = back2(-dy);
dsqrtd = 2*sqrtd.*dd;
[dP,dH] = back1(dA,db);
dw = pack(dP,dH,dsqrtd);
end
end
end
function test_this()
zdim = 2;
rdim = 4;
n = 5;
m = 3;
prior = create_PYCRP([],0,m,n);
labels = prior.sample(n);
nu = pi;
R = randn(rdim,n);
test = true;
niters = [];
SGME_train(R,labels,nu,zdim,niters,test);
end
|
github | bsxfan/meta-embeddings-master | scaled_GME_precision.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/scaled_GME_precision.m | 2,566 | utf_8 | 59c037444c1e57e933d5346bc36263b6 | function [SGMEP,meand] = scaled_GME_precision(B)
if nargin==0
test_this();
return;
end
dim = size(B,1);
[V,D] = eig(B); % B = VDV'
d = diag(D);
meand = mean(d);
%D = sparse(D);
%I = speye(dim);
SGMEP.logdet = @logdet;
SGMEP.solve = @solve;
function [y,back] = logdet(beta)
betad = bsxfun(@times,beta,d);
y = sum(log1p(betad),1);
back = @(dy) dy*sum(d./(1+betad),1);
end
function [Y,back] = solve(RHS,beta)
betad = beta*d;
Y = V*bsxfun(@ldivide,betad+1,V.'*RHS);
back = @(dY) back_solve(dY,Y,beta);
end
function [dRHS,dbeta] = back_solve(dY,Y,beta)
dRHS = solve(dY,beta);
if nargout >= 2
%dA = (-dRHS)*Y.';
%dbeta = trace(dA*B.');
dbeta = -trace(Y.'*B.'*dRHS);
end
end
end
function [y,back] = logdettestfun(SGMEP,gamma)
beta = gamma^2;
[y,back1] = SGMEP.logdet(beta);
back =@(dy) 2*gamma*back1(dy);
end
function [Y,back] = solvetestfun(SGMEP,RHS,gamma)
beta = gamma^2;
[Y,back1] = SGMEP.solve(RHS,beta);
back =@(dY) back_solvetestfun(dY);
function [dRHS,dgamma] = back_solvetestfun(dY)
[dRHS,dbeta] = back1(dY);
dgamma = 2*gamma*dbeta;
end
end
function test_this()
close all;
fprintf('Test function values:\n');
dim = 5;
RHS = rand(dim,1);
%R = randn(dim,floor(1.1*dim));B = R*R.';B = B/trace(B);
R = randn(dim,dim);B = R*R.';B = B/trace(B);
I = eye(dim);
[SGMEP,meand] = scaled_GME_precision(B);
beta = rand/rand;
[log(det(I+beta*B)),SGMEP.logdet(beta)]
[(I+beta*B)\RHS,SGMEP.solve(RHS,beta)]
doplot = false;
if doplot
beta = 0.01:0.01:200;
y = zeros(size(beta));
for i=1:length(beta)
y(i) = SGMEP.logdet(beta(i));
end
1/meand
plot(log(1/meand+beta),y);
end
gamma = rand/rand;
fprintf('\n\n\nTest logdet backprop (complex step) :\n');
testBackprop(@(gamma) logdettestfun(SGMEP,gamma),gamma);
fprintf('\n\n\nTest logdet backprop (real step) :\n');
testBackprop_rs(@(gamma) logdettestfun(SGMEP,gamma),gamma,1e-4);
fprintf('\n\n\nTest solve backprop (complex step) :\n');
testBackprop(@(RHS,gamma) solvetestfun(SGMEP,RHS,gamma),{RHS,gamma},{1,1});
fprintf('\n\n\nTest solve backprop (real step) :\n');
testBackprop_rs(@(RHS,gamma) solvetestfun(SGMEP,RHS,gamma),{RHS,gamma},1e-4,{1,1});
end
|
github | bsxfan/meta-embeddings-master | dsolve.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/dsolve.m | 980 | utf_8 | 8734dea4d3f28af88579fef7b106d892 | function [Y,back] = dsolve(RHS,A)
% SOLVE: Y= A\RHS, with backpropagation into both arguments
%
% This is mostly for debugging purposes. It can be done more efficiently
% by caching a matrix factorization to re-use for derivative (and also for
% the determinant if needed).
if nargin==0
test_this();
return;
end
Y = A\RHS;
back = @back_this;
function [dRHS,dA] = back_this(dY)
dRHS = A.'\dY; % A\dY = dsolve(dY,A) can be re-used for symmetric A
if nargout>=2
dA = -dRHS*Y.';
end
end
end
% function [Y,back] = IbetaB(beta,B)
% dim = size(B,1);
% Y = speye(dim)+beta*B;
% back = @(dY) trace(dY*B.');
% end
function test_this()
m = 5;
n = 2;
A = randn(m,m);
RHS = randn(m,n);
testBackprop(@dsolve,{RHS,A});
testBackprop_rs(@dsolve,{RHS,A},1e-4);
% beta = rand/rand;
% testBackprop(@(beta) IbetaB(beta,A),{beta});
end |
github | bsxfan/meta-embeddings-master | labels2blocks.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/labels2blocks.m | 1,058 | utf_8 | 4c8472730d7214ee98dda298830f8849 | function [subsets,counts] = labels2blocks(labels)
% Inputs:
% labels: n-vector with elements in 1..m, maps each of n customers to a
% table number. There are m tables. Empty tables not allowed.
%
% Ouputs:
% subsets: n-by-m logical, with one-hot rows
% counts: m-vector, maps table number to customer count
if nargin==0
test_this();
return;
end
m = max(labels); %m tables
n = length(labels); %n customers
assert(min(labels)==1,'illegal argument ''labels'': tables must be consecutively numbered from 1');
assert(m <= n,'illegal argument ''labels'': there are more tables than customers');
subsets = bsxfun(@eq,1:m,labels(:));
%subsets = sparse(1:n,labels,true,n,m,n);
counts = sum(subsets,1);
assert(sum(counts)==n,'illegal argument ''labels'': table counts must add up to length(labels)');
assert(all(counts),'illegal argument ''labels'': empty tables not allowed');
end
function test_this()
labels = [2,3,3,3,4];
[subsets,counts] = labels2blocks(labels)
end |
github | bsxfan/meta-embeddings-master | create_BXE_calculator.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/create_BXE_calculator.m | 2,055 | utf_8 | 494fcd9ff939f75d131309b403080ae5 | function calc = create_BXE_calculator(log_expectations,prior,poi)
calc.BXE = @BXE;
calc.get_tar_non = @get_tar_non;
n = length(poi);
spoi = sparse(poi);
tar = bsxfun(@eq,spoi,spoi.');
ntar = 0;
nnon = 0;
for k=1:n-1
jj = k+1:n;
tari = full(tar(k,jj));
ntari = sum(tari);
ntar = ntar + ntari;
nnon = nnon + length(jj) - ntari;
end
if isempty(prior)
prior = ntar/(ntar+nnon);
end
plo = log(prior) - log1p(-prior);
function y = BXE(A,B)
LEc = log_expectations(A,B);
yt = 0;
yn = 0;
for i=1:n-1
jj = i+1:n;
AA = bsxfun(@plus,A(:,i),A(:,jj));
BB = bsxfun(@plus,B(:,i),B(:,jj));
tari = full(tar(i,jj));
LE2 = log_expectations(AA,BB);
llr = LE2 - LEc(i) - LEc(jj);
log_post = plo + llr;
yt = yt + sum(softplus(-log_post(tari)));
yn = yn + sum(softplus(log_post(~tari)));
end
y = prior*yt/ntar + (1-prior)*yn/(nnon);
end
function [tars,nons] = get_tar_non(A,B)
LEc = log_expectations(A,B);
tars = zeros(1,ntar);
nons = zeros(1,nnon);
tcount = 0;
ncount = 0;
for i=1:n-1
jj = i+1:n;
AA = bsxfun(@plus,A(:,i),A(:,jj));
BB = bsxfun(@plus,B(:,i),B(:,jj));
tari = full(tar(i,jj));
LE2 = log_expectations(AA,BB);
llr = LE2 - LEc(i) - LEc(jj);
llr_tar = llr(tari);
count = length(llr_tar);
tars(tcount+(1:count)) = llr_tar;
tcount = tcount + count;
llr_non = llr(~tari);
count = length(llr_non);
nons(ncount+(1:count)) = llr_non;
ncount = ncount + count;
end
end
end
function y = softplus(x)
% y = log(1+exp(x));
y = x;
f = find(x<30);
y(f) = log1p(exp(x(f)));
end |
github | bsxfan/meta-embeddings-master | PLDA_mixture_responsibilities.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/PLDA_mixture_responsibilities.m | 1,346 | utf_8 | 78dfbb4de92f575f08845cbc7e0010fb | function P = PLDA_mixture_responsibilities(w,F,W,R)
if nargin==0
P = test_this();
return
end
K = length(w);
if iscell(F)
[D,d] = size(F{1});
else
[D,d] = size(F);
end
N = size(R,2);
P = zeros(K,N);
Id = eye(d);
for k=1:K
if iscell(F)
Fk = F{k};
else
Fk = F;
end
Wk = W{k};
Bk = Fk.'*Wk*Fk;
Gk = Wk - Wk*Fk*((Id+Bk)\Fk.'*Wk);
RGR = sum(R.*(Gk*R),1);
logdetW = 2*sum(log(diag(chol(Wk))));
logdetIB = 2*sum(log(diag(chol(Id+Bk))));
P(k,:) = log(w(k)) + (logdetW - logdetIB - RGR)/2;
end
P = exp(bsxfun(@minus,P,max(P,[],1)));
P = bsxfun(@rdivide,P,sum(P,1));
end
function P = test_this()
close all;
d = 100;
D = 400;
N = 1000;
K = 5;
w = ones(1,K)/K;
W = cell(1,K);
W{1} = eye(D);
for k=2:K
W{k} = 2*W{k-1};
end
%F = randn(D,d);
F = cell(1,K);
for k=1:K
F{k} = randn(D,d);
end
Z = randn(d,N*K);
R = randn(D,N*K);
jj = 1:N;
for k=1:K
R(:,jj) = F{k}*Z(:,jj) + chol(W{k})\randn(D,N);
jj = jj + N;
end
P = PLDA_mixture_responsibilities(w,F,W,R);
plot(P');
end
|
github | bsxfan/meta-embeddings-master | create_partition_posterior_calculator.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/create_partition_posterior_calculator.m | 4,076 | utf_8 | 32fda68f00bdccc246e56e3db2e0babe | function calc = create_partition_posterior_calculator(log_expectations,prior,poi)
% Inputs:
% log_expectations: function handle, maps matrices of additive natural
% parameters to log-expectations
% prior: Exchangeable prior over partitions, for example CRP. It needs to
% implement prior.logprob(counts), where counts are the number of
% customers per table (partition block sizes).
% poi: partition of interest, given as an n-vector of table assignments,
% where there are n customers. The tables are numbered 1 to m.
if nargin==0
test_this();
return;
end
n = length(poi); %number of customers
%Generate flags for all possible (non-empty) subsets
ns = 2^n-1; %number of non-empty customer subsets
subsets = logical(mod(fix(bsxfun(@rdivide,0:ns,2.^(0:n-1)')),2));
subsets = subsets(:,2:end); % dump empty subset
%subsets = sparse(subsets);
%maps partition to flags indicating subsets (blocks)
% also returns table counts
function [flags,counts] = labels2weights(labels)
[blocks,counts] = labels2blocks(labels);
%blocks = sparse(blocks);
[tf,loc] = ismember(blocks',subsets','rows'); %seems faster with full matrices
assert(all(tf));
flags = false(ns,1);
flags(loc) = true;
end
[poi_weights,counts] = labels2weights(poi);
log_prior_poi = prior.logprob(counts);
%precompute weights and prior for every partition
Bn = Bell(n);
PI = create_partition_iterator(n);
Weights = false(ns,Bn);
log_prior = zeros(1,Bn);
for j=1:Bn
labels = PI.next();
[Weights(:,j),counts] = labels2weights(labels);
log_prior(j) = prior.logprob(counts);
end
Weights = sparse(Weights);
subsets = sparse(subsets);
poi_weights = sparse(poi_weights);
calc.logPost = @logPost;
calc.logPostPoi = @logPostPoi;
function y = logPostPoi(A,B)
% Inputs:
% A,B: n-column matrices of natural parameters for n meta-embeddings
% Output:
% y: log P(poi | A,B, prior)
assert(size(B,2)==n && size(A,2)==n);
%compute subset likelihoods
log_ex = log_expectations(A*subsets,B*subsets);
%compute posterior
num = log_prior_poi + log_ex*poi_weights;
dens = log_prior + log_ex*Weights;
maxden = max(dens);
den = maxden+log(sum(exp(dens-maxden)));
y = num - den;
end
function f = logPost(A,B)
% Inputs:
% A,B: n-column matrices of natural parameters for n meta-embeddings
% Output:
% y: log P(poi | A,B, prior)
assert(size(B,2)==n && size(A,2)==n);
%compute subset likelihoods
log_ex = log_expectations(A*subsets,B*subsets);
llh = log_ex*Weights;
den = log_prior + llh;
maxden = max(den);
den = maxden+log(sum(exp(den-maxden)));
function y = logpost_this(poi)
[poi_weights,counts] = labels2weights(poi);
log_prior_poi = prior.logprob(counts);
num = log_prior_poi + log_ex*poi_weights;
y = num - den;
end
f = @logpost_this;
end
end
function test_this
Mu = [-1 0 -1.1; 0 -3 0];
C = [3 1 3; 1 1 1];
A = Mu./C;
B = zeros(4,3);
B(1,:) = 1./C(1,:);
B(4,:) = 1./C(2,:);
scale = 3;
B = B * scale;
C = C / scale;
close all;
figure;hold;
plotGaussian(Mu(:,1),diag(C(:,1)),'blue','b');
plotGaussian(Mu(:,2),diag(C(:,2)),'red','r');
plotGaussian(Mu(:,3),diag(C(:,3)),'green','g');
axis('square');
axis('equal');
poi = [1 1 2];
%prior = create_PYCRP(0,[],2,3);
%prior = create_PYCRP([],0,2,3);
create_flat_partition_prior(length(poi));
calc = create_partition_posterior_calculator(prior,poi);
f = calc.logPost(A,B);
exp([f([1 1 2]), f([1 1 1]), f([1 2 3]), f([1 2 2]), f([1 2 1])])
end
|
github | bsxfan/meta-embeddings-master | SGME_train_BXE.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_train_BXE.m | 2,434 | utf_8 | 4fb4ed77b580dc09d69346bc07a2cd16 | function model = SGME_train_BXE(R,labels,nu,zdim,niters,timeout,test)
if nargin==0
test_this();
return;
end
[rdim,n] = size(R);
spoi = sparse(labels);
tar = bsxfun(@eq,spoi,spoi.');
ntar = 0;
nnon = 0;
for k=1:n-1
jj = k+1:n;
tari = full(tar(k,jj));
ntari = sum(tari);
ntar = ntar + ntari;
nnon = nnon + length(jj) - ntari;
end
prior = ntar/(ntar+nnon);
plo = log(prior) - log1p(-prior);
wt = prior/ntar;
wn = (1-prior)/nnon;
delta = rdim - zdim;
assert(delta>0);
%initialize
P0 = randn(zdim,rdim);
H0 = randn(delta,rdim);
sqrtd0 = rand(zdim,1);
szP = numel(P0);
szH = numel(H0);
w0 = pack(P0,H0,sqrtd0);
if exist('test','var') && test
testBackprop(@objective,w0);
return;
end
mem = 20;
stpsz0 = 1e-3;
%timeout = 5*60;
w = L_BFGS(@objective,w0,niters,timeout,mem,stpsz0);
[P,H,sqrtd] = unpack(w);
d = sqrtd.^2;
model.logexpectation = @(A,b) SGME_logexpectation(A,b,d);
model.extract = @(R) SGME_extract(P,H,nu,R);
model.d = d;
function w = pack(P,H,d)
w = [P(:);H(:);d(:)];
end
function [P,H,d] = unpack(w)
at = 1:szP;
P = reshape(w(at),zdim,rdim);
at = szP + (1:szH);
H = reshape(w(at),delta,rdim);
at = szP + szH + (1:zdim);
d = w(at);
end
function [y,back] = objective(w)
[P,H,sqrtd] = unpack(w);
[A,b,back1] = SGME_extract(P,H,nu,R);
d = sqrtd.^2;
[y,back2] = SGME_BXE(A,b,d,plo,wt,wn,tar);
back = @back_this;
function [dw] = back_this(dy)
[dA,db,dd] = back2(dy);
dsqrtd = 2*sqrtd.*dd;
[dP,dH] = back1(dA,db);
dw = pack(dP,dH,dsqrtd);
end
end
end
function test_this()
zdim = 2;
rdim = 4;
n = 10;
m = 3;
prior = create_PYCRP([],0,m,n);
while true
labels = prior.sample(n);
if max(labels) > 1
break;
end
end
nu = pi;
R = randn(rdim,n);
test = true;
niters = [];
timeout = [];
SGME_train_BXE(R,labels,nu,zdim,niters,timeout,test);
end
|
github | bsxfan/meta-embeddings-master | SGME_extract.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_extract.m | 1,065 | utf_8 | b9106e80e9a78235222680c566b510fd | function [A,b,back] = SGME_extract(P,H,nu,R)
if nargin==0
test_this();
return;
end
[zdim,rdim] = size(P);
nuprime = nu + rdim - zdim;
HR = H*R;
q = sum(HR.^2,1);
den = nu + q;
b = nuprime./den;
M = P*R;
A = bsxfun(@times,b,M);
back = @back_this;
function [dP,dH] = back_this(dA,db)
%A = bsxfun(@times,b,M);
db = db + sum(dA.*M,1);
dM = bsxfun(@times,b,dA);
%M = P*R;
dP = dM*R.';
%b = nuprime./den;
dden = -db.*b./den;
%den = nu + q;
dq = dden;
%q = sum(HR.^2,1);
dHR = bsxfun(@times,2*dq,HR);
%HR = H*R;
dH = dHR*R.';
end
end
function test_this()
zdim = 2;
rdim = 4;
n = 5;
P = randn(zdim,rdim);
H = randn(rdim-zdim,rdim);
nu = pi;
R = randn(rdim,n);
f = @(P,H) SGME_extract(P,H,nu,R);
testBackprop_multi(f,2,{P,H});
end
|
github | bsxfan/meta-embeddings-master | sumlogsumexp.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/sumlogsumexp.m | 455 | utf_8 | cccd5f3ae0b7894b95682910eba4a060 | function [y,back] = sumlogsumexp(X)
if nargin==0
test_this();
return;
end
mx = max(real(X),[],1);
yy = mx + log(sum(exp(bsxfun(@minus,X,mx)),1));
y = sum(yy,2);
back = @back_this;
function dX = back_this(dy)
dX = dy*exp(bsxfun(@minus,X,yy));
end
end
function test_this()
m = 3;
n = 5;
X = randn(m,n);
testBackprop(@(X)sumlogsumexp(X),X);
end
|
github | bsxfan/meta-embeddings-master | SGME_logexpectation.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_logexpectation.m | 1,796 | utf_8 | 46f79c08a985ae0a1833cad86fb74983 | function [y,back] = SGME_logexpectation(A,b,d)
% log expected values (w.r.t. standard normal) of diagonalized SGMEs
% Inputs:
% A: dim-by-n, natural parameters (precision *mean) for n SGMEs
% b: 1-by-n, precision scale factors for these SGMEs
% d: dim-by-1, common diagonal precision
%
% Note:
% bsxfun(@times,b,d) is dim-by-n precision diagonals for the n SGMEs
%
% Outputs:
% y: 1-by-n, log expectations
% back: backpropagation handle, [dA,db,dd] = back(dy)
if nargin==0
test_this();
return;
end
bd = bsxfun(@times,b,d);
logdets = sum(log1p(bd),1);
den = 1 + bd;
Aden = A./den;
Q = sum(A.*Aden,1); %Q = sum((A.^2)./den,1);
y = (Q-logdets)/2;
back = @back_this;
function [dA,db,dd] = back_this(dy)
dQ = dy/2;
%dlogdets = - dQ;
dAden = bsxfun(@times,dQ,A);
dA = bsxfun(@times,dQ,Aden);
dA2 = dAden./den;
dA = dA + dA2;
dden = -Aden.*dA2;
dbd = dden - bsxfun(@rdivide,dQ,den); %dlogdets = -dQ
db = d.' * dbd;
dd = dbd * b.';
end
end
function test_this0()
m = 3;
n = 5;
A = randn(m,n);
b = rand(1,n);
d = rand(m,1);
testBackprop(@SGME_logexpectation,{A,b,d},{1,1,1});
end
function test_this()
%em = 4;
n = 7;
dim = 2;
%prior = create_PYCRP([],0,em,n);
%poi = prior.sample(n);
%m = max(poi);
%blocks = sparse(poi,1:n,true,m+1,n);
%num = find(blocks(:));
%logPrior = prior.GibbsMatrix(poi);
d = rand(dim,1);
A = randn(dim,n);
b = rand(1,n);
f = @(A,b,d) SGME_logexpectation(A,b,d);
testBackprop(f,{A,b,d},{1,1,1});
end
|
github | bsxfan/meta-embeddings-master | SGME_train_MXE.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_train_MXE.m | 2,514 | utf_8 | 939eef34cb61a4493dfe9c98a11d633c | function model = SGME_train_MXE(R,labels,nu,zdim,niters,timeout,test)
if nargin==0
test_this();
return;
end
[rdim,n] = size(R);
m = max(labels);
blocks = sparse(labels,1:n,true,m,n);
counts = sum(blocks,2);
logPrior = [log(counts);-inf];
delta = rdim - zdim;
assert(delta>0);
%initialize
P0 = randn(zdim,rdim);
H0 = randn(delta,rdim);
sqrtd0 = rand(zdim,1);
As0 = randn(zdim,m);
sqrtBs0 = randn(1,m);
szP = numel(P0);
szH = numel(H0);
szd = numel(sqrtd0);
szAs = numel(As0);
szBs = numel(sqrtBs0);
w0 = pack(P0,H0,sqrtd0,As0,sqrtBs0);
if exist('test','var') && test
testBackprop(@objective,w0);
return;
end
mem = 20;
stpsz0 = 1e-3;
%timeout = 5*60;
w = L_BFGS(@objective,w0,niters,timeout,mem,stpsz0);
[P,H,sqrtd,As,sqrtBs] = unpack(w);
d = sqrtd.^2;
model.logexpectation = @(A,b) SGME_logexpectation(A,b,d);
model.extract = @(R) SGME_extract(P,H,nu,R);
model.d = d;
function w = pack(P,H,d,As,Bs)
w = [P(:);H(:);d(:);As(:);Bs(:)];
end
function [P,H,d,As,Bs] = unpack(w)
at = 1:szP;
P = reshape(w(at),zdim,rdim);
at = szP + (1:szH);
H = reshape(w(at),delta,rdim);
at = szP + szH + (1:szd);
d = w(at);
at = szP + szH + szd + (1:szAs);
As = reshape(w(at),zdim,m);
at = szP + szH + szd + szAs + (1:szBs);
Bs = w(at).';
end
function [y,back] = objective(w)
[P,H,sqrtd,As,sqrtBs] = unpack(w);
[A,b,back1] = SGME_extract(P,H,nu,R);
d = sqrtd.^2;
Bs = sqrtBs.^2;
[y,back2] = SGME_MXE(A,b,d,As,Bs,labels,logPrior);
back = @back_this;
function [dw] = back_this(dy)
[dA,db,dd,dAs,dBs] = back2(dy);
dsqrtd = 2*sqrtd.*dd;
dsqrtBs = 2*sqrtBs.*dBs;
[dP,dH] = back1(dA,db);
dw = pack(dP,dH,dsqrtd,dAs,dsqrtBs);
end
end
end
function test_this()
zdim = 2;
rdim = 4;
n = 5;
m = 3;
prior = create_PYCRP([],0,m,n);
labels = prior.sample(n);
nu = pi;
R = randn(rdim,n);
test = true;
niters = [];
timeout = [];
SGME_train_MXE(R,labels,nu,zdim,niters,timeout,test);
end
|
github | bsxfan/meta-embeddings-master | SGME_BXE.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_BXE.m | 1,927 | utf_8 | 43f8a07c46e1df00ef02abdfbbc38dde | function [y,back] = SGME_BXE(A,B,D,plo,wt,wn,tar)
if nargin==0
test_this();
return;
end
n = size(A,2);
[LEc,back1] = SGME_logexpectation(A,B,D);
y = 0;
dA = zeros(size(A));
dB = zeros(size(B));
dLEc = zeros(size(LEc));
dD = zeros(size(D));
for i=1:n-1
jj = i+1:n;
AA = bsxfun(@plus,A(:,i),A(:,jj));
BB = bsxfun(@plus,B(:,i),B(:,jj));
tari = full(tar(i,jj));
[LE2,back2] = SGME_logexpectation(AA,BB,D);
llr = LE2 - LEc(i) - LEc(jj);
arg_tar = -plo - llr(tari);
noni = ~tari;
arg_non = plo + llr(noni);
y = y + wt*sum(softplus(arg_tar));
y = y + wn*sum(softplus(arg_non));
dllr = zeros(size(llr));
dllr(tari) = (-wt)*sigmoid(arg_tar);
dllr(noni) = wn*sigmoid(arg_non);
dLE2 = dllr;
dLEc(i) = dLEc(i) - sum(dllr);
dLEc(jj) = dLEc(jj) - dllr;
[dAA,dBB,dD2] = back2(dLE2);
dD = dD + dD2;
dA(:,i) = dA(:,i) + sum(dAA,2);
dB(:,i) = dB(:,i) + sum(dBB,2);
dA(:,jj) = dA(:,jj) + dAA;
dB(:,jj) = dB(:,jj) + dBB;
end
back = @(dy) back_this(dy,dA,dB,dLEc,dD);
function [dA,dB,dD] = back_this(dy,dA,dB,dLEc,dD)
[dA1,dB1,dD1] = back1(dLEc);
dA = dy*(dA + dA1);
dB = dy*(dB + dB1);
dD = dy*(dD + dD1);
end
end
function y = sigmoid(x)
y = 1./(1+exp(-x));
end
function y = softplus(x)
% y = log(1+exp(x));
y = x;
f = find(x<30);
y(f) = log1p(exp(x(f)));
end
function test_this()
zdim = 2;
n = 5;
A = randn(zdim,n);
B = rand(1,n);
plo = randn;
wt = rand;
wn = rand;
tar = sparse(randn(n)>0);
D = rand(zdim,1);
f = @(A,B,D) SGME_BXE(A,B,D,plo,wt,wn,tar);
testBackprop(f,{A,B,D});
end
|
github | bsxfan/meta-embeddings-master | plotGaussian.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/plotGaussian.m | 1,323 | utf_8 | 16ea9cd804af31a79f3ccd3cf5687a49 | function tikz = plotGaussian(mu,C,colr,c)
if nargin==0
test_this();
return;
end
if isempty(C) %assume mu is a GME
[mu,C] = mu.get_mu_cov();
end
[V,D] = eig(C);
v1 = V(:,1);
v2 = V(:,2);
if all(v1>=0)
r1 = sqrt(D(1,1));
r2 = sqrt(D(2,2));
rotate = acos(v1(1))*180/pi;
elseif all(-v1>=0)
r1 = sqrt(D(1,1));
r2 = sqrt(D(2,2));
rotate = acos(-v1(1))*180/pi;
elseif all(v2>=0)
r1 = sqrt(D(2,2));
r2 = sqrt(D(1,1));
rotate = acos(v2(1))*180/pi;
else
r1 = sqrt(D(2,2));
r2 = sqrt(D(1,1));
rotate = acos(-v2(1))*180/pi;
end
if ~isempty(colr)
tikz = sprintf('\\draw[rotate around ={%4.3g:(%4.3g,%4.3g)},%s] (%4.3g,%4.3g) ellipse [x radius=%4.3g, y radius=%4.3g];\n',rotate,mu(1),mu(2),colr,mu(1),mu(2),r1,r2);
fprintf('%s',tikz);
end
theta = (0:100)*2*pi/100;
circle = [cos(theta);sin(theta)];
ellipse = bsxfun(@plus,mu,V*sqrt(D)*circle);
plot(ellipse(1,:),ellipse(2,:),c);
end
function test_this
close all;
%B = 2*eye(2) + ones(2);
B = 2*eye(2) + [1,-1;-1,1];
mu = [1;2];
figure;hold;
axis('equal');
axis('square');
plotGaussian(mu,B,'blue','b')
end |
github | bsxfan/meta-embeddings-master | create_HTPLDA_extractor.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/create_HTPLDA_extractor.m | 5,955 | utf_8 | 1304b09dbdcd66e16a53851e8e270761 | function HTPLDA = create_HTPLDA_extractor(F,nu,W)
if nargin==0
test_PsL();
%test_this();
return;
end
[rdim,zdim] = size(F);
assert(rdim>zdim);
nu_prime = nu + rdim - zdim;
if ~exist('W','var') || isempty(W)
W = speye(rdim);
end
E = F.'*W*F;
G = W - W*F*(E\F.')*W;
SGME = create_SGME_calculator(E);
V = SGME.V; % E = VDV'
VFW = V.'*F.'*W;
HTPLDA.extractSGMEs = @extractSGMEs;
HTPLDA.SGME = SGME;
HTPLDA.plot_database = @plot_database;
HTPLDA.getPHd = @getPHd;
function [P,H,d] = getPHd()
P = VFW;
H = G;
%HH = H'*H;
d = SGME.d;
end
function [A,b] = extractSGMEs(R)
q = sum(R.*(G*R),1);
b = nu_prime./(nu+q);
A = bsxfun(@times,b,VFW*R);
end
matlab_colours = {'r','g','b','m','c','k',':r',':g',':b',':m',':c',':k'};
tikz_colours = {'red','green','blue','magenta','cyan','black','red, dotted','green, dotted','blue, dotted','magenta, dotted','cyan, dotted','black, dotted'};
function plot_database(R,labels,Z)
assert(max(labels) <= length(matlab_colours),'not enough colours to plot all speakers');
[A,b] = extractSGMEs(R);
%SGME.plotAll(A,b,matlab_colours(labels), tikz_colours(labels));
SGME.plotAll(A,b,matlab_colours(labels), []);
if exist('Z','var') && ~isempty(Z)
for i=1:size(Z,2)
plot(Z(1,i),Z(2,i),[matlab_colours{i},'*']);
end
end
end
end
function test_this()
zdim = 2;
xdim = 20; %required: xdim > zdim
nu = 3; %required: nu >= 1, integer, DF
fscal = 3; %increase fscal to move speakers apart
F = randn(xdim,zdim)*fscal;
HTPLDA = create_HTPLDA_extractor(F,nu);
SGME = HTPLDA.SGME;
%labels = [1,2,2];
%[R,Z,precisions] = sample_HTPLDA_database(nu,F,labels);
n = 8;
m = 5;
%prior = create_PYCRP(0,[],m,n);
prior = create_PYCRP([],0,m,n);
[R,Z,precisions,labels] = sample_HTPLDA_database(nu,F,prior,n);
fprintf('there are %i speakers\n',max(labels));
[A,b] = HTPLDA.extractSGMEs(R);
rotate = true;
[Ap,Bp] = SGME.SGME2GME(A,b,rotate);
close all;
figure;hold;
plotGaussian(zeros(zdim,1),eye(zdim),'black, dashed','k--');
%matlab_colours = {'b','r','r'};
%tikz_colours = {'blue','red','red'};
%SGME.plotAll(A,b,matlab_colours, tikz_colours, rotate);
HTPLDA.plot_database(R,labels,Z);
axis('square');axis('equal');
calc1 = create_partition_posterior_calculator(SGME.log_expectations,prior,labels);
calc2 = create_pseudolikelihood_calculator(SGME.log_expectations,prior,labels);
calc3 = create_BXE_calculator(SGME.log_expectations,[],labels);
scale = exp(-5:0.1:5);
MCL = zeros(size(scale));
PsL = zeros(size(scale));
slowPsL = zeros(size(scale));
BXE = zeros(size(scale));
tic;
for i=1:length(scale)
MCL(i) = - calc1.logPostPoi(scale(i)*A,scale(i)*b);
end
toc
tic;
for i=1:length(scale)
BXE(i) = calc3.BXE(scale(i)*A,scale(i)*b);
end
toc
tic;
for i=1:length(scale)
slowPsL(i) = - calc2.slow_log_pseudo_likelihood(scale(i)*A,scale(i)*b);
end
toc
tic;
for i=1:length(scale)
PsL(i) = - calc2.log_pseudo_likelihood(scale(i)*A,scale(i)*b);
end
toc
figure;
%subplot(2,1,1);semilogx(scale,MCL);title('MCL')
%subplot(2,1,2);semilogx(scale,PsL);title('PsL');
subplot(2,1,1);semilogx(scale,MCL,scale,slowPsL,scale,PsL,'--');legend('MCL','slowPsL','PsL');
subplot(2,1,2);semilogx(scale,BXE);legend('BXE');
%[precisions;b]
%[plain_GME_log_expectations(Ap,Bp);SGME.log_expectations(A,b)]
end
function test_PsL()
zdim = 2;
xdim = 20; %required: xdim > zdim
nu = 3; %required: nu >= 1, integer, DF
fscal = 3; %increase fscal to move speakers apart
F = randn(xdim,zdim)*fscal;
HTPLDA = create_HTPLDA_extractor(F,nu);
SGME = HTPLDA.SGME;
n = 1000;
m = 100;
%prior = create_PYCRP(0,[],m,n);
prior = create_PYCRP([],0,m,n);
[R,Z,precisions,labels] = sample_HTPLDA_database(nu,F,prior,n);
fprintf('there are %i speakers\n',max(labels));
[A,b] = HTPLDA.extractSGMEs(R);
rotate = true;
[Ap,Bp] = SGME.SGME2GME(A,b,rotate);
close all;
if zdim==2 && max(labels)<=12
figure;hold;
plotGaussian(zeros(zdim,1),eye(zdim),'black, dashed','k--');
HTPLDA.plot_database(R,labels,Z);
axis('square');axis('equal');
end
tic;calc0 = create_pseudolikelihood_calculator_old(SGME.log_expectations,prior,labels);toc
tic;calc1 = create_pseudolikelihood_calculator(SGME.log_expectations,prior,labels);toc;
tic;calc2 = create_BXE_calculator(SGME.log_expectations,[],labels);toc
scale = exp(-5:0.1:5);
oldPsL = zeros(size(scale));
PsL = zeros(size(scale));
BXE = zeros(size(scale));
% tic;
% for i=1:length(scale)
% slowPsL(i) = - calc1.slow_log_pseudo_likelihood(scale(i)*A,scale(i)*b);
% end
% toc
tic;
for i=1:length(scale)
oldPsL(i) = - calc0.log_pseudo_likelihood(scale(i)*A,scale(i)*b);
end
toc
tic;
for i=1:length(scale)
PsL(i) = - calc1.log_pseudo_likelihood(scale(i)*A,scale(i)*b);
end
toc
% tic;
% for i=1:length(scale)
% BXE(i) = calc2.BXE(scale(i)*A,scale(i)*b);
% end
% toc
figure;
subplot(2,1,1);semilogx(scale,oldPsL,scale,PsL,'r--');legend('oldPsL','PsL');
subplot(2,1,2);semilogx(scale,BXE);title('BXE');
%[precisions;b]
%[plain_GME_log_expectations(Ap,Bp);SGME.log_expectations(A,b)]
end
|
github | bsxfan/meta-embeddings-master | SGME_MXE2.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_MXE2.m | 1,787 | utf_8 | 353320c477be13a9cd785ec811fdd210 | function [y,back] = SGME_MXE2(A,B,D,As,Bs,labels,logPrior)
if nargin==0
test_this();
return;
end
dA = zeros(size(A));
dB = zeros(size(B));
dD = zeros(size(D));
dAs = zeros(size(As));
dBs = zeros(size(Bs));
[LEs,back2] = SGME_logexpectation(As,Bs,D);
dLEs = zeros(size(LEs));
m = length(LEs); % #speakers
n = size(A,2); % #recordings
scal = 1/(n*log(m));
y = 0;
for j=1:n
AA = bsxfun(@plus,As,A(:,j));
BB = bsxfun(@plus,Bs,B(:,j));
[LEboth,back3] = SGME_logexpectation(AA,BB,D);
logPost = logPrior + LEboth.' - LEs.';
[yj,back4] = sumlogsoftmax(logPost,labels(j));
y = y - yj;
dlogPost = back4(-1);
dLEs = dLEs - dlogPost.';
dLEboth = dlogPost.';
[dAA,dBB,dDj] = back3(dLEboth);
dD = dD + dDj;
dAs = dAs + dAA;
dBs = dBs + dBB;
dA(:,j) = sum(dAA,2);
dB(:,j) = sum(dBB,2);
end
y = y*scal;
back = @(dy) back_this(dy,dA,dB,dD,dAs,dBs);
function [dA,dB,dD,dAs,dBs] = back_this(dy,dA,dB,dD,dAs,dBs)
%[LEs,back2] = SGME_logexpectation(As,Bs,D).';
[dAs2,dBs2,dD2] = back2(dLEs);
dA = (dy*scal) * dA;
dB = (dy*scal) * dB;
dD = (dy*scal) * (dD + dD2);
dAs = (dy*scal) * (dAs + dAs2);
dBs = (dy*scal) * (dBs + dBs2);
end
end
function test_this()
m = 3;
n = 5;
dim = 2;
A = randn(dim,n);
As = randn(dim,m);
B = rand(1,n);
Bs = rand(1,m);
D = rand(dim,1);
logPrior = randn(m,1);
labels = randi(m,1,n);
f = @(A,B,D,As,Bs) SGME_MXE2(A,B,D,As,Bs,labels,logPrior);
testBackprop(f,{A,B,D,As,Bs});
end
|
github | bsxfan/meta-embeddings-master | SGME_train_MXE2.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_train_MXE2.m | 2,510 | utf_8 | b71a75273c325f1e45edf8af7e971f30 | function model = SGME_train_MXE2(R,labels,nu,zdim,niters,timeout,test)
if nargin==0
test_this();
return;
end
[rdim,n] = size(R);
m = max(labels);
blocks = sparse(labels,1:n,true,m,n);
counts = sum(blocks,2);
logPrior = log(counts);
delta = rdim - zdim;
assert(delta>0);
%initialize
P0 = randn(zdim,rdim);
H0 = randn(delta,rdim);
sqrtd0 = rand(zdim,1);
As0 = randn(zdim,m);
sqrtBs0 = randn(1,m);
szP = numel(P0);
szH = numel(H0);
szd = numel(sqrtd0);
szAs = numel(As0);
szBs = numel(sqrtBs0);
w0 = pack(P0,H0,sqrtd0,As0,sqrtBs0);
if exist('test','var') && test
testBackprop(@objective,w0);
return;
end
mem = 20;
stpsz0 = 1e-3;
%timeout = 5*60;
w = L_BFGS(@objective,w0,niters,timeout,mem,stpsz0);
[P,H,sqrtd,As,sqrtBs] = unpack(w);
d = sqrtd.^2;
model.logexpectation = @(A,b) SGME_logexpectation(A,b,d);
model.extract = @(R) SGME_extract(P,H,nu,R);
model.d = d;
function w = pack(P,H,d,As,Bs)
w = [P(:);H(:);d(:);As(:);Bs(:)];
end
function [P,H,d,As,Bs] = unpack(w)
at = 1:szP;
P = reshape(w(at),zdim,rdim);
at = szP + (1:szH);
H = reshape(w(at),delta,rdim);
at = szP + szH + (1:szd);
d = w(at);
at = szP + szH + szd + (1:szAs);
As = reshape(w(at),zdim,m);
at = szP + szH + szd + szAs + (1:szBs);
Bs = w(at).';
end
function [y,back] = objective(w)
[P,H,sqrtd,As,sqrtBs] = unpack(w);
[A,b,back1] = SGME_extract(P,H,nu,R);
d = sqrtd.^2;
Bs = sqrtBs.^2;
[y,back2] = SGME_MXE2(A,b,d,As,Bs,labels,logPrior);
back = @back_this;
function [dw] = back_this(dy)
[dA,db,dd,dAs,dBs] = back2(dy);
dsqrtd = 2*sqrtd.*dd;
dsqrtBs = 2*sqrtBs.*dBs;
[dP,dH] = back1(dA,db);
dw = pack(dP,dH,dsqrtd,dAs,dsqrtBs);
end
end
end
function test_this()
zdim = 2;
rdim = 4;
n = 5;
m = 3;
prior = create_PYCRP([],0,m,n);
labels = prior.sample(n);
nu = pi;
R = randn(rdim,n);
test = true;
niters = [];
timeout = [];
SGME_train_MXE2(R,labels,nu,zdim,niters,timeout,test);
end
|
github | bsxfan/meta-embeddings-master | asChol.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/asChol.m | 2,365 | utf_8 | ea86b12ae1d2edfe698ac2881861b35f | function CA = asChol(A)
if nargin==0
test_this();
return;
end
if isreal(A)
C = chol(A); %C'C = A
r = true;
else
[L,U] = lu(A); % LU = A
r = false;
end
dim = size(A,1);
CA.logdet = @logdet;
CA.solve = @solve;
function [y,back] = logdet()
if r
y = 2*sum(log(diag(C)));
else
y = sum(log(diag(U).^2))/2;
end
back = @(dy) solve(dy*speye(dim));
end
function [Y,back] = solve(RHS)
if r
Y = C\(C'\RHS);
else
Y = U\(L\RHS);
end
back = @(dY) back_solve(dY,Y);
end
function Y = solveT(RHS) %A'\RHS, for LU case
Y = L.'\(U.'\RHS);
end
function [dRHS,dA] = back_solve(dY,Y)
if r
dRHS = solve(dY);
if nargout >= 2
dA = (-dRHS)*Y.';
end
else
dRHS = solveT(dY);
if nargout >= 2
dA = (-dRHS)*Y.';
end
end
end
end
function [y,back] = logdettestfun(A)
CA = asChol(A*A.');
[y,back1] = CA.logdet();
sym = @(DY) DY + DY.';
back =@(dy) sym(back1(dy))*A;
end
function [Y,back] = solvetestfun(RHS,A)
CA = asChol(A*A.');
[Y,back1] = CA.solve(RHS);
back =@(dY) back_solvetestfun(dY);
function [dRHS,dA] = back_solvetestfun(dY)
[dRHS,dAA] = back1(dY);
dA = (dAA+dAA.')*A;
end
end
function test_this()
fprintf('Test function values:\n');
dim = 5;
RHS = rand(dim,1);
A = randn(dim);A = A*A';
CA = asChol(A);
[log(det(A)),CA.logdet()]
[A\RHS,CA.solve(RHS)]
A = complex(randn(dim),zeros(dim));
CA = asChol(A);
[log(abs(det(A))),CA.logdet()]
[A\RHS,CA.solve(RHS)]
A = randn(dim,2*dim);A = A*A';
fprintf('\n\n\nTest logdet backprop (complex step) :\n');
testBackprop(@logdettestfun,A);
fprintf('\n\n\nTest logdet backprop (real step) :\n');
testBackprop_rs(@logdettestfun,A,1e-4);
fprintf('\n\n\nTest solve backprop (complex step) :\n');
testBackprop(@solvetestfun,{RHS,A},{1,1});
fprintf('\n\n\nTest solve backprop (real step) :\n');
testBackprop_rs(@solvetestfun,{RHS,A},1e-4,{1,1});
end
|
github | bsxfan/meta-embeddings-master | SGME_logPsL.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/SGME_logPsL.m | 3,902 | utf_8 | 2459f9858e466eb1e4b939681dce8f05 | function [y,back] = SGME_logPsL(A,B,d,blocks,poi,num,logPrior)
if nargin==0
test_this();
return;
end
if isempty(blocks)
m = max(poi);
n = length(poi);
blocks = sparse(poi,1:n,true,m+1,n);
num = find(blocks(:));
else
m = size(blocks,1) - 1;
end
if isstruct(logPrior) % then it is prior
prior = logPrior;
logPrior = prior.GibbsMatrix(poi);
end
At = A*blocks.';
Bt = B*blocks.';
[LEt,back1] = SGME_logexpectation(At,Bt,d);
[LEc,back2] = SGME_logexpectation(A,B,d);
Amin = At(:,poi) - A;
Bmin = Bt(:,poi) - B;
[LEmin,back3] = SGME_logexpectation(Amin,Bmin,d);
LLR = zeros(size(blocks));
for i=1:m
tar = full(blocks(i,:));
LLR(i,tar) = LEt(i) - LEmin(tar) - LEc(tar);
non = ~tar;
Aplus = bsxfun(@plus,A(:,non),At(:,i));
Bplus = bsxfun(@plus,B(:,non),Bt(:,i));
LLR(i,non) = SGME_logexpectation(Aplus,Bplus,d) - LEt(i) - LEc(non);
end
%y = LLR;
[y,back5] = sumlogsoftmax(LLR + logPrior,num);
back = @back_this;
function [dA,dB,dd] = back_this(dy)
dA = zeros(size(A));
dB = zeros(size(B));
dd = zeros(size(d));
dLEt = zeros(size(LEt));
dLEmin = zeros(size(LEmin));
dLEc = zeros(size(LEmin));
dAt = zeros(size(At));
dBt = zeros(size(Bt));
%[y,back5] = sumlogsoftmax(LLR + logPrior,num);
dLLR = back5(dy);
for k=1:m
tar = full(blocks(k,:));
%LLR(k,tar) = LEt(k) - LEmin(tar) - LEc(tar);
row = dLLR(k,tar);
dLEt(k) = dLEt(k) + sum(row);
dLEmin(tar) = dLEmin(tar) - row;
dLEc(tar) = dLEc(tar) - row;
non = ~tar;
Aplus = bsxfun(@plus,A(:,non),At(:,k));
Bplus = bsxfun(@plus,B(:,non),Bt(:,k));
%LLR(k,non) = SGME_logexpectation(Aplus,Bplus,d) - LEt(k) - LEc(non);
[~,back4] = SGME_logexpectation(Aplus,Bplus,d);
row = dLLR(k,non);
[dAplus,dBplus,dd4] = back4(row);
dLEt(k) = dLEt(k) - sum(row);
dLEc(non) = dLEc(non) - row;
dd = dd + dd4;
dA(:,non) = dA(:,non) + dAplus;
dB(:,non) = dB(:,non) + dBplus;
dAt(:,k) = dAt(:,k) + sum(dAplus,2);
dBt(:,k) = dBt(:,k) + sum(dBplus,2);
end
%[LEmin,back3] = SGME_logexpectation(Amin,Bmin,d);
[dAmin,dBmin,dd3] = back3(dLEmin);
dd = dd + dd3;
%Amin = At(:,poi) - A;
%Bmin = Bt(:,poi) - B;
dA = dA - dAmin;
dB = dB - dBmin;
dAt = dAt + dAmin*blocks.';
dBt = dBt + dBmin*blocks.';
%[LEc,back2] = SGME_logexpectation(A,B,d);
[dA2,dB2,dd2] = back2(dLEc);
dA = dA + dA2;
dB = dB + dB2;
dd = dd + dd2;
%[LEt,back1] = SGME_logexpectation(At,Bt,d);
[dAt1,dBt1,dd1] = back1(dLEt);
dAt = dAt + dAt1;
dBt = dBt + dBt1;
dd = dd + dd1;
%At = A*blocks.';
%Bt = B*blocks.';
dA = dA + dAt*blocks;
dB = dB + dBt*blocks;
end
end
function test_this()
em = 4;
n = 7;
dim = 2;
prior = create_PYCRP([],0,em,n);
poi = prior.sample(n);
m = max(poi);
blocks = sparse(poi,1:n,true,m+1,n);
num = find(blocks(:));
logPrior = prior.GibbsMatrix(poi);
d = rand(dim,1);
A = randn(dim,n);
b = rand(1,n);
%f = @(A,b,d) SGME_logexpectation(A,b,d);
%testBackprop(f,{A,b,d},{1,1,1});
g = @(A,b,d) SGME_logPsL(A,b,d,blocks,poi,num,logPrior);
testBackprop(g,{A,b,d},{1,1,1});
end
|
github | bsxfan/meta-embeddings-master | sumlogsoftmax.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/sumlogsoftmax.m | 517 | utf_8 | 5591b4f9a440f97900ac26aefd1faf62 | function [y,back] = sumlogsoftmax(X,num)
if nargin==0
test_this();
return;
end
[den,back1] = sumlogsumexp(X);
y = sum(X(num)) - den;
back = @back_this;
function dX = back_this(dy)
dX = back1(-dy);
dX(num) = dX(num) + dy;
end
end
function test_this()
m = 3;
n = 5;
X = randn(m,n);
labels = randi(m,1,n);
num = sub2ind(size(X),labels,1:n);
testBackprop(@(X)sumlogsoftmax(X,num),X);
end
|
github | bsxfan/meta-embeddings-master | create_SGME_calculator.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/create_SGME_calculator.m | 3,098 | utf_8 | 22c43d447699e600cb1e2c8a1f4c4a2d | function [SGME,LEfun] = create_SGME_calculator(E)
if nargin==0
test_this();
return;
end
[V,D] = eig(E); % E = VDV'
d = diag(D); % eigenvalues
dd = zeros(size(d)); %gradient w.r.t. d backpropagated from log_expectations
zdim = length(d);
ii = reshape(logical(eye(zdim)),[],1);
SGME.SGME2GME = @SGME2GME;
SGME.log_expectations = @log_expectations;
SGME.logLR = @logLR;
SGME.plotAll = @plotAll;
SGME.V = V;
SGME.d = d;
LEfun = @LE;
SGME.reset_parameter_gradient = @reset_parameter_gradient;
SGME.get_parameter_gradient = @get_parameter_gradient;
function reset_parameter_gradient()
dd(:) = 0;
end
function dd1 = get_parameter_gradient()
dd1 = dd;
end
function plotAll(A,b,matlab_colours, tikz_colours, rotate)
if ~exist('rotate','var') || isempty(rotate)
rotate = true;
end
if ~exist('tikz_colours','var')
tikz_colours = [];
end
[A,B] = SGME2GME(A,b,rotate);
n = length(b);
for i=1:n
Bi = reshape(B(:,i),zdim,zdim);
mu = Bi\A(:,i);
if ~isempty(tikz_colours)
plotGaussian(mu,inv(Bi),tikz_colours{i},matlab_colours{i});
else
plotGaussian(mu,inv(Bi),[],matlab_colours{i});
end
end
end
function [A,B] = SGME2GME(A,b,rotate)
B = zeros(zdim*zdim,length(b));
B(ii,:) = bsxfun(@times,b,d);
if ~exist('rotate','var') || isempty(rotate) || rotate %rotate by default
A = V*A;
for j = 1:size(B,2)
BR = V*reshape(B(:,j),zdim,zdim)*V.';
B(:,j) = BR(:);
end
end
end
function [y,back] = log_expectations(A,b)
[y,back0] = LE(A,b,d);
back = @back_this;
function [dA,db] = back_this(dy)
[dA,db,dd0] = back0(dy);
dd = dd + dd0;
end
end
function Y = logLR(left,right)
B = bsxfun(@plus,left.b.',right.b);
[m,n] = size(B);
Y = zeros(m,n);
for i=1:m
AA = bsxfun(@plus,left.A(:,i),right.A);
Y(i,:) = log_expectations(AA,B(i,:));
end
end
end
function [y,back] = LE(A,b,d)
bd = bsxfun(@times,b,d);
logdets = sum(log1p(bd),1);
den = 1 + bd;
Aden = A./den;
Q = sum(A.*Aden,1); %Q = sum((A.^2)./den,1);
y = (Q-logdets)/2;
back = @back_LE;
function [dA,db,dd] = back_LE(dy)
dQ = dy/2;
%dlogdets = - dQ;
dAden = bsxfun(@times,dQ,A);
dA = bsxfun(@times,dQ,Aden);
dA2 = dAden./den;
dA = dA + dA2;
dden = -Aden.*dA2;
dbd = dden - bsxfun(@rdivide,dQ,den); %dlogdets = -dQ
db = d.' * dbd;
dd = dbd * b.';
end
end
function test_this()
m = 3;
n = 5;
A = randn(m,n);
b = rand(1,n);
d = rand(m,1);
testBackprop(@LE,{A,b,d},{1,1,1});
end
|
github | bsxfan/meta-embeddings-master | logsumexp.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/logsumexp.m | 456 | utf_8 | ba0f6dd080d4fa7a7cd270a5055c5980 | function [y,back] = logsumexp(X)
if nargin==0
test_this();
return;
end
mx = max(X,[],1);
y = bsxfun(@plus,log(sum(exp(bsxfun(@minus,X,mx)),1)),mx);
back = @back_this;
function dX = back_this(dy)
dX = bsxfun(@times,dy,exp(bsxfun(@minus,X,y)));
end
end
function test_this()
m = 3;
n = 5;
X = randn(m,n);
testBackprop(@(X)logsumexp(X),X);
end
|
github | bsxfan/meta-embeddings-master | sample_speaker.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/synthdata/sample_speaker.m | 1,520 | utf_8 | f0f62cb9af06dc368f90cf9c9d6c92d3 | function [X,precisions] = sample_speaker(z,F,k,n,chi_sq)
% Sample n heavy-tailed observations of speaker with identity variable z.
% Inputs:
% z: d-by-1 speaker identity variable
% F: D-by-d factor loading matrix
% k: integer, k>=1, where nu=2k is degrees of freedom of resulting
% t-distribution
% n: number of samples
% chi_sq: [optional] If given and true, then precisions are sampled from
% chi^2 with DF: nu = k*2. In this case, k*2 must be an integer,
% so for example k=0.5 is valid and gives Cauchy samples.
%
% Output:
% X: D-by-n samples
% precisions: 1-by-n, the hidden precisions
if nargin==0
test_this();
return;
end
if ~exist('n','var') || isempty(n)
n = size(z,2);
end
if exist('chi_sq','var') && ~isempty(chi_sq) && chi_sq
% sample Chi^2, with DF = nu=2k, scaled by 1/nu, so that mean = 1.
nu = 2*k;
precisions = mean(randn(nu,n).^2,1);
else %Gamma
% Sample n precisions independently from Gamma(k,k), which has mean = 1
% mode = (k-1)/k.
precisions = -mean(log(rand(k,n)),1);
end
std = 1./sqrt(precisions);
dim = size(F,1);
Y = bsxfun(@times,std,randn(dim,n));
X = bsxfun(@plus,F*z,Y);
end
function test_this()
close all;
z = 0;
F = zeros(100,1);
k = 5;
[X,precisions] = sample_speaker(z,F,k,1000);
figure;
plot(X(1,:),X(2,:),'.');
figure;
plot(sum(X.^2,1),1./precisions,'.');
end |
github | bsxfan/meta-embeddings-master | sample_HTnoise.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/synthdata/sample_HTnoise.m | 695 | utf_8 | 9ffb422905007acca5d9b5c71ee828a9 | function [X,precisions] = sample_HTnoise(nu,dim,n)
% Sample n heavy-tailed observations of speaker with identity variable z.
% Inputs:
% nu: integer nu >=1, degrees of freedom of resulting t-distribution
% n: number of samples
%
% Output:
% X: dim-by-n samples
% precisions: 1-by-n, the hidden precisions
if nargin==0
test_this();
return;
end
precisions = mean(randn(nu,n).^2,1);
std = 1./sqrt(precisions);
X = bsxfun(@times,std,randn(dim,n));
end
function test_this()
close all;
[X,precisions] = sample_HTnoise(2,2,1000);
figure;
plot(X(1,:),X(2,:),'.');
figure;
plot(sum(X.^2,1),1./precisions,'.');
end |
github | bsxfan/meta-embeddings-master | qfuser_linear.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/fusion/funcs/qfuser_linear.m | 2,337 | utf_8 | 0fe31df563db3c6f4f08ea791e83c340 | function [fusion,w0] = qfuser_linear(w,scores,scrQ,ndx,w_init)
% This function does the actual quality fusion (and is passed to
% the training function when training the quality fusion weights).
% The scores from the linear fusion are added to the combined
% quality measure for each trial to produce the final score.
% Inputs:
% w: The trained quality fusion weights. If empty, this function
% returns a function handle.
% scores: A matrix of scores where the number of rows is the
% number of systems to be fused and the number of columns
% is the number of scores.
% scrQ: An object of type Quality containing the quality measures
% for models and segments.
% ndx: A Key or Ndx object indicating trials.
% w_init: The trained weights from the linear fusion (without
% quality measures) training.
% Outputs:
% fusion: If w is supplied, fusion is a vector of fused scores.
% If w is not supplied, fusion is a function handle to a
% function that takes w as input and produces a vector of fused
% scores as output. This function wraps the scores and quality
% measures.
% w0: Initial weights for starting the quality fusion training.
if nargin==0
test_this();
return
end
assert(isa(scrQ,'Quality'))
assert(isa(ndx,'Ndx')||isa(ndx,'Key'))
if ~exist('w_init','var')
assert(~isempty(w),'If w=[], then w_init must be supplied.');
w_init = w;
end
[m,n] = size(scores);
wlin_sz = m+1;
% linear fuser
f1 = linear_fuser([],scores);
w1 = w_init(1:wlin_sz);
[wlin,wq] = splitvec_fh(wlin_sz);
f1 = f1(wlin);
[q,n1] = size(scrQ.modelQ);
[q2,n2] = size(scrQ.segQ);
assert(q==q2);
scrQ.modelQ = [scrQ.modelQ;ones(1,n1)];
scrQ.segQ = [scrQ.segQ;ones(1,n2)];
q = q + 1;
f2 = AWB_sparse(scrQ,ndx,tril_to_symm_fh(q));
f2 = f2(wq);
wq_sz = q*(q+1)/2;
w3 = zeros(wq_sz,1);
% assemble
fusion = sum_of_functions(w,[1,1],f1,f2);
w0 = [w1;w3];
end
function test_this()
k = 2;
m = 3;
n = 4;
q = 2;
qual = Quality();
qual.modelQ = randn(q,m);
qual.segQ = randn(q,n);
ndx = Ndx();
ndx.trialmask = false(m,n);
ndx.trialmask(1,1:2) = true;
ndx.trialmask(2:3,3:4) = true;
scores = randn(k,sum(ndx.trialmask(:)));
w_init = [randn(k+1,1)]; % linear init
[fusion,w0] = qfuser_linear([],scores,qual,ndx,w_init);
test_MV2DF(fusion,w0);
[fusion(w0),linear_fuser(w_init,scores)]
end
|
github | bsxfan/meta-embeddings-master | AWB_sparse.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/fusion/funcs/AWB_sparse.m | 2,062 | utf_8 | dcb6e85fdcca1dfb1b5cdee3eb6ab112 | function fh = AWB_sparse(qual,ndx,w)
% Produces trial quality measures from segment quality measures
% using the weighting matrix 'w'.
% This is almost an MV2DF, but it does not return derivatives on numeric
% input, w.
%
% Algorithm: Y = A*reshape(w,..)*B
% Inputs:
% qual: A Quality object containing quality measures in modelQ
% and segQ fields.
% ndx: A Key or Ndx object indicating trials.
% w: The combination weights for making trial quality measures.
% Outputs:
% fh: If 'w' is given, vector of quality scores --- one for each
% trial. If 'w' is empty, a function handle that produces
% these scores given a 'w'.
if nargin==0
test_this();
return
end
assert(isa(qual,'Quality'))
assert(isa(ndx,'Ndx')||isa(ndx,'Key'))
[q,m] = size(qual.modelQ);
[q1,n] = size(qual.segQ);
assert(q==q1);
if isa(ndx,'Ndx')
trials = ndx.trialmask;
else
trials = ndx.tar | ndx.non;
end
ftrials = find(trials(:));
k = length(ftrials);
assert(m==size(trials,1)&n==size(trials,2));
[ii,jj] = ind2sub([m,n],ftrials);
function y = map_this(w)
WR = reshape(w,q,q)*qual.segQ;
y = zeros(1,k);
done = 0;
for j=1:n
right = WR(:,j);
col = right.'*qual.modelQ(:,trials(:,j));
len = length(col);
y(done+1:done+len) = col;
done = done + len;
end
assert(done==k);
end
function w = transmap_this(y)
Y = sparse(ii,jj,y,m,n);
w = qual.modelQ*Y*qual.segQ.';
end
map = @(y) map_this(y);
transmap = @(y) transmap_this(y);
fh = linTrans([],map,transmap);
if exist('w','var') && ~isempty(w)
fh = fh(w);
end
end
function test_this()
m = 3;
n = 4;
q = 2;
qual = Quality();
qual.modelQ = randn(q,m);
qual.segQ = randn(q,n);
ndx = Ndx();
ndx.trialmask = false(m,n);
ndx.trialmask(1,1:2) = true;
ndx.trialmask(2:3,3:4) = true;
ndx.trialmask
f = AWB_sparse(qual,ndx);
w = randn(q*q,1);
test_MV2DF(f,w);
W = reshape(w,q,q)
AWB = qual.modelQ'*W*qual.segQ
[f(w),AWB(ndx.trialmask(:))]
end
|
github | bsxfan/meta-embeddings-master | dcfplot.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/plotting/dcfplot.m | 1,889 | utf_8 | 9fbbba6b08ba70f285386536481e29d5 | function dcfplot(devkeyname,evalkeyname,devscrfilename,evalscrfilename,outfilename,plot_title,xmin,xmax,ymin,ymax,prior)
% Makes a Norm_DCF plot of the dev and eval scores for a system.
% Inputs:
% devkeyname: The name of the file containing the Key for
% the dev scores.
% evalkeyname: The name of the file containing the Key for
% the eval scores.
% devscrfilename: The name of the file containing the Scores
% for the dev trials.
% evalscrfilename: The name of the file containing the
% Scores the eval trials.
% outfilename: The name for the PDF file that the plot will be
% written in.
% plot_title: A string for the plot title. (optional)
% xmin, xmax, ymin, ymax: The boundaries of the plot. (optional)
% prior: The effective target prior. (optional)
assert(isa(devkeyname,'char'))
assert(isa(evalkeyname,'char'))
assert(isa(devscrfilename,'char'))
assert(isa(evalscrfilename,'char'))
assert(isa(outfilename,'char'))
if ~exist('plot_title','var') || isempty(plot_title)
plot_title = '';
end
if ~exist('xmin','var')
xmin = -10;
xmax = 0;
ymin = 0;
ymax = 1.2;
prior = 0.001;
end
[dev_tar,dev_non] = get_tar_non_scores(devscrfilename,devkeyname);
[eval_tar,eval_non] = get_tar_non_scores(evalscrfilename,evalkeyname);
close all
plot_obj = Norm_DCF_Plot([xmin,xmax,ymin,ymax],plot_title);
plot_obj.set_system(dev_tar,dev_non,'dev')
plot_obj.plot_operating_point(logit(prior),'m--','new DCF point')
plot_obj.plot_curves([0 0 0 1 1 1 0 0],{{'b--'},{'g--'},{'r--'}})
plot_obj.set_system(eval_tar,eval_non,'eval')
plot_obj.plot_curves([0 0 1 1 1 1 0 1],{{'r','LineWidth',2},{'b'},{'g'},{'r'},{'k*'}})
plot_obj.display_legend()
plot_obj.save_as_pdf(outfilename)
end
function [tar,non] = get_tar_non_scores(scrfilename,keyname)
key = Key.read(keyname);
scr = Scores.read(scrfilename);
[tar,non] = scr.get_tar_non(key);
end
|
github | bsxfan/meta-embeddings-master | fast_actDCF.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/stats/fast_actDCF.m | 3,032 | utf_8 | 5e62c5e1058f0ba3f5a59149249da2a9 | function [dcf,Pmiss,Pfa] = fast_actDCF(tar,non,plo,normalize)
% Computes the actual average cost of making Bayes decisions with scores
% calibrated to act as log-likelihood-ratios. The average cost (DCF) is
% computed for a given range of target priors and for unity cost of error.
% If un-normalized, DCF is just the Bayes error-rate.
%
% Usage examples: dcf = fast_actDCF(tar,non,-10:0.01:0)
% norm_dcf = fast_actDCF(tar,non,-10:0.01:0,true)
% [dcf,pmiss,pfa] = fast_actDCF(tar,non,-10:0.01:0)
%
% Inputs:
% tar: a vector of T calibrated target scores
% non: a vector of N calibrated non-target scores
% Both are assumed to be of the form
%
% log P(data | target)
% llr = -----------------------
% log P(data | non-target)
%
% where log is the natural logarithm.
%
% plo: an ascending vector of log-prior-odds, plo = logit(Ptar)
% = log(Ptar) - log(1-Ptar)
%
% normalize: (optional, default false) return normalized dcf if true.
%
%
% Outputs:
% dcf: a vector of DCF values, one for every value of plo.
%
% dcf(plo) = Ptar(plo)*Pmiss(plo) + (1-Ptar(plo))*Pfa(plo)
%
% where Ptar(plo) = sigmoid(plo) = 1./(1+exp(-plo)) and
% where Pmiss and Pfa are computed by counting miss and false-alarm
% rates, when comparing 'tar' and 'non' scores to the Bayes decision
% threshold, which is just -plo. If 'normalize' is true, then dcf is
% normalized by dividing by min(Ptar,1-Ptar).
%
% Pmiss: empirical actual miss rate, one value per element of plo.
% Pmiss is not altered by parameter 'normalize'.
%
% Pfa: empirical actual false-alarm rate, one value per element of plo.
% Pfa is not altered by parameter 'normalize'.
%
% Note, the decision rule applied here is to accept if
%
% llr >= Bayes threshold.
%
% or reject otherwise. The >= is a consequence of the stability of the
% sort algorithm , where equal values remain in the original order.
%
%
if nargin==0
test_this();
return
end
assert(isvector(tar))
assert(isvector(non))
assert(isvector(plo))
assert(issorted(plo),'Parameter plo must be in ascending order.');
tar = tar(:)';
non = non(:)';
plo = plo(:)';
if ~exist('normalize','var') || isempty(normalize)
normalize = false;
end
D = length(plo);
T = length(tar);
N = length(non);
[s,ii] = sort([-plo,tar]); % -plo are thresholds
r = zeros(1,T+D);
r(ii) = 1:T+D;
r = r(1:D); % rank of thresholds
Pmiss = r-(D:-1:1);
[s,ii] = sort([-plo,non]); % -plo are thresholds
r = zeros(1,N+D);
r(ii) = 1:N+D;
r = r(1:D); % rank of thresholds
Pfa = N - r + (D:-1:1);
Pmiss = Pmiss / T;
Pfa = Pfa / N;
Ptar = sigmoid(plo);
Pnon = sigmoid(-plo);
dcf = Ptar.*Pmiss + Pnon.*Pfa;
if normalize
dcf = dcf ./ min(Ptar,Pnon);
end
end
function test_this()
tar = [1 2 5 7];
non = [-7 -5 -2 -1];
plo = -6:6;
[dcf,Pmiss,Pfa] = fast_actDCF(tar,non,plo)
end
|
github | bsxfan/meta-embeddings-master | fast_minDCF.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/stats/fast_minDCF.m | 2,585 | utf_8 | 6a709a2b121037d7919f57c87d835531 | function [minDCF,Pmiss,Pfa,prbep,eer] = fast_minDCF(tar,non,plo,normalize)
% Inputs:
%
% tar: vector of target scores
% non: vector of non-target scores
% plo: vector of prior-log-odds: plo = logit(Ptar)
% = log(Ptar) - log(1-Ptar)
%
% normalize: if true, return normalized minDCF, else un-normalized.
% (optional, default = false)
%
% Output:
% minDCF: a vector with one value for every element of plo
% Note that minDCF is parametrized by plo:
%
% minDCF(Ptar) = min_t Ptar * Pmiss(t) + (1-Ptar) * Pfa(t)
%
% where t is the adjustable decision threshold and
% Ptar = sigmoid(plo) = 1./(1+exp(-plo))
% If normalize == true, then the returned value is
% minDCF(Ptar) / min(Ptar,1-Ptar).
%
%
% Pmiss: a vector with one value for every element of plo.
% This is Pmiss(tmin), where tmin is the minimizing threshold
% for minDCF, at every value of plo. Pmiss is not altered by
% parameter 'normalize'.
%
% Pfa: a vector with one value for every element of plo.
% This is Pfa(tmin), where tmin is the minimizing threshold for
% minDCF, at every value of plo. Pfa is not altered by
% parameter 'normalize'.
%
% prbep: precision-recall break-even point: Where #FA == #miss
%
% eer: the equal error rate.
%
% Note, for the un-normalized case:
% minDCF(plo) = sigmoid(plo).*Pfa(plo) + sigmoid(-plo).*Pmiss(plo)
if nargin==0
test_this();
return
end
assert(isvector(tar))
assert(isvector(non))
assert(isvector(plo))
if ~exist('normalize','var') || isempty(normalize)
normalize = false;
end
plo = plo(:);
[Pmiss,Pfa] = rocch(tar,non);
if nargout > 3
Nmiss = Pmiss * length(tar);
Nfa = Pfa * length(non);
prbep = rocch2eer(Nmiss,Nfa);
end
if nargout > 4
eer = rocch2eer(Pmiss,Pfa);
end
Ptar = sigmoid(plo);
Pnon = sigmoid(-plo);
cdet = [Ptar,Pnon]*[Pmiss(:)';Pfa(:)'];
[minDCF,ii] = min(cdet,[],2);
if nargout>1
Pmiss = Pmiss(ii);
Pfa = Pfa(ii);
end
if normalize
minDCF = minDCF ./ min(Ptar,Pnon);
end
end
function test_this
close all;
plo = -20:0.01:20;
tar = randn(1,1e4)+4;
non = randn(1,1e4);
minDCF = fast_minDCF(tar,non,plo,true);
%sminDCF = slow_minDCF(tar,non,plo,true);
%plot(plo,minDCF,'r',plo,sminDCF,'k');
plot(plo,minDCF,'r');
hold on;
tar = randn(1,1e5)+4;
non = randn(1,1e5);
minDCF = fast_minDCF(tar,non,plo,true);
plot(plo,minDCF,'g')
tar = randn(1,1e6)+4;
non = randn(1,1e6);
minDCF = fast_minDCF(tar,non,plo,true);
plot(plo,minDCF,'b')
hold off;
end
|
github | bsxfan/meta-embeddings-master | rocch.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/det/rocch.m | 2,725 | utf_8 | 68aaac9f8a1f40d0d5eac901abc533d5 | function [pmiss,pfa] = rocch(tar_scores,nontar_scores)
% ROCCH: ROC Convex Hull.
% Usage: [pmiss,pfa] = rocch(tar_scores,nontar_scores)
% (This function has the same interface as compute_roc.)
%
% Note: pmiss and pfa contain the coordinates of the vertices of the
% ROC Convex Hull.
%
% For a demonstration that plots ROCCH against ROC for a few cases, just
% type 'rocch' at the MATLAB command line.
%
% Inputs:
% tar_scores: scores for target trials
% nontar_scores: scores for non-target trials
if nargin==0
test_this();
return
end
assert(nargin==2)
assert(isvector(tar_scores))
assert(isvector(nontar_scores))
Nt = length(tar_scores);
Nn = length(nontar_scores);
N = Nt+Nn;
scores = [tar_scores(:)',nontar_scores(:)'];
Pideal = [ones(1,Nt),zeros(1,Nn)]; %ideal, but non-monotonic posterior
%It is important here that scores that are the same (i.e. already in order) should NOT be swapped.
%MATLAB's sort algorithm has this property.
[scores,perturb] = sort(scores);
Pideal = Pideal(perturb);
[Popt,width] = pavx(Pideal);
nbins = length(width);
pmiss = zeros(1,nbins+1);
pfa = zeros(1,nbins+1);
%threshold leftmost: accept eveything, miss nothing
left = 0; %0 scores to left of threshold
fa = Nn;
miss = 0;
for i=1:nbins
pmiss(i) = miss/Nt;
pfa(i) = fa/Nn;
left = left + width(i);
miss = sum(Pideal(1:left));
fa = N - left - sum(Pideal(left+1:end));
end
pmiss(nbins+1) = miss/Nt;
pfa(nbins+1) = fa/Nn;
end
function test_this()
figure();
subplot(2,3,1);
tar = [1]; non = [0];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;legend('ROCCH','ROC');
title('2 scores: non < tar');
subplot(2,3,2);
tar = [0]; non = [1];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g-v');
axis('square');grid;
title('2 scores: tar < non');
subplot(2,3,3);
tar = [0]; non = [-1,1];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;
title('3 scores: non < tar < non');
subplot(2,3,4);
tar = [-1,1]; non = [0];
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g--v');
axis('square');grid;
title('3 scores: tar < non < tar');
xlabel('P_{fa}');
ylabel('P_{miss}');
subplot(2,3,5);
tar = randn(1,100)+1; non = randn(1,100);
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g');
axis('square');grid;
title('45^{\circ} DET');
subplot(2,3,6);
tar = randn(1,100)*2+1; non = randn(1,100);
[pmiss,pfa] = rocch(tar,non);
[pm,pf] = compute_roc(tar,non);
plot(pfa,pmiss,'r-^',pf,pm,'g');
axis('square');grid;
title('flatter DET');
end
|
github | bsxfan/meta-embeddings-master | compute_roc.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/det/compute_roc.m | 1,956 | utf_8 | 16907ef9816ee330ac64b4eeb708366b | function [Pmiss, Pfa] = compute_roc(true_scores, false_scores)
% compute_roc computes the (observed) miss/false_alarm probabilities
% for a set of detection output scores.
%
% true_scores (false_scores) are detection output scores for a set of
% detection trials, given that the target hypothesis is true (false).
% (By convention, the more positive the score,
% the more likely is the target hypothesis.)
%
% this code is matlab-tized for speed.
% speedup: Old routine 54 secs -> new routine 5.71 secs.
% for 109776 points.
%-------------------------
%Compute the miss/false_alarm error probabilities
assert(nargin==2)
assert(isvector(true_scores))
assert(isvector(false_scores))
num_true = length(true_scores);
num_false = length(false_scores);
assert(num_true>0)
assert(num_false>0)
total=num_true+num_false;
Pmiss = zeros(num_true+num_false+1, 1); %preallocate for speed
Pfa = zeros(num_true+num_false+1, 1); %preallocate for speed
scores(1:num_false,1) = false_scores;
scores(1:num_false,2) = 0;
scores(num_false+1:total,1) = true_scores;
scores(num_false+1:total,2) = 1;
scores=DETsort(scores);
sumtrue=cumsum(scores(:,2),1);
sumfalse=num_false - ([1:total]'-sumtrue);
Pmiss(1) = 0;
Pfa(1) = 1.0;
Pmiss(2:total+1) = sumtrue ./ num_true;
Pfa(2:total+1) = sumfalse ./ num_false;
end
function [y,ndx] = DETsort(x,col)
% DETsort Sort rows, the first in ascending, the remaining in decending
% thereby postponing the false alarms on like scores.
% based on SORTROWS
if nargin<1, error('Not enough input arguments.'); end
if ndims(x)>2, error('X must be a 2-D matrix.'); end
if nargin<2, col = 1:size(x,2); end
if isempty(x), y = x; ndx = []; return, end
ndx = (1:size(x,1))';
% sort 2nd column ascending
[v,ind] = sort(x(ndx,2));
ndx = ndx(ind);
% reverse to decending order
ndx(1:size(x,1)) = ndx(size(x,1):-1:1);
% now sort first column ascending
[v,ind] = sort(x(ndx,1));
ndx = ndx(ind);
y = x(ndx,:);
end
|
github | bsxfan/meta-embeddings-master | rocchdet.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/det/rocchdet.m | 5,471 | utf_8 | 2452dd1f98aad313c79879d410214cb2 | function [x,y,eer,mindcf] = rocchdet(tar,non,dcfweights,pfa_min,pfa_max,pmiss_min,pmiss_max,dps)
% ROCCHDET: Computes ROC Convex Hull and then maps that to the DET axes.
%
% (For demo, type 'rocchdet' on command line.)
%
% Inputs:
%
% tar: vector of target scores
% non: vector of non-target scores
%
% dcfweights: 2-vector, such that: DCF = [pmiss,pfa]*dcfweights(:).
% (Optional, provide only if mindcf is desired, otherwise
% omit or use [].)
%
% pfa_min,pfa_max,pmiss_min,pmiss_max: limits of DET-curve rectangle.
% The DET-curve is infinite, non-trivial limits (away from 0 and 1)
% are mandatory.
% (Uses min = 0.0005 and max = 0.5 if omitted.)
%
% dps: number of returned (x,y) dots (arranged in a curve) in DET space,
% for every straight line-segment (edge) of the ROC Convex Hull.
% (Uses dps = 100 if omitted.)
%
% Outputs:
%
% x: probit(Pfa)
% y: probit(Pmiss)
% eer: ROCCH EER = max_p mindcf(dcfweights=[p,1-p]), which is also
% equal to the intersection of the ROCCH with the line pfa = pmiss.
%
% mindcf: Identical to result using traditional ROC, but
% computed by mimimizing over the ROCCH vertices, rather than
% over all the ROC points.
if nargin==0
test_this();
return
end
assert(isvector(tar))
assert(isvector(non))
if ~exist('pmiss_max','var') || isempty(pmiss_max)
pfa_min = 0.0005;
pfa_max = 0.5;
pmiss_min = 0.0005;
pmiss_max = 0.5;
end
if ~exist('dps','var') || isempty(dps)
dps = 100;
end
assert(pfa_min>0 && pfa_max<1 && pmiss_min>0 && pmiss_max<1,'limits must be strictly inside (0,1)');
assert(pfa_min<pfa_max && pmiss_min < pmiss_max);
[pmiss,pfa] = rocch(tar,non);
if nargout>3
dcf = dcfweights(:)'*[pmiss(:)';pfa(:)'];
mindcf = min(dcf);
end
%pfa is decreasing
%pmiss is increasing
box.left = pfa_min;
box.right = pfa_max;
box.top = pmiss_max;
box.bottom = pmiss_min;
x = [];
y = [];
eer = 0;
for i=1:length(pfa)-1
xx = pfa(i:i+1);
yy = pmiss(i:i+1);
[xdots,ydots,eerseg] = plotseg(xx,yy,box,dps);
x = [x,xdots];
y = [y,ydots];
eer = max(eer,eerseg);
end
end
function [x,y,eer] = plotseg(xx,yy,box,dps)
%xx and yy should be sorted:
assert(xx(2)<=xx(1)&&yy(1)<=yy(2));
XY = [xx(:),yy(:)];
dd = [1,-1]*XY;
if min(abs(dd))==0
eer = 0;
else
%find line coefficieents seg s.t. seg'[xx(i);yy(i)] = 1,
%when xx(i),yy(i) is on the line.
seg = XY\[1;1];
eer = 1/(sum(seg)); %candidate for EER, eer is highest candidate
end
%segment completely outside of box
if xx(1)<box.left || xx(2)>box.right || yy(2)<box.bottom || yy(1)>box.top
x = [];
y = [];
return
end
if xx(2)<box.left
xx(2) = box.left;
yy(2) = (1-seg(1)*box.left)/seg(2);
end
if xx(1)>box.right
xx(1) = box.right;
yy(1) = (1-seg(1)*box.right)/seg(2);
end
if yy(1)<box.bottom
yy(1) = box.bottom;
xx(1) = (1-seg(2)*box.bottom)/seg(1);
end
if yy(2)>box.top
yy(2) = box.top;
xx(2) = (1-seg(2)*box.top)/seg(1);
end
dx = xx(2)-xx(1);
xdots = xx(1)+dx*(0:dps)/dps;
ydots = (1-seg(1)*xdots)/seg(2);
x = probit(xdots);
y = probit(ydots);
end
function test_this
subplot(2,3,1);
hold on;
make_det_axes();
tar = randn(1,100)+2;
non = randn(1,100);
[x,y,eer] = rocchdet(tar,non);
[pmiss,pfa] = compute_roc(tar,non);
plot(x,y,'g',probit(pfa),probit(pmiss),'r');
legend(sprintf('ROCCH-DET (EER = %3.1f%%)',eer*100),'classical DET',...
'Location','SouthWest');
title('EER read off ROCCH-DET');
subplot(2,3,2);
show_eer(pmiss,pfa,eer);
subplot(2,3,3);
[pmiss,pfa] = rocch(tar,non);
show_eer(pmiss,pfa,eer);
subplot(2,3,4);
hold on;
make_det_axes();
tar = randn(1,100)*2+3;
non = randn(1,100);
[x,y,eer] = rocchdet(tar,non);
[pmiss,pfa] = compute_roc(tar,non);
plot(x,y,'b',probit(pfa),probit(pmiss),'k');
legend(sprintf('ROCCH-DET (EER = %3.1f%%)',eer*100),'classical DET',...
'Location','SouthWest');
title('EER read off ROCCH-DET');
subplot(2,3,5);
show_eer(pmiss,pfa,eer);
subplot(2,3,6);
[pmiss,pfa] = rocch(tar,non);
show_eer(pmiss,pfa,eer);
end
function show_eer(pmiss,pfa,eer)
p = 0:0.001:1;
x = p;
y = zeros(size(p));
for i=1:length(p);
%y(i) = mincdet @ ptar = p(i), cmiss = cfa = 1
y(i) = min(p(i)*pmiss+(1-p(i))*pfa);
end
plot([min(x),max(x)],[eer,eer],x,y);
grid;
legend('EER','minDCF(P_{tar},C_{miss}=C_{fa}=1)','Location','South');
xlabel('P_{tar}');
title('EER via minDCF on classical DET');
end
function make_det_axes()
% make_det_axes creates a plot for displaying detection performance
% with the axes scaled and labeled so that a normal Gaussian
% distribution will plot as a straight line.
%
% The y axis represents the miss probability.
% The x axis represents the false alarm probability.
%
% Creates a new figure, switches hold on, embellishes and returns handle.
pROC_limits = [0.0005 0.5];
pticks = [0.001 0.002 0.005 0.01 0.02 0.05 0.1 0.2 0.3 0.4];
ticklabels = ['0.1';'0.2';'0.5';' 1 ';' 2 ';' 5 ';'10 ';'20 ';'30 ';'40 '];
axis('square');
set (gca, 'xlim', probit(pROC_limits));
set (gca, 'xtick', probit(pticks));
set (gca, 'xticklabel', ticklabels);
set (gca, 'xgrid', 'on');
xlabel ('False Alarm probability (in %)');
set (gca, 'ylim', probit(pROC_limits));
set (gca, 'ytick', probit(pticks));
set (gca, 'yticklabel', ticklabels);
set (gca, 'ygrid', 'on')
ylabel ('Miss probability (in %)')
end
|
github | bsxfan/meta-embeddings-master | map_mod_names.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/manip/map_mod_names.m | 3,127 | utf_8 | 6aa97cdf9b5df6095e803bd14f612e52 | function ndx = map_mod_names(ndx,src_map,dst_map)
% Changes the model names in an index using two maps. The one map
% lists the training segment for each model name and the other map
% lists the new model name for each training segment. Existing
% model names are replaced by new model names that are mapped to
% the same training segment. If a model name is not present in the
% src_map, it is left unchanged in the output ndx. If a train seg
% is not present in the dst_map, the source model is dropped from
% the output ndx (along with all its trials).
% Inputs:
% ndx: the Key or Ndx for which the model names must be changed
% scr_map: the map from current model names to trn seg names
% dst_map: the map from trn seg names to new model names
% Outputs:
% ndx: the Key or Ndx with a modified modelset field
if nargin == 0
test_this()
return
end
assert(nargin==3)
assert(isa(ndx,'Ndx')||isa(ndx,'Key'))
assert(isstruct(src_map))
assert(isstruct(dst_map))
assert(isfield(src_map,'keySet'))
assert(isfield(dst_map,'keySet'))
assert(isfield(src_map,'values'))
assert(isfield(dst_map,'values'))
[trnsegs,is_present1] = maplookup(src_map,ndx.modelset);
num_unchanged = length(is_present1) - sum(is_present1);
if num_unchanged ~= 0
log_warning('Keeping %d model name(s) unchanged.\n',num_unchanged);
end
[newnames,is_present2] = maplookup(dst_map,trnsegs);
num_dropped = length(is_present2) - sum(is_present2);
if num_dropped ~= 0
log_warning('Discarding %d row(s) in score matrix.\n',num_dropped);
end
keepndxs = true(length(ndx.modelset),1);
keepndxs(is_present1) = is_present2;
newmodnames = cell(length(is_present2),1);
newmodnames(is_present2) = newnames;
ndx.modelset(is_present1) = newmodnames;
ndx.modelset = ndx.modelset(keepndxs);
if isa(ndx,'Ndx')
ndx.trialmask = ndx.trialmask(keepndxs,:);
else
ndx.tar = ndx.tar(keepndxs,:);
ndx.non = ndx.non(keepndxs,:);
end
function test_this()
src_map.keySet = {'mod1','mod2','mod3','mod4','mod8'};
src_map.values = {'seg1','seg2','seg3','seg5','seg8'};
dst_map.keySet = {'seg1','seg2','seg3','seg4','seg5','seg6'};
dst_map.values = {'new1','new2','new3','new4','new5','new6'};
ndx = Ndx();
fprintf('Test1\n');
ndx.modelset = {'mod2','mod3','mod4'};
ndx.trialmask = true(3,4);
fprintf('Input:\n');
disp(ndx.modelset)
fprintf('Output should be:\n');
out = {'new2','new3','new5'};
disp(out)
fprintf('Output is:\n');
newndx = map_mod_names(ndx,src_map,dst_map);
disp(newndx.modelset)
fprintf('Test2\n');
ndx.modelset = {'mod2','mod3','mod10','mod4','mod6'};
ndx.trialmask = true(5,4);
fprintf('Input:\n');
disp(ndx.modelset)
fprintf('Output should be:\n');
out = {'new2','new3','mod10','new5','mod6'};
disp(out)
fprintf('Output is:\n');
newndx = map_mod_names(ndx,src_map,dst_map);
disp(newndx.modelset)
fprintf('Test3\n');
ndx.modelset = {'mod2','mod3','mod10','mod4','mod8','mod6'};
ndx.trialmask = true(6,4);
fprintf('Input:\n');
disp(ndx.modelset)
fprintf('Output should be:\n');
out = {'new2','new3','mod10','new5','mod6'};
disp(out)
fprintf('Output is:\n');
newndx = map_mod_names(ndx,src_map,dst_map);
disp(newndx.modelset)
|
github | bsxfan/meta-embeddings-master | maplookup.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/manip/maplookup.m | 3,084 | utf_8 | 9e8a55e6a2201b6a0e975469dfe9c299 | function [values,is_present] = maplookup(map,keys)
% Does a map lookup, to map mutliple keys to multiple values in one call.
% The parameter 'map' represents a function, where each key maps to a
% unique value. Each value may be mapped to by one or more keys.
%
% Inputs:
% map.keySet: a one-dimensional cell array;
% or one-dimensional numeric array;
% or a two dimensional char array, where each row is an
% element.
% The elements should be unique. If there are repeated elements,
% the last one of each will be used.
%
% map.values: The values that each member of keySet maps to, in the same
% order.
%
% keys: The array of keys to look up in the map. The class should agree
% with map.keySet.
%
% Outputs:
% values: a one-dimensional cell array; or one dimensional numeric array;
% or a two dimensional char array, where rows are string values.
% Each value corresponds to one of the elements in keys.
%
% is_present: logical array of same size as keys, indicating which keys
% are in map.keySet.
% Optional: if not asked, then maplookup crashes if one or
% more keys are not in the map. If is_present is asked,
% then maplookup does not crash for missing keys. The keys
% that are in the map are: keys(is_present).
if nargin==0
test_this();
return;
end
assert(nargin==2)
assert(isstruct(map))
assert(isfield(map,'keySet'))
assert(isfield(map,'values'))
if ischar(map.keySet)
keySetSize = size(map.keySet,1);
else
keySetSize = length(map.keySet);
end
if ischar(map.values)
valueSize = size(map.values,1);
else
valueSize = length(map.keySet);
end
if ~valueSize==keySetSize
error('bad map: sizes of keySet and values are different')
end
if ~strcmp(class(map.keySet),class(keys))
error('class(keys) = ''%s'', should be class(map.keySet) = ''%s''',class(keys),class(map.keySet));
end
if ischar(keys)
[is_present,at] = ismember(keys,map.keySet,'rows');
else
[is_present,at] = ismember(keys,map.keySet);
end
missing = length(is_present) - sum(is_present);
if missing>0
if nargout<2
error('%i of keys not in map',missing);
else
if ischar(map.values)
values = map.values(at(is_present),:);
else
values = map.values(at(is_present));
end
end
else
if ischar(map.values)
values = map.values(at,:);
else
values = map.values(at);
end
end
end
function test_this()
map.keySet = ['one ';'two ';'three'];
map.values = ['a';'b';'c'];
maplookup(map,['one ';'one ';'three'])
map.keySet = {'one','two','three'};
map.values = [1,2,3];
maplookup(map,{'one','one','three'})
map.values = {'a','b','c'};
maplookup(map,{'one','one','three'})
map.keySet = [1 2 3];
maplookup(map,[1 1 3])
%maplookup(map,{1 2 3})
[values,is_present] = maplookup(map,[1 1 3 4 5])
fprintf('Now testing error message:\n');
maplookup(map,[1 1 3 4 5])
end
|
github | bsxfan/meta-embeddings-master | test_binary_classifier.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/test_binary_classifier.m | 1,332 | utf_8 | 9683ce2757d7eb67c8a8ec37954cbab4 | function obj_val = test_binary_classifier(objective_function,classf, ...
prior,system,input_data)
% Returns the result of the objective function evaluated on the
% scores.
%
% Inputs:
% objective_function: a function handle to the objective function
% to feed the scores into
% classf: length T vector where T is the number of trials with entries +1 for target scores; -1
% for non-target scores
% prior: the prior (given to the system that produced the scores)
% system: a function handle to the system to be run
% input_data: the data to run the system on (to produce scores)
%
% Outputs
% obj_val: the value returned by the objective function
if nargin==0
test_this();
return;
end
scores = system(input_data);
obj_val = evaluate_objective(objective_function,scores,classf,prior);
end
function test_this()
num_trials = 100;
input_data = randn(20,num_trials);
prior = 0.5;
maxiters = 1000;
classf = [ones(1,num_trials/2),-ones(1,num_trials/2)];
tar = input_data(:,1:num_trials/2);
non = input_data(:,num_trials/2+1:end);
[sys,run_sys,w0] = linear_fusion_factory(tar,non);
w = train_binary_classifier(@cllr_obj,classf,sys,[],w0,[],maxiters,[],prior,[],true);
system = @(data) run_sys(w,data);
test_binary_classifier(@cllr_obj,classf,prior,system,input_data)
end
|
github | bsxfan/meta-embeddings-master | evaluate_objective.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/evaluate_objective.m | 1,417 | utf_8 | 70262971965caac5629612bd125dd0a2 | function obj_val = evaluate_objective(objective_function,scores,classf, ...
prior)
% Returns the result of the objective function evaluated on the
% scores.
%
% Inputs:
% objective_function: a function handle to the objective function
% to feed the scores into
% scores: length T vector of scores to be evaluated where T is
% the number of trials
% classf: length T vector with entries +1 for target scores; -1
% for non-target scores
% prior: the prior (given to the system that produced the scores)
%
% Outputs
% obj_val: the value returned by the objective function
if nargin==0
test_this();
return;
end
if ~exist('objective_function','var') || isempty(objective_function)
objective_function = @(w,T,weights,logit_prior) cllr_obj(w,T,weights,logit_prior);
end
logit_prior = logit(prior);
prior_entropy = objective_function([0;0],[1,-1],[prior,1-prior],logit_prior);
ntar = length(find(classf>0));
nnon = length(find(classf<0));
N = nnon+ntar;
weights = zeros(1,N);
weights(classf>0) = prior/(ntar*prior_entropy);
weights(classf<0) = (1-prior)/(nnon*prior_entropy);
obj_val = objective_function(scores,classf,weights,logit_prior);
end
function test_this()
num_trials = 20;
scores = randn(1,num_trials);
classf = [ones(1,num_trials/2),-ones(1,num_trials/2)];
prior = 0.5;
res = evaluate_objective(@cllr_obj,scores,classf,prior)
end
|
github | bsxfan/meta-embeddings-master | train_binary_classifier.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/train_binary_classifier.m | 3,938 | utf_8 | de96b98d88aa8e3d0c36785a2f9a3a94 | function [w,cxe,w_pen,optimizerState,converged] = ...
train_binary_classifier(classifier,classf,w0,objective_function,prior,...
penalizer,lambda,maxiters,maxCG,optimizerState,...
quiet,cstepHessian)
%
% Supervised training of a regularized fusion.
%
%
% Inputs:
%
% classifier: MV2DF function handle that maps parameters to llr-scores.
% Note: The training data is already wrapped in this handle.
%
% classf: 1-by-N row of class labels:
% -1 for non_target,
% +1 for target,
% 0 for ignore
%
% w0: initial parameters. This is NOT optional.
%
% objective_function: A function handle to an Mv2DF function that
% maps the output (llr-scores) of classifier, to
% the to-be-minimized objective (called cxe).
% optional, use [] to invoke 'cllr_obj'.
%
% prior: a prior probability for target to set the 'operating point'
% of the objective function.
% optional: use [] to invoke default of 0.5
%
% penalizer: MV2DF function handle that maps parameters to a positive
% regularization penalty.
%
% lambda: a weighting for the penalizer
%
% maxiters: the maximum number of Newton Trust Region optimization
% iterations to perform. Note, the user can make maxiters
% small, examine the solution and then continue training:
% -- see w0 and optimizerState.
%
%
%
% optimizerState: In this implementation, it is the trust region radius.
% optional:
% omit or use []
% If not supplied when resuming iteration,
% this may cost some extra iterations.
% Resume further iteration thus:
% [w1,...,optimizerState] = train_binary_classifier(...);
% ... examine solution w1 ...
% [w2,...,optimizerState] = train_binary_classifier(...,w1,...,optimizerState);
%
%
% quiet: if false, outputs more info during training
%
%
% Outputs:
% w: the solution.
% cxe: normalized multiclass cross-entropy of the solution.
% The range is 0 (good) to 1(useless).
%
% optimizerState: see above, can be used to resume iteration.
%
if nargin==0
test_this();
return;
end
if ~exist('maxCG','var') || isempty(maxCG)
maxCG = 100;
end
if ~exist('optimizerState','var')
optimizerState=[];
end
if ~exist('prior','var') || isempty(prior)
prior = 0.5;
end
if ~exist('objective_function','var') || isempty(objective_function)
objective_function = @(w,T,weights,logit_prior) cllr_obj(w,T,weights,logit_prior);
end
%prior_entropy = -prior*log(prior)-(1-prior)*log(1-prior);
prior_entropy = objective_function([0;0],[1,-1],[prior,1-prior],logit(prior));
classf = classf(:)';
ntar = length(find(classf>0));
nnon = length(find(classf<0));
N = nnon+ntar;
weights = zeros(size(classf));
weights(classf>0) = prior/(ntar*prior_entropy);
weights(classf<0) = (1-prior)/(nnon*prior_entropy);
%weights remain 0, where classf==0
w=[];
if exist('penalizer','var') && ~isempty(penalizer)
obj1 = objective_function(classifier,classf,weights,logit(prior));
obj2 = penalizer(w);
obj = sum_of_functions(w,[1,lambda],obj1,obj2);
else
obj = objective_function(classifier,classf,weights,logit(prior));
end
w0 = w0(:);
if exist('cstepHessian','var') &&~ isempty(cstepHessian)
obj = replace_hessian([],obj,cstepHessian);
end
[w,y,optimizerState,converged] = trustregion_newton_cg(obj,w0,maxiters,maxCG,optimizerState,[],1,quiet);
if exist('penalizer','var') && ~isempty(penalizer)
w_pen = lambda*obj2(w);
else
w_pen = 0;
end
cxe = y-w_pen;
if ~quiet
fprintf('cxe = %g, pen = %g\n',cxe,w_pen);
end
function test_this()
%invoke test for linear_fuser, which calls train_binary_classifier
linear_fuser();
|
github | bsxfan/meta-embeddings-master | qfuser_v5.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v5.m | 921 | utf_8 | f82cbe0c178dae2a667496466b612770 | function [fusion,w0] = qfuser_v5(w,scores,wfuse)
if nargin==0
test_this();
return;
end
% block 1
f1 = linear_fuser([],scores.scores);
w1 = wfuse;
[whead,wtail] = splitvec_fh(length(w1));
f1 = f1(whead);
% block 2
modelQ = scores.modelQ;
[q,n1] = size(modelQ);
modelQ = [modelQ;ones(1,n1)];
segQ = scores.segQ;
[q2,n2] = size(segQ);
segQ = [segQ;ones(1,n2)];
assert(q==q2);
q = q + 1;
wq = q*(q+1)/2;
f2 = AWB_fh(modelQ',segQ,tril_to_symm_fh(q,wtail));
w2 = zeros(wq,1);
% assemble
fusion = sum_of_functions(w,[1,1],f1,f2);
w0 = [w1;w2];
end
function test_this()
m = 5;
k = 2;
n1 = 4;
n2 = 5;
scores.sindx = [1,2,3];
scores.qindx = [4,5];
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
wfuse = [1,2,3,4]';
[fusion,w0] = qfuser_v4([],scores,wfuse);
%test_MV2DF(fusion,w0);
[fusion(w0),linear_fuser(wfuse,scores.scores(scores.sindx,:))]
%fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | qfuser_v2.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v2.m | 1,166 | utf_8 | e10bf159cbd2dacaf85be8d4a90554f6 | function [fusion,params] = qfuser_v2(w,scores)
%
% Inputs:
%
% scores: the primary detection scores, for training
% D-by-T matrix of T scores for D input systems
%
% quality_input: K-by-T matrix of quality measures
%
% Output:
% fusion: is numeric if w is numeric, or a handle to an MV2DF, representing:
%
% y= (alpha'*scores+beta) * sigmoid( gamma'*quality_inputs + delta)
%
if nargin==0
test_this();
return;
end
% Create building blocks
[Cal,params1] = parallel_cal_augm([],scores.scores);
m = size(scores.scores,1)+1;
[P,params2] = QQtoP(params1.tail,scores.modelQ,scores.segQ,m);
%params.get_w0 = @(wfuse) [params1.get_w0() ;params2.get_w0()];
params.get_w0 = @(wfuse) [params1.get_w0(wfuse) ;params2.get_w0()];
params.tail = params2.tail;
% Assemble building blocks
% modulate linear fusion with quality
fusion = sumcolumns_fh(m,dottimes_of_functions(w,P,Cal));
end
function test_this()
m = 3;
k = 2;
n1 = 4;
n2 = 5;
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
[fusion,params] = qfuser_v2([],scores);
w0 = params.get_w0();
test_MV2DF(fusion,w0);
fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | linear_fuser.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/linear_fuser.m | 2,654 | utf_8 | 627fab3e121d1d87d9fad2a3234d26f8 | function [fusion,params] = linear_fuser(w,scores)
%
% Does affine fusion of scores: It does a weighted sum of scores and adds
% an offset.
%
% Inputs:
% scores: M-by-N matrix of N scores for each of M input systems.
% w: Optional:
% - when supplied, the output 'fusion' is the vector of fused scores.
% - when w=[], the output 'fusion' is a function handle, to be used
% for training the fuser.
% w is a (K+1)-vector, with one weight per system, followed by the
% offset.
%
% fusion: if w is given, fusion is a vector of N fused scores.
% if w is not given, fusion is a function handle, so that
% fusion(w) = @(w) linear_fusion(scores,w).
% w0: default values for w, to initialize training.
%
% For training use:
% [fuser,params] = linear_fuser(train_scores);
% w0 = get_w0();
% w = train_binary_classifier(fuser,...,w0,...);
%
% For test use:
% fused_scores = linear_fuser(test_scores,w);
%
if nargin==0
test_this();
return;
end
if ~exist('scores','var') || isempty(scores)
fusion = sprintf(['linear fuser:',repmat(' %g',1,length(w))],w);
return;
end
wsz = size(scores,1)+1;
[whead,wtail] = splitvec_fh(wsz,w);
params.get_w0 = @() zeros(wsz,1);
%params.get_w0 = @() randn(wsz,1);
params.tail = wtail;
fusion = fusion_mv2df(whead,scores);
end
function test_this()
N = 100;
dim = 2; % number of used systems
% ----------------synthesize training data -------------------
randn('state',0);
means = randn(dim,2)*8; %signal
[tar,non] = make_data(N,means);
% ------------- create system ------------------------------
[fuser,params] = linear_fuser([],[tar,non]);
% ------------- train it ------------------------------
ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];
prior = 0.1;
maxiters = 50;
quiet = true;
objfun = [];
w0 = params.get_w0();
[w,cxe] = train_binary_classifier(fuser,classf,w0,objfun,prior,[],0,maxiters,[],[],quiet);
fprintf('train Cxe = %g\n',cxe);
% ------------- test it ------------------------------
[tar,non] = make_data(N,means);
scores = [tar,non];
tail = [1;2;3];
wbig = [w;tail];
[fused_scores,params] = linear_fuser(wbig,scores);
check_tails = [tail,params.tail],
cxe = evaluate_objective(objfun,fused_scores,classf,prior);
fprintf('test Cxe = %g\n',cxe);
plot(fused_scores);
end
function [tar,non] = make_data(N,means)
[dim,K] = size(means);
X = 5*randn(dim,K*N); % noise
ii = 1:N;
for k=1:K
X(:,ii) = bsxfun(@plus,means(:,k),X(:,ii));
ii = ii+N;
end
N = K*N;
tar = X(:,1:N/2);
non = X(:,N/2+(1:N/2));
end
|
github | bsxfan/meta-embeddings-master | qfuser_v3.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v3.m | 1,290 | utf_8 | a2245f6284afa9f203096fc932e8cf07 | function [fusion,params] = qfuser_v3(w,scores)
%
% Inputs:
%
% scores: the primary detection scores, for training
% D-by-T matrix of T scores for D input systems
%
% quality_input: K-by-T matrix of quality measures
%
% Output:
% fusion: is numeric if w is numeric, or a handle to an MV2DF, representing:
%
% y= (alpha'*scores+beta) * sigmoid( gamma'*quality_inputs + delta)
%
if nargin==0
test_this();
return;
end
% Create building blocks
[Cal,params1] = parallel_cal([],scores.scores);
m = size(scores.scores,1);
[LLH,params2] = QQtoLLH(params1.tail,scores.modelQ,scores.segQ,m);
P = LLH;
%P = exp_mv2df(logsoftmax_trunc_mv2df(LLH,m));
W = reshape(params2.get_w0(),[],m);
W(:) = 0;
W(end,:) = 0.5/(m+1);
%params.get_w0 = @(wfuse) [params1.get_w0(wfuse) ;params2.get_w0()];
params.get_w0 = @(wfuse) [params1.get_w0(wfuse) ;W(:)];
params.tail = params2.tail;
% Assemble building blocks
% modulate linear fusion with quality
fusion = sumcolumns_fh(m,dottimes_of_functions(w,P,Cal));
end
function test_this()
m = 3;
k = 2;
n1 = 4;
n2 = 5;
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
[fusion,params] = qfuser_v3([],scores);
w0 = params.get_w0([1 2 3 4]');
test_MV2DF(fusion,w0);
fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | qfuser_v6.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v6.m | 1,013 | utf_8 | 0bcb6e5fbd79494afd1c1c36eff1e95c | function [fusion,w0] = qfuser_v6(w,scores,wfuse)
if nargin==0
test_this();
return;
end
% block 1
f1 = linear_fuser([],scores.scores);
w1 = wfuse;
[whead,wtail] = splitvec_fh(length(w1));
f1 = f1(whead);
% block 2
modelQ = scores.modelQ;
[q,n1] = size(modelQ);
modelQ = [modelQ;ones(1,n1)];
segQ = scores.segQ;
[q2,n2] = size(segQ);
segQ = [segQ;ones(1,n2)];
assert(q==q2);
q = q + 1;
wq = q*(q+1)/2;
r = AWB_fh(modelQ',segQ,tril_to_symm_fh(q));
[whead,wtail] = splitvec_fh(wq,wtail);
r = r(whead);
w2 = zeros(wq,1);w2(end) = -5;
% block 3
s = AWB_fh(modelQ',segQ,tril_to_symm_fh(q,wtail));
w3 = w2;
% assemble
rs = stack([],r,s);
fusion = scalibration_fh(stack(w,f1,rs));
w0 = [w1;w2;w3];
end
function test_this()
m = 3;
k = 2;
n1 = 4;
n2 = 5;
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
wfuse = [1,2,3,4]';
[fusion,w0] = qfuser_v6([],scores,wfuse);
test_MV2DF(fusion,w0);
[fusion(w0),linear_fuser(wfuse,scores.scores)]
%fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | qfuser_v1.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v1.m | 1,137 | utf_8 | 8dcda09e63d0f7e6a3f1fc2298b84d7e | function [fusion,params] = qfuser_v1(w,scores)
%
% Inputs:
%
% scores: the primary detection scores, for training
% D-by-T matrix of T scores for D input systems
%
% quality_input: K-by-T matrix of quality measures
%
% Output:
% fusion: is numeric if w is numeric, or a handle to an MV2DF, representing:
%
% y= (alpha'*scores+beta) * sigmoid( gamma'*quality_inputs + delta)
%
if nargin==0
test_this();
return;
end
% Create building blocks
[linfusion,params1] = linear_fuser([],scores.scores);
[Q,params2] = outerprod_of_sigmoids(params1.tail,scores.modelQ,scores.segQ);
params.get_w0 = @(ssat) [params1.get_w0(); params2.get_w0(ssat)];
params.tail = params2.tail;
% Assemble building blocks
% modulate linear fusion with quality
fusion = dottimes_of_functions([],Q,linfusion);
if ~isempty(w)
fusion = fusion(w);
end
end
function test_this()
m = 3;
k = 2;
n1 = 4;
n2 = 5;
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
ssat = 0.99;
[fusion,params] = qfuser_v1([],scores);
w0 = params.get_w0(ssat);
test_MV2DF(fusion,w0);
fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | qfuser_v7.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v7.m | 1,107 | utf_8 | 8d156ad2d97a7aa1b90d702cb2f0a195 | function [fusion,w0] = qfuser_v7(w,scores,wfuse)
if nargin==0
test_this();
return;
end
% block 1
f1 = linear_fuser([],scores.scores);
w1 = wfuse;
[whead,wtail] = splitvec_fh(length(w1));
f1 = f1(whead);
% block 2
modelQ = scores.modelQ;
[q,n1] = size(modelQ);
modelQ = [modelQ;ones(1,n1)];
segQ = scores.segQ;
[q2,n2] = size(segQ);
segQ = [segQ;ones(1,n2)];
assert(q==q2);
q = q + 1;
wq = q*(q+1)/2;
f2 = AWB_fh(modelQ',segQ,tril_to_symm_fh(q));
w2 = zeros(wq,1);
[whead,rs] = splitvec_fh(wq,wtail);
f2 = f2(whead);
% block 3
n = size(scores.scores,2);
map = @(rs) repmat(rs,n,1);
transmap =@(RS) sum(reshape(RS,2,[]),2);
RS = linTrans(rs,map,transmap);
w3 = [-10;-10];
% assemble
f12 = sum_of_functions([],[1,1],f1,f2);
XRS = stack(w,f12,RS);
fusion = scalibration_fh(XRS);
w0 = [w1;w2;w3];
end
function test_this()
m = 3;
k = 2;
n1 = 4;
n2 = 5;
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
wfuse = [1,2,3,4]';
[fusion,w0] = qfuser_v7([],scores,wfuse);
test_MV2DF(fusion,w0);
[fusion(w0),linear_fuser(wfuse,scores.scores)]
end
|
github | bsxfan/meta-embeddings-master | qfuser_v4.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/qfuser_v4.m | 1,388 | utf_8 | cd65aea99057c92c142fc7e024dc1d53 | function [fusion,w0] = qfuser_v4(w,scores,wfuse)
% qindx: index set for rows of scores.scores which are per-trial quality
% measures.
%
% sindx: index set for rows of scores.scores which are normal discriminative
% scores.
if nargin==0
test_this();
return;
end
sindx = scores.sindx;
qindx = scores.qindx;
m =length(sindx);
% Create building blocks
[Cal,w1] = parallel_cal([],scores.scores(sindx,:),wfuse);
[whead,wtail] = splitvec_fh(length(w1));
Cal = Cal(whead);
[LLH1,w2] = QQtoLLH([],scores.modelQ,scores.segQ,m);
[whead,wtail] = splitvec_fh(length(w2),wtail);
LLH1 = LLH1(whead);
W2 = reshape(w2,[],m);
W2(:) = 0;
W2(end,:) = 0.5/(m+1);
w2 = W2(:);
[LLH2,w3] = QtoLLH([],scores.scores(qindx,:),m);
LLH2 = LLH2(wtail);
LLH = sum_of_functions([],[1,1],LLH1,LLH2);
%LLH = LLH1;
P = LLH;
%P = exp_mv2df(logsoftmax_trunc_mv2df(LLH,m));
w0 = [w1;w2;w3];
% Assemble building blocks
% modulate linear fusion with quality
fusion = sumcolumns_fh(m,dottimes_of_functions(w,P,Cal));
end
function test_this()
m = 5;
k = 2;
n1 = 4;
n2 = 5;
scores.sindx = [1,2,3];
scores.qindx = [4,5];
scores.scores = randn(m,n1*n2);
scores.modelQ = randn(k,n1);
scores.segQ = randn(k,n2);
wfuse = [1,2,3,4]';
[fusion,w0] = qfuser_v4([],scores,wfuse);
%test_MV2DF(fusion,w0);
[fusion(w0),linear_fuser(wfuse,scores.scores(scores.sindx,:))]
%fusion(w0)
end
|
github | bsxfan/meta-embeddings-master | scal_fuser.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/scal_fuser.m | 2,918 | utf_8 | 7e49185b74a064be721d9c243a08c07f | function [fusion,params] = scal_fuser(w,scores)
%
% Does scal calibration
%
% Inputs:
% scores: M-by-N matrix of N scores for each of M input systems.
% w: Optional:
% - when supplied, the output 'fusion' is the vector of fused scores.
% - when w=[], the output 'fusion' is a function handle, to be used
% for training the fuser.
% w is a (K+1)-vector, with one weight per system, followed by the
% offset.
%
% fusion: if w is given, fusion is a vector of N fused scores.
% if w is not given, fusion is a function handle, so that
% fusion(w) = @(w) linear_fusion(scores,w).
% w0: default values for w, to initialize training.
%
% For training use:
% [fuser,params] = scal_fuser(train_scores);
% w0 = params.get_w0();
% w = train_binary_classifier(fuser,...,w0,...);
%
% For test use:
% fused_scores = scal_fuser(test_scores,w);
%
if nargin==0
test_this();
return;
end
if ~exist('scores','var') || isempty(scores)
fusion = sprintf(['scal fuser:',repmat(' %g',1,length(w))],w);
return;
end
[m,n] = size(scores);
wsz = size(scores,1)+1;
[wlin,wtail] = splitvec_fh(wsz);
[rs,wtail] = splitvec_fh(2,wtail);
x = fusion_mv2df(wlin,scores);
xrs = stack([],x,rs);
fusion = scal_simple_fh(xrs);
if ~isempty(w)
fusion = fusion(w);
wtail = wtail(w);
end
params.get_w0 = @() [zeros(wsz,1);-10;-10];
params.tail = wtail;
end
function test_this()
N = 10;
dim = 2; % number of used systems
% ----------------synthesize training data -------------------
randn('state',0);
means = randn(dim,2)*8; %signal
[tar,non] = make_data(N,means);
tar = [tar,[min(non(1,:));min(non(2,:))]];
non = [non,[max(tar(1,:));max(tar(2,:))]];
% ------------- create system ------------------------------
[fuser,params] = scal_fuser([],[tar,non]);
w0 = params.get_w0();
test_mv2df(fuser,w0);
return;
% ------------- train it ------------------------------
ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];
prior = 0.1;
maxiters = 50;
quiet = false;
objfun = [];
w0 = params.get_w0();
[w,cxe] = train_binary_classifier(fuser,classf,w0,objfun,prior,[],0,maxiters,[],[],quiet);
fprintf('train Cxe = %g\n',cxe);
% ------------- test it ------------------------------
[tar,non] = make_data(N,means);
ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];
scores = [tar,non];
tail = [1;2;3];
wbig = [w;tail];
[fused_scores,params] = scal_fuser(wbig,scores);
check_tails = [tail,params.tail],
cxe = evaluate_objective(objfun,fused_scores,classf,prior);
fprintf('test Cxe = %g\n',cxe);
plot(fused_scores);
end
function [tar,non] = make_data(N,means)
[dim,K] = size(means);
X = 5*randn(dim,K*N); % noise
ii = 1:N;
for k=1:K
X(:,ii) = bsxfun(@plus,means(:,k),X(:,ii));
ii = ii+N;
end
N = K*N;
tar = X(:,1:N/2);
non = X(:,N/2+(1:N/2));
end
|
github | bsxfan/meta-embeddings-master | scal_fuser_slow.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/scal_fuser_slow.m | 2,972 | utf_8 | abc2a78dc2b6cf08cfdd508f4dabdb71 | function [fusion,params] = scal_fuser_slow(w,scores)
%
% Does scal calibration
%
% Inputs:
% scores: M-by-N matrix of N scores for each of M input systems.
% w: Optional:
% - when supplied, the output 'fusion' is the vector of fused scores.
% - when w=[], the output 'fusion' is a function handle, to be used
% for training the fuser.
% w is a (K+1)-vector, with one weight per system, followed by the
% offset.
%
% fusion: if w is given, fusion is a vector of N fused scores.
% if w is not given, fusion is a function handle, so that
% fusion(w) = @(w) linear_fusion(scores,w).
% w0: default values for w, to initialize training.
%
% For training use:
% [fuser,params] = scal_fuser(train_scores);
% w0 = params.get_w0();
% w = train_binary_classifier(fuser,...,w0,...);
%
% For test use:
% fused_scores = scal_fuser(test_scores,w);
%
if nargin==0
test_this();
return;
end
if ~exist('scores','var') || isempty(scores)
fusion = sprintf(['scal fuser:',repmat(' %g',1,length(w))],w);
return;
end
[m,n] = size(scores);
wsz = size(scores,1)+1;
[wlin,wtail] = splitvec_fh(wsz);
[rs,wtail] = splitvec_fh(2,wtail);
map = @(rs) repmat(rs,n,1);
transmap =@(RS) sum(reshape(RS,2,[]),2);
RS = linTrans(rs,map,transmap);
X = fusion_mv2df(wlin,scores);
XRS = stack([],X,RS);
fusion = scalibration_fh(XRS);
if ~isempty(w)
fusion = fusion(w);
wtail = wtail(w);
end
params.get_w0 = @() [zeros(wsz,1);-5;-5];
params.tail = wtail;
end
function test_this()
N = 1000;
dim = 2; % number of used systems
% ----------------synthesize training data -------------------
randn('state',0);
means = randn(dim,2)*8; %signal
[tar,non] = make_data(N,means);
tar = [tar,[min(non(1,:));min(non(2,:))]];
non = [non,[max(tar(1,:));max(tar(2,:))]];
% ------------- create system ------------------------------
[fuser,params] = scal_fuser([],[tar,non]);
% ------------- train it ------------------------------
ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];
prior = 0.1;
maxiters = 50;
quiet = false;
objfun = [];
w0 = params.get_w0();
[w,cxe] = train_binary_classifier(fuser,classf,w0,objfun,prior,[],0,maxiters,[],[],quiet);
fprintf('train Cxe = %g\n',cxe);
% ------------- test it ------------------------------
[tar,non] = make_data(N,means);
ntar = size(tar,2);
nnon = size(non,2);
classf = [ones(1,ntar),-ones(1,nnon)];
scores = [tar,non];
tail = [1;2;3];
wbig = [w;tail];
[fused_scores,params] = scal_fuser(wbig,scores);
check_tails = [tail,params.tail],
cxe = evaluate_objective(objfun,fused_scores,classf,prior);
fprintf('test Cxe = %g\n',cxe);
plot(fused_scores);
end
function [tar,non] = make_data(N,means)
[dim,K] = size(means);
X = 5*randn(dim,K*N); % noise
ii = 1:N;
for k=1:K
X(:,ii) = bsxfun(@plus,means(:,k),X(:,ii));
ii = ii+N;
end
N = K*N;
tar = X(:,1:N/2);
non = X(:,N/2+(1:N/2));
end
|
github | bsxfan/meta-embeddings-master | logsumexp_special.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/logsumexp_special.m | 1,102 | utf_8 | a15ffa60b181fdc8b0a1e3fb4bcfd403 | function [y,deriv] = logsumexp_special(w)
% This is a MV2DF. See MV2DF_API_DEFINITION.readme.
%
% If w = [x;r], where r is scalar and x vector, then
% y = log(exp(x)+exp(r))
if nargin==0
test_this();
return;
end
if isempty(w)
y = @(w)logsumexp_special(w);
return;
end
if isa(w,'function_handle')
outer = logsumexp_special([]);
y = compose_mv(outer,w,[]);
return;
end
[r,x] = get_rx(w);
rmax = (r>x);
rnotmax = ~rmax;
y = zeros(size(x));
y(rmax) = log(exp(x(rmax)-r)+1)+r;
y(rnotmax) = log(exp(r-x(rnotmax))+1)+x(rnotmax);
if nargout>1
deriv = @(Dy) deriv_this(Dy,r,x,y);
end
end
function [r,x] = get_rx(w)
w = w(:);
r = w(end);
x = w(1:end-1);
end
function [g,hess,linear] = deriv_this(dy,r,x,y)
gr = exp(r-y);
gx = exp(x-y);
g = [gx.*dy(:);gr.'*dy(:)];
linear = false;
hess = @(dw) hess_this(dw,dy,gr,gx);
end
function [h,Jv] = hess_this(dw,dy,gr,gx)
[dr,dx] = get_rx(dw);
p = gr.*gx.*dy;
h = [p.*(dx-dr);dr*sum(p)-dx.'*p];
if nargout>1
Jv = gx.*dx+dr*gr;
end
end
function test_this()
f = logsumexp_special([]);
test_MV2DF(f,randn(5,1));
end
|
github | bsxfan/meta-embeddings-master | scalibration_fh.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/scalibration_fh.m | 1,735 | utf_8 | b9918a8e2a9fa07dfcef33933013931b | function f = scalibration_fh(w)
% This is a factory for a function handle to an MV2DF, which represents
% the vectorization of the s-calibration function. The whole mapping works like
% this, in MATLAB-style pseudocode:
%
% If y = f([x;r;s]), where x,r,s are column vectors of size m, then y
% is a column vector of size m and
%
% y = log( exp(x) + exp(r) ) + log( exp(-s) + 1 )
% - log( exp(x) + exp(-s) ) - log( exp(r) + 1 )
%
% Viewed as a data-dependent calibration transform from x to y, with
% parameters r and s, then:
%
% r: is the log-odds that x is a typical non-target score, given that
% there really is a target.
%
% s: is the log-odds that x is a typical target score, given that
% there really is a non-target.
%
% Ideally r and s should be large negative, in which case this is almost
% an identity transform from x to y, but with saturation at large
% positive and negative values. Increasing r increases the lower
% saturation level. Increasing s decreases the upper saturation level.
if nargin==0
test_this();
return;
end
x = columnJofN_fh(1,3);
r = columnJofN_fh(2,3);
s = columnJofN_fh(3,3);
neg = @(x)-x;
negr = linTrans(r,neg,neg);
negs = linTrans(s,neg,neg);
num1 = logsumexp_fh(2,2,stack([],x,r));
num2 = neglogsigmoid_fh(s);
den1 = neglogsigmoid_fh(negr);
den2 = logsumexp_fh(2,2,stack([],x,negs));
f = sum_of_functions([],[1 1],num1,num2);
f = sum_of_functions([],[1 -1],f,den1);
f = sum_of_functions([],[1 -1],f,den2);
if exist('w','var') && ~isempty(w)
f = f(w);
end
end
function test_this()
n = 3;
x = randn(n,1);
r = randn(n,1);
s = randn(n,1);
X = [x;r;s];
f = scalibration_fh([]);
test_MV2DF(f,X(:));
end
|
github | bsxfan/meta-embeddings-master | scalibration_fragile_fh.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/scalibration_fragile_fh.m | 2,389 | utf_8 | 8eec3ccf6bcd5f130a3d399194acd676 | function f = scalibration_fragile_fh(direction,w)
%
% Don't use this function, it is just for reference. It will break for
% large argument values.
%
% This is a factory for a function handle to an MV2DF, which represents
% the vectorization of the logsumexp function. The whole mapping works like
% this, in MATLAB-style psuedocode:
%
% F: R^(m*n) --> R^n, where y = F(x) is computed thus:
%
% n = length(x)/m
% If direction=1, X = reshape(x,m,n), or
% if direction=1, X = reshape(x,n,m).
% y = log(sum(exp(X),direction))
%
% Inputs:
% m: the number of inputs to each individual logsumexp calculation.
% direction: 1 sums down columns, or 2 sums accross rows.
% w: optional, if ssupplied
%
% Outputs:
% f: a function handle to the MV2DF described above.
%
% see: MV2DF_API_DEFINITION.readme
if nargin==0
test_this();
return;
end
f = vectorized_function([],@(X)F0(X,direction),3,direction);
if exist('w','var') && ~isempty(w)
f = f(w);
end
end
function [y,f1] = F0(X,dr)
if dr==1
x = X(1,:);
p = X(2,:);
q = X(3,:);
else
x = X(:,1);
p = X(:,2);
q = X(:,3);
end
expx = exp(x);
num = (expx-1).*p+1;
den = (expx-1).*q+1;
y = log(num)-log(den);
f1 = @() F1(expx,p,q,num,den,dr);
end
function [J,f2,linear] = F1(expx,p,q,num,den,dr)
linear = false;
if dr==1
J = [expx.*(p-q)./(num.*den);(expx-1)./num;-(expx-1)./den];
else
J = [expx.*(p-q)./(num.*den),(expx-1)./num,-(expx-1)./den];
end
f2 = @(dX) F2(dX,expx,p,q,num,den,dr);
end
function H = F2(dX,expx,p,q,num,den,dr)
d2dx2 = -expx.*(p-q).*(p+q+p.*q.*(expx.^2-1)-1)./(num.^2.*den.^2);
d2dxdp = expx./num.^2;
d2dxdq = -expx./den.^2;
d2dp2 = -(expx-1).^2./num.^2;
d2dq2 = (expx-1).^2./den.^2;
if dr==1
dx = dX(1,:);
dp = dX(2,:);
dq = dX(3,:);
H = [
dx.*d2dx2+dp.*d2dxdp+dq.*d2dxdq; ...
dx.*d2dxdp+dp.*d2dp2; ...
dx.*d2dxdq+dq.*d2dq2...
];
else
dx = dX(:,1);
dp = dX(:,2);
dq = dX(:,3);
H = [
dx.*d2dx2+dp.*d2dxdp+dq.*d2dxdq, ...
dx.*d2dxdp+dp.*d2dp2, ...
dx.*d2dxdq+dq.*d2dq2...
];
end
end
function test_this()
n = 10;
x = randn(1,n);
p = rand(1,n);
q = rand(1,n);
X = [x;p;q];
fprintf('testing dir==1:\n');
f = scalibration_fragile_fh(1);
test_MV2DF(f,X(:));
fprintf('\n\n\ntesting dir==2:\n');
f = scalibration_fragile_fh(2);
X = X';
test_MV2DF(f,X(:));
end
|
github | bsxfan/meta-embeddings-master | scal_simple_fh.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/scalibration/scal_simple_fh.m | 1,903 | utf_8 | b6e3992c13b4424d2129302a3c51424c | function f = scal_simple_fh(w)
% This is a factory for a function handle to an MV2DF, which represents
% the vectorization of the s-calibration function. The whole mapping works like
% this, in MATLAB-style pseudocode:
%
% If y = f([x;r;s]), where r,s are scalar, x is column vector of size m,
% then y is a column vector of size m and
%
% y_i = log( exp(x_i) + exp(r) ) + log( exp(-s) + 1 )
% - log( exp(x_i) + exp(-s) ) - log( exp(r) + 1 )
%
% Viewed as a data-dependent calibration transform from x to y, with
% parameters r and s, then:
%
% r: is the log-odds that x is a typical non-target score, given that
% there really is a target.
%
% s: is the log-odds that x is a typical target score, given that
% there really is a non-target.
%
% Ideally r and s should be large negative, in which case this is almost
% an identity transform from x to y, but with saturation at large
% positive and negative values. Increasing r increases the lower
% saturation level. Increasing s decreases the upper saturation level.
if nargin==0
test_this();
return;
end
[x,rs] = splitvec_fh(-2);
[r,s] = splitvec_fh(-1,rs);
neg = @(t)-t;
negr = linTrans(r,neg,neg);
negs = linTrans(s,neg,neg);
linmap = linTrans([],@(x)map(x),@(y)transmap(y)); %add last element to others
num1 = logsumexp_special(stack([],x,r));
num2 = neglogsigmoid_fh(s);
num = linmap(stack([],num1,num2));
den1 = neglogsigmoid_fh(negr);
den2 = logsumexp_special(stack([],x,negs));
den = linmap(stack([],den2,den1));
f = sum_of_functions([],[1 -1],num,den);
if exist('w','var') && ~isempty(w)
f = f(w);
end
end
function y = map(x)
y = x(1:end-1)+x(end);
end
function x = transmap(y)
x = [y(:);sum(y)];
end
function test_this()
n = 3;
x = randn(n,1);
r = randn(1,1);
s = randn(1,1);
X = [x;r;s];
f = scal_simple_fh([]);
test_MV2DF(f,X(:));
end
|
github | bsxfan/meta-embeddings-master | quality_fuser_v3.m | .m | meta-embeddings-master/code/snapshot_for_anya/matlab/bosaris_toolkit/utility_funcs/Optimization_Toolkit/applications/fusion2class/systems/aside/quality_fuser_v3.m | 1,843 | utf_8 | 1be42594eb854e9b0b4d89daa27c0759 | function [fusion,params] = quality_fuser_v3(w,scores,train_vecs,test_vecs,train_ndx,test_ndx,ddim)
%
% Inputs:
%
% scores: the primary detection scores, for training
% D-by-T matrix of T scores for D input systems
%
% train_vecs: K1-by-M matrix, one column-vector for each of M training
% segemnts
%
% test_vecs: K2-by-N matrix, one column-vector for each of N training
% segemnts
%
% train_ndx: 1-by-T index where train_ndx(t) is the index into train_vecs
% for trial t.
%
% test_ndx: 1-by-T index where test_ndx(t) is the index into test_vecs
% for trial t.
% ddim: dimension of subspace for quality distandce calculation,
% where ddim <= min(K1,K2)
%
% Outputs:
%
if nargin==0
test_this();
return;
end
% Check data dimensions
[K1,M] = size(train_vecs);
[K2,N] = size(test_vecs);
assert(ddim<min(K1,K2));
[D,T] = size(scores);
assert(T == length(train_ndx));
assert(T == length(test_ndx));
assert(max(train_ndx)<=M);
assert(max(test_ndx)<=N);
% Create building blocks
[linfusion,params1] = linear_fuser([],scores);
[quality,params2] = sigmoid_log_sumsqdist(params1.tail,train_vecs,test_vecs,train_ndx,test_ndx,ddim);
params.get_w0 = @(ssat) [params1.get_w0(); params2.get_w0(ssat)];
params.tail = params2.tail;
% Assemble building blocks
% modulate linear fusion with quality
fusion = dottimes_of_functions([],quality,linfusion);
if ~isempty(w)
fusion = fusion(w);
end
end
function test_this()
D = 2;
N = 5;
T = 3;
Q = 4;
ndx = ceil(T.*rand(1,N));
scores = randn(D,N);
train = randn(Q,T);
test = randn(Q,T);
ddim = 2;
ssat = 0.99;
[fusion,params] = quality_fuser_v3([],scores,train,test,ndx,ndx,ddim);
w0 = params.get_w0(ssat);
test_MV2DF(fusion,w0);
quality_fuser_v3(w0,scores,train,test,ndx,ndx,ddim),
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.