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 | durgeshsamariya/Coursera_MachineLearning_Course-master | loadubjson.m | .m | Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/lib/jsonlab/loadubjson.m | 15,574 | utf_8 | 5974e78e71b81b1e0f76123784b951a4 | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | saveubjson.m | .m | Coursera_MachineLearning_Course-master/Week 5/machine-learning-ex4/ex4/lib/jsonlab/saveubjson.m | 16,123 | utf_8 | 61d4f51010aedbf97753396f5d2d9ec0 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | submit.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/submit.m | 1,605 | utf_8 | 9b63d386e9bd7bcca66b1a3d2fa37579 | function submit()
addpath('./lib');
conf.assignmentSlug = 'logistic-regression';
conf.itemName = 'Logistic Regression';
conf.partArrays = { ...
{ ...
'1', ...
{ 'sigmoid.m' }, ...
'Sigmoid Function', ...
}, ...
{ ...
'2', ...
{ 'costFunction.m' }, ...
'Logistic Regression Cost', ...
}, ...
{ ...
'3', ...
{ 'costFunction.m' }, ...
'Logistic Regression Gradient', ...
}, ...
{ ...
'4', ...
{ 'predict.m' }, ...
'Predict', ...
}, ...
{ ...
'5', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Cost', ...
}, ...
{ ...
'6', ...
{ 'costFunctionReg.m' }, ...
'Regularized Logistic Regression Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
y = sin(X(:,1) + X(:,2)) > 0;
if partId == '1'
out = sprintf('%0.5f ', sigmoid(X));
elseif partId == '2'
out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y));
elseif partId == '3'
[cost, grad] = costFunction([0.25 0.5 -0.5]', X, y);
out = sprintf('%0.5f ', grad);
elseif partId == '4'
out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X));
elseif partId == '5'
out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1));
elseif partId == '6'
[cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1);
out = sprintf('%0.5f ', grad);
end
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | submitWithConfiguration.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/lib/submitWithConfiguration.m | 5,562 | utf_8 | 4ac719ea6570ac228ea6c7a9c919e3f5 | function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | savejson.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/lib/jsonlab/savejson.m | 17,462 | utf_8 | 861b534fc35ffe982b53ca3ca83143bf | function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | loadjson.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/lib/jsonlab/loadjson.m | 18,732 | ibm852 | ab98cf173af2d50bbe8da4d6db252a20 | function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | loadubjson.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/lib/jsonlab/loadubjson.m | 15,574 | utf_8 | 5974e78e71b81b1e0f76123784b951a4 | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | saveubjson.m | .m | Coursera_MachineLearning_Course-master/Week 3/machine-learning-ex2/ex2/lib/jsonlab/saveubjson.m | 16,123 | utf_8 | 61d4f51010aedbf97753396f5d2d9ec0 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | submit.m | .m | Coursera_MachineLearning_Course-master/Week 4/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 | durgeshsamariya/Coursera_MachineLearning_Course-master | submitWithConfiguration.m | .m | Coursera_MachineLearning_Course-master/Week 4/machine-learning-ex3/ex3/lib/submitWithConfiguration.m | 5,562 | utf_8 | 4ac719ea6570ac228ea6c7a9c919e3f5 | function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
parts = parts(conf);
fprintf('== Submitting solutions | %s...\n', conf.itemName);
tokenFile = 'token.mat';
if exist(tokenFile, 'file')
load(tokenFile);
[email token] = promptToken(email, token, tokenFile);
else
[email token] = promptToken('', '', tokenFile);
end
if isempty(token)
fprintf('!! Submission Cancelled\n');
return
end
try
response = submitParts(conf, email, token, parts);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(parts, response);
save(tokenFile, 'email', 'token');
end
end
function [email token] = promptToken(email, existingToken, tokenFile)
if (~isempty(email) && ~isempty(existingToken))
prompt = sprintf( ...
'Use token from last successful submission (%s)? (Y/n): ', ...
email);
reenter = input(prompt, 's');
if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y')
token = existingToken;
return;
else
delete(tokenFile);
end
end
email = input('Login (email address): ', 's');
token = input('Token: ', 's');
end
function isValid = isValidPartOptionIndex(partOptions, i)
isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions));
end
function response = submitParts(conf, email, token, parts)
body = makePostBody(conf, email, token, parts);
submissionUrl = submissionUrl();
responseBody = getResponse(submissionUrl, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submissionUrl = submissionUrl()
submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | savejson.m | .m | Coursera_MachineLearning_Course-master/Week 4/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 | durgeshsamariya/Coursera_MachineLearning_Course-master | loadjson.m | .m | Coursera_MachineLearning_Course-master/Week 4/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 | durgeshsamariya/Coursera_MachineLearning_Course-master | loadubjson.m | .m | Coursera_MachineLearning_Course-master/Week 4/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 | durgeshsamariya/Coursera_MachineLearning_Course-master | saveubjson.m | .m | Coursera_MachineLearning_Course-master/Week 4/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 | durgeshsamariya/Coursera_MachineLearning_Course-master | submit.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/submit.m | 2,135 | utf_8 | eebb8c0a1db5a4df20b4c858603efad6 | function submit()
addpath('./lib');
conf.assignmentSlug = 'anomaly-detection-and-recommender-systems';
conf.itemName = 'Anomaly Detection and Recommender Systems';
conf.partArrays = { ...
{ ...
'1', ...
{ 'estimateGaussian.m' }, ...
'Estimate Gaussian Parameters', ...
}, ...
{ ...
'2', ...
{ 'selectThreshold.m' }, ...
'Select Threshold', ...
}, ...
{ ...
'3', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Cost', ...
}, ...
{ ...
'4', ...
{ 'cofiCostFunc.m' }, ...
'Collaborative Filtering Gradient', ...
}, ...
{ ...
'5', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Cost', ...
}, ...
{ ...
'6', ...
{ 'cofiCostFunc.m' }, ...
'Regularized Gradient', ...
}, ...
};
conf.output = @output;
submitWithConfiguration(conf);
end
function out = output(partId, auxstring)
% Random Test Cases
n_u = 3; n_m = 4; n = 5;
X = reshape(sin(1:n_m*n), n_m, n);
Theta = reshape(cos(1:n_u*n), n_u, n);
Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u);
R = Y > 0.5;
pval = [abs(Y(:)) ; 0.001; 1];
Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed
yval = [R(:) ; 1; 0];
params = [X(:); Theta(:)];
if partId == '1'
[mu sigma2] = estimateGaussian(X);
out = sprintf('%0.5f ', [mu(:); sigma2(:)]);
elseif partId == '2'
[bestEpsilon bestF1] = selectThreshold(yval, pval);
out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]);
elseif partId == '3'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', J(:));
elseif partId == '4'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 0);
out = sprintf('%0.5f ', grad(:));
elseif partId == '5'
[J] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', J(:));
elseif partId == '6'
[J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ...
n, 1.5);
out = sprintf('%0.5f ', grad(:));
end
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | submitWithConfiguration.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/lib/submitWithConfiguration.m | 5,569 | utf_8 | cc10d7a55178eb991c495a2b638947fd | function submitWithConfiguration(conf)
addpath('./lib/jsonlab');
partss = 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, partss);
catch
e = lasterror();
fprintf('\n!! Submission failed: %s\n', e.message);
fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ...
e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line);
fprintf('\nPlease correct your code and resubmit.\n');
return
end
if isfield(response, 'errorMessage')
fprintf('!! Submission failed: %s\n', response.errorMessage);
elseif isfield(response, 'errorCode')
fprintf('!! Submission failed: %s\n', response.message);
else
showFeedback(partss, 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);
submission_Url = submissionUrl();
responseBody = getResponse(submission_Url, body);
jsonResponse = validateResponse(responseBody);
response = loadjson(jsonResponse);
end
function body = makePostBody(conf, email, token, parts)
bodyStruct.assignmentSlug = conf.assignmentSlug;
bodyStruct.submitterEmail = email;
bodyStruct.secret = token;
bodyStruct.parts = makePartsStruct(conf, parts);
opt.Compact = 1;
body = savejson('', bodyStruct, opt);
end
function partsStruct = makePartsStruct(conf, parts)
for part = parts
partId = part{:}.id;
fieldName = makeValidFieldName(partId);
outputStruct.output = conf.output(partId);
partsStruct.(fieldName) = outputStruct;
end
end
function [parts] = parts(conf)
parts = {};
for partArray = conf.partArrays
part.id = partArray{:}{1};
part.sourceFiles = partArray{:}{2};
part.name = partArray{:}{3};
parts{end + 1} = part;
end
end
function showFeedback(parts, response)
fprintf('== \n');
fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback');
fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------');
for part = parts
score = '';
partFeedback = '';
partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id));
partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id));
score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore);
fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback);
end
evaluation = response.evaluation;
totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore);
fprintf('== --------------------------------\n');
fprintf('== %43s | %9s | %-s\n', '', totalScore, '');
fprintf('== \n');
end
% use urlread or curl to send submit results to the grader and get a response
function response = getResponse(url, body)
% try using urlread() and a secure connection
params = {'jsonBody', body};
[response, success] = urlread(url, 'post', params);
if (success == 0)
% urlread didn't work, try curl & the peer certificate patch
if ispc
% testing note: use 'jsonBody =' for a test case
json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url);
else
% it's linux/OS X, so use the other form
json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url);
end
% get the response body for the peer certificate patch method
[code, response] = system(json_command);
% test the success code
if (code ~= 0)
fprintf('[error] submission with curl() was not successful\n');
end
end
end
% validate the grader's response
function response = validateResponse(resp)
% test if the response is json or an HTML page
isJson = length(resp) > 0 && resp(1) == '{';
isHtml = findstr(lower(resp), '<html');
if (isJson)
response = resp;
elseif (isHtml)
% the response is html, so it's probably an error message
printHTMLContents(resp);
error('Grader response is an HTML message');
else
error('Grader sent no response');
end
end
% parse a HTML response and print it's contents
function printHTMLContents(response)
strippedResponse = regexprep(response, '<[^>]+>', ' ');
strippedResponse = regexprep(strippedResponse, '[\t ]+', ' ');
fprintf(strippedResponse);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Service configuration
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function submission_Url = submissionUrl()
submission_Url = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1';
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | savejson.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/lib/jsonlab/savejson.m | 17,462 | utf_8 | 861b534fc35ffe982b53ca3ca83143bf | function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
else
fid = fopen(opt.FileName, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
else
txt=mat2json(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2json(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
nl=ws.newline;
if(len>1)
if(~isempty(name))
txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name='';
else
txt=sprintf('%s[%s',padding0,nl);
end
elseif(len==0)
if(~isempty(name))
txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name='';
else
txt=sprintf('%s[]',padding0);
end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:}));
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1));
nl=ws.newline;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding0,nl); end
end
for j=1:dim(2)
if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl);
else
txt=sprintf('%s%s{%s',txt,padding1,nl);
end
if(~isempty(names))
for e=1:length(names)
txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:}));
if(e<length(names)) txt=sprintf('%s%s',txt,','); end
txt=sprintf('%s%s',txt,nl);
end
end
txt=sprintf('%s%s}',txt,padding1);
if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end
if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end
%%-------------------------------------------------------------------------
function txt=str2json(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(~isempty(name))
if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end
else
if(len>1) txt=sprintf('%s[%s',padding1,nl); end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
if(isoct)
val=regexprep(item(e,:),'\\','\\');
val=regexprep(val,'"','\"');
val=regexprep(val,'^"','\"');
else
val=regexprep(item(e,:),'\\','\\\\');
val=regexprep(val,'"','\\"');
val=regexprep(val,'^"','\\"');
end
val=escapejsonstring(val);
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name)) obj=['"',val,'"']; end
txt=sprintf('%s%s%s%s',txt,padding1,obj);
else
txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']);
end
if(e==len) sep=''; end
txt=sprintf('%s%s',txt,sep);
end
if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matdata2json(mat,level,varargin)
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
tab=ws.tab;
nl=ws.newline;
if(size(mat,1)==1)
pre='';
post='';
level=level-1;
else
pre=sprintf('[%s',nl);
post=sprintf('%s%s]',nl,repmat(tab,1,level-1));
end
if(isempty(mat))
txt='null';
return;
end
floatformat=jsonopt('FloatFormat','%.10g',varargin{:});
%if(numel(mat)>1)
formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]];
%else
% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]];
%end
if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1)
formatstr=[repmat(tab,1,level) formatstr];
end
txt=sprintf(formatstr,mat');
txt(end-length(nl):end)=[];
if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1)
txt=regexprep(txt,'1','true');
txt=regexprep(txt,'0','false');
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],\n['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
txt=[pre txt post];
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function newstr=escapejsonstring(str)
newstr=str;
isoct=exist('OCTAVE_VERSION','builtin');
if(isoct)
vv=sscanf(OCTAVE_VERSION,'%f');
if(vv(1)>=3.8) isoct=0; end
end
if(isoct)
escapechars={'\a','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},escapechars{i});
end
else
escapechars={'\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | loadjson.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/lib/jsonlab/loadjson.m | 18,732 | ibm852 | ab98cf173af2d50bbe8da4d6db252a20 | function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=data(j).x0x5F_ArraySize_;
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=jsonopt('progressbar_',-1,varargin{:});
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str); switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos), keyboard
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct
currstr=inStr(pos:end);
numstr=0;
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num, one] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
pbar=jsonopt('progressbar_',-1,varargin{:});
if(pbar>0)
waitbar(pos/len,pbar,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | loadubjson.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/lib/jsonlab/loadubjson.m | 15,574 | utf_8 | 5974e78e71b81b1e0f76123784b951a4 | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
fileendian=upper(jsonopt('IntEndian','B',opt));
[os,maxelem,systemendian]=computer;
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(~isempty(data))
if(isstruct(data)) % data can be a struct array
data=jstruct2array(data);
elseif(iscell(data))
data=jcell2array(data);
end
end
%%
function newdata=parse_collection(id,data,obj)
if(jsoncount>0 && exist('data','var'))
if(~iscell(data))
newdata=cell(1);
newdata{1}=data;
data=newdata;
end
end
%%
function newdata=jcell2array(data)
len=length(data);
newdata=data;
for i=1:len
if(isstruct(data{i}))
newdata{i}=jstruct2array(data{i});
elseif(iscell(data{i}))
newdata{i}=jcell2array(data{i});
end
end
%%-------------------------------------------------------------------------
function newdata=jstruct2array(data)
fn=fieldnames(data);
newdata=data;
len=length(data);
for i=1:length(fn) % depth-first
for j=1:len
if(isstruct(getfield(data(j),fn{i})))
newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i})));
end
end
end
if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn)))
newdata=cell(len,1);
for j=1:len
ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_);
iscpx=0;
if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn)))
if(data(j).x0x5F_ArrayIsComplex_)
iscpx=1;
end
end
if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn)))
if(data(j).x0x5F_ArrayIsSparse_)
if(~isempty(strmatch('x0x5F_ArraySize_',fn)))
dim=double(data(j).x0x5F_ArraySize_);
if(iscpx && size(ndata,2)==4-any(dim==1))
ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end));
end
if isempty(ndata)
% All-zeros sparse
ndata=sparse(dim(1),prod(dim(2:end)));
elseif dim(1)==1
% Sparse row vector
ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end)));
elseif dim(2)==1
% Sparse column vector
ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end)));
else
% Generic sparse array.
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end)));
end
else
if(iscpx && size(ndata,2)==4)
ndata(:,3)=complex(ndata(:,3),ndata(:,4));
end
ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3));
end
end
elseif(~isempty(strmatch('x0x5F_ArraySize_',fn)))
if(iscpx && size(ndata,2)==2)
ndata=complex(ndata(:,1),ndata(:,2));
end
ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_);
end
newdata{j}=ndata;
end
if(len==1)
newdata=newdata{1};
end
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
eval( sprintf( 'object.%s = val;', valid_field(str) ) );
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
id=strfind('iUIlLdD',type);
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ndims(object)==2)
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr esc index_esc len_esc
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr len isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
if(isoct)
newdata=int8(datastr);
else
newdata=uint8(datastr);
end
if(id<=5 && fileendian~=systemendian)
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
true = 1; false = 0;
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
if isstruct(val)
if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact')))
val=jstruct2array(val);
end
elseif isempty(val)
val = struct;
end
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos)) return; end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos e1l e1r maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r)) e1r=bpos(pos); end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l)) e1l=bpos(pos); end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | durgeshsamariya/Coursera_MachineLearning_Course-master | saveubjson.m | .m | Coursera_MachineLearning_Course-master/Week 9/machine-learning-ex8/ex8/lib/jsonlab/saveubjson.m | 16,123 | utf_8 | 61d4f51010aedbf97753396f5d2d9ec0 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(nargin==1)
varname=inputname(1);
obj=rootname;
if(isempty(varname))
varname='root';
end
rootname=varname;
else
varname=inputname(2);
end
if(length(varargin)==1 && ischar(varargin{1}))
opt=struct('FileName',varargin{1});
else
opt=varargin2struct(varargin{:});
end
opt.IsOctave=exist('OCTAVE_VERSION','builtin');
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
if(~isempty(jsonopt('FileName','',opt)))
fid = fopen(opt.FileName, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item); % let's handle 1D cell first
if(len>1)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[S_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
for j=1:dim(2)
if(dim(1)>1) txt=[txt '[']; end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1)
txt=[txt S_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},getfield(item(i,j),...
names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1) txt=[txt ']']; end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end
else
if(len>1) txt='['; end
end
isoct=jsonopt('IsOctave',0,varargin{:});
for e=1:len
val=item(e,:);
if(len==1)
obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name)) obj=['',S_(val),'']; end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1) txt=[txt ']']; end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
isempty(item) || jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[S_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[S_(checkname(name,varargin{:})) numtxt];
else
txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,S_('_ArrayIsComplex_'),'T'];
end
txt=[txt,S_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,S_('_ArrayIsComplex_'),'T'];
txt=[txt,S_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
if(size(mat,1)==1)
level=level-1;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(find(id)))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(find(id));
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos)) return; end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | Hannes333/Computer-Aided-Manufacturing-Programm-for-2.5D-Laser-Ablation-Version-2.0-master | F00_stlread.m | .m | Computer-Aided-Manufacturing-Programm-for-2.5D-Laser-Ablation-Version-2.0-master/F00_stlread.m | 5,235 | utf_8 | d6f780ddf573a34879cf3fe24bd1308f | function varargout = stlread(file)
% STLREAD imports geometry from an STL file into MATLAB.
% FV = STLREAD(FILENAME) imports triangular faces from the ASCII or binary
% STL file idicated by FILENAME, and returns the patch struct FV, with fields
% 'faces' and 'vertices'.
%
% [F,V] = STLREAD(FILENAME) returns the faces F and vertices V separately.
%
% [F,V,N] = STLREAD(FILENAME) also returns the face normal vectors.
%
% The faces and vertices are arranged in the format used by the PATCH plot
% object.
if ~exist(file,'file')
error(['File ''%s'' not found. If the file is not on MATLAB''s path' ...
', be sure to specify the full path to the file.'], file);
end
fid = fopen(file,'r');
if ~isempty(ferror(fid))
error(lasterror); %#ok
end
M = fread(fid,inf,'uint8=>uint8');
fclose(fid);
[f,v,n] = stlbinary(M);
%if( isbinary(M) ) % This may not be a reliable test
% [f,v,n] = stlbinary(M);
%else
% [f,v,n] = stlascii(M);
%end
varargout = cell(1,nargout);
switch nargout
case 2
varargout{1} = f;
varargout{2} = v;
case 3
varargout{1} = f;
varargout{2} = v;
varargout{3} = n;
otherwise
varargout{1} = struct('faces',f,'vertices',v);
end
end
function [F,V,N] = stlbinary(M)
F = [];
V = [];
N = [];
if length(M) < 84
error('MATLAB:stlread:incorrectFormat', ...
'Incomplete header information in binary STL file.');
end
% Bytes 81-84 are an unsigned 32-bit integer specifying the number of faces
% that follow.
numFaces = typecast(M(81:84),'uint32');
%numFaces = double(numFaces);
if numFaces == 0
warning('MATLAB:stlread:nodata','No data in STL file.');
return
end
T = M(85:end);
F = NaN(numFaces,3);
V = NaN(3*numFaces,3);
N = NaN(numFaces,3);
bar = waitbar(0,'Stl-Datei wird importiert...'); %Ladebalken erstellen
numRead = 0;
fInd = 0;
while numRead < numFaces
% Each facet is 50 bytes
% - Three single precision values specifying the face normal vector
% - Three single precision values specifying the first vertex (XYZ)
% - Three single precision values specifying the second vertex (XYZ)
% - Three single precision values specifying the third vertex (XYZ)
% - Two unused bytes
i1 = 50 * numRead + 1;
i2 = i1 + 50 - 1;
facet = T(i1:i2)';
n = typecast(facet(1:12),'single');
v1 = typecast(facet(13:24),'single');
v2 = typecast(facet(25:36),'single');
v3 = typecast(facet(37:48),'single');
n = double(n);
if isequal(n,[0 0 0]) %Eingelesener Normalvektor ist Null (noch nicht bestimmt)
%n=cross(v2-v1,v3-v1); %Normalenvektor wird mit Kreuzprodukt berechnet
a=v2-v1;
b=v3-v1;
n=[a(2)*b(3)-a(3)*b(2),a(3)*b(1)-a(1)*b(3),a(1)*b(2)-a(2)*b(1)];
end
if n==[0 0 0] %berechneter Normalenvektor ist immer noch Null (also Dreieck fehlerhaft)
% STL-Objekt hat fehlerhafte Dreiecke (Zwei Kanten liegen
% aufeinander) Solch fehlerhaften Dreiecke werden verworfen
warning('Fehlerhaftes Dreieck verworfen');
else
% Figure out where to fit these new vertices, and the face, in the
% larger F and V collections.
fInd = fInd + 1;
vInd1 = 3 * (fInd - 1) + 1;
vInd2 = vInd1 + 3 - 1;
v = double([v1; v2; v3]);
V(vInd1:vInd2,:) = v;
F(fInd,:) = vInd1:vInd2;
n=n/norm(n); %Berechneter Normalenvektor wird normiert
N(fInd,:)= n; %Normalenvektor wird im Array N gespeichert
end
numRead = numRead + 1;
if mod(numRead,round(numFaces/50))==0 %Ladebalken nicht bei jedem Schleifendurchlauf aktualisieren (Rechenleistung sparen)
waitbar(numRead/double(numFaces)) %Aktualisierung Ladebalken
end
end
%close(bar); %Ladebalken schliessen
delete(bar);
F(fInd+1:end,:)=[]; %remove unfilled entries
N(fInd+1:end,:)=[]; %remove unfilled entries
V(fInd*3+1:end,:)=[]; %remove unfilled entries
end
function [F,V,N] = stlascii(M)
warning('MATLAB:stlread:ascii','ASCII STL files currently not supported.');
F = [];
V = [];
N = [];
end
% TODO: Change the testing criteria! Some binary STL files still begin with
% 'solid'.
function tf = isbinary(A)
% ISBINARY uses the first line of an STL file to identify its format.
if isempty(A) || length(A) < 5
error('MATLAB:stlread:incorrectFormat', ...
'File does not appear to be an ASCII or binary STL file.');
end
if strcmpi('solid',char(A(1:5)'))
tf = false; % ASCII
else
tf = true; % Binary
end
end |
github | Hannes333/Computer-Aided-Manufacturing-Programm-for-2.5D-Laser-Ablation-Version-2.0-master | F16_Intersections.m | .m | Computer-Aided-Manufacturing-Programm-for-2.5D-Laser-Ablation-Version-2.0-master/F16_Intersections.m | 11,787 | utf_8 | 52d726542cc35a2287fe572fc23a47bc | function [x0,y0,iout,jout] = F16_Intersections(x1,y1,x2,y2,robust)
%INTERSECTIONS Intersections of curves.
% Computes the (x,y) locations where two curves intersect. The curves
% can be broken with NaNs or have vertical segments.
%
% Example:
% [X0,Y0] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% where X1 and Y1 are equal-length vectors of at least two points and
% represent curve 1. Similarly, X2 and Y2 represent curve 2.
% X0 and Y0 are column vectors containing the points at which the two
% curves intersect.
%
% ROBUST (optional) set to 1 or true means to use a slight variation of the
% algorithm that might return duplicates of some intersection points, and
% then remove those duplicates. The default is true, but since the
% algorithm is slightly slower you can set it to false if you know that
% your curves don't intersect at any segment boundaries. Also, the robust
% version properly handles parallel and overlapping segments.
%
% The algorithm can return two additional vectors that indicate which
% segment pairs contain intersections and where they are:
%
% [X0,Y0,I,J] = intersections(X1,Y1,X2,Y2,ROBUST);
%
% For each element of the vector I, I(k) = (segment number of (X1,Y1)) +
% (how far along this segment the intersection is). For example, if I(k) =
% 45.25 then the intersection lies a quarter of the way between the line
% segment connecting (X1(45),Y1(45)) and (X1(46),Y1(46)). Similarly for
% the vector J and the segments in (X2,Y2).
%
% You can also get intersections of a curve with itself. Simply pass in
% only one curve, i.e.,
%
% [X0,Y0] = intersections(X1,Y1,ROBUST);
%
% where, as before, ROBUST is optional.
% Version: 2.0, 25 May 2017
% Author: Douglas M. Schwarz
% Email: dmschwarz=ieee*org, dmschwarz=urgrad*rochester*edu
% Real_email = regexprep(Email,{'=','*'},{'@','.'})
% Theory of operation:
%
% Given two line segments, L1 and L2,
%
% L1 endpoints: (x1(1),y1(1)) and (x1(2),y1(2))
% L2 endpoints: (x2(1),y2(1)) and (x2(2),y2(2))
%
% we can write four equations with four unknowns and then solve them. The
% four unknowns are t1, t2, x0 and y0, where (x0,y0) is the intersection of
% L1 and L2, t1 is the distance from the starting point of L1 to the
% intersection relative to the length of L1 and t2 is the distance from the
% starting point of L2 to the intersection relative to the length of L2.
%
% So, the four equations are
%
% (x1(2) - x1(1))*t1 = x0 - x1(1)
% (x2(2) - x2(1))*t2 = x0 - x2(1)
% (y1(2) - y1(1))*t1 = y0 - y1(1)
% (y2(2) - y2(1))*t2 = y0 - y2(1)
%
% Rearranging and writing in matrix form,
%
% [x1(2)-x1(1) 0 -1 0; [t1; [-x1(1);
% 0 x2(2)-x2(1) -1 0; * t2; = -x2(1);
% y1(2)-y1(1) 0 0 -1; x0; -y1(1);
% 0 y2(2)-y2(1) 0 -1] y0] -y2(1)]
%
% Let's call that A*T = B. We can solve for T with T = A\B.
%
% Once we have our solution we just have to look at t1 and t2 to determine
% whether L1 and L2 intersect. If 0 <= t1 < 1 and 0 <= t2 < 1 then the two
% line segments cross and we can include (x0,y0) in the output.
%
% In principle, we have to perform this computation on every pair of line
% segments in the input data. This can be quite a large number of pairs so
% we will reduce it by doing a simple preliminary check to eliminate line
% segment pairs that could not possibly cross. The check is to look at the
% smallest enclosing rectangles (with sides parallel to the axes) for each
% line segment pair and see if they overlap. If they do then we have to
% compute t1 and t2 (via the A\B computation) to see if the line segments
% cross, but if they don't then the line segments cannot cross. In a
% typical application, this technique will eliminate most of the potential
% line segment pairs.
% Input checks.
if verLessThan('matlab','7.13')
error(nargchk(2,5,nargin)) %#ok<NCHKN>
else
narginchk(2,5)
end
% Adjustments based on number of arguments.
switch nargin
case 2
robust = true;
x2 = x1;
y2 = y1;
self_intersect = true;
case 3
robust = x2;
x2 = x1;
y2 = y1;
self_intersect = true;
case 4
robust = true;
self_intersect = false;
case 5
self_intersect = false;
end
% x1 and y1 must be vectors with same number of points (at least 2).
if sum(size(x1) > 1) ~= 1 || sum(size(y1) > 1) ~= 1 || ...
length(x1) ~= length(y1)
error('X1 and Y1 must be equal-length vectors of at least 2 points.')
end
% x2 and y2 must be vectors with same number of points (at least 2).
if sum(size(x2) > 1) ~= 1 || sum(size(y2) > 1) ~= 1 || ...
length(x2) ~= length(y2)
error('X2 and Y2 must be equal-length vectors of at least 2 points.')
end
% Force all inputs to be column vectors.
x1 = x1(:);
y1 = y1(:);
x2 = x2(:);
y2 = y2(:);
% Compute number of line segments in each curve and some differences we'll
% need later.
n1 = length(x1) - 1;
n2 = length(x2) - 1;
xy1 = [x1 y1];
xy2 = [x2 y2];
dxy1 = diff(xy1);
dxy2 = diff(xy2);
% Determine the combinations of i and j where the rectangle enclosing the
% i'th line segment of curve 1 overlaps with the rectangle enclosing the
% j'th line segment of curve 2.
% Original method that works in old MATLAB versions, but is slower than
% using binary singleton expansion (explicit or implicit).
% [i,j] = find( ...
% repmat(mvmin(x1),1,n2) <= repmat(mvmax(x2).',n1,1) & ...
% repmat(mvmax(x1),1,n2) >= repmat(mvmin(x2).',n1,1) & ...
% repmat(mvmin(y1),1,n2) <= repmat(mvmax(y2).',n1,1) & ...
% repmat(mvmax(y1),1,n2) >= repmat(mvmin(y2).',n1,1));
% Select an algorithm based on MATLAB version and number of line
% segments in each curve. We want to avoid forming large matrices for
% large numbers of line segments. If the matrices are not too large,
% choose the best method available for the MATLAB version.
if n1 > 1000 || n2 > 1000 || verLessThan('matlab','7.4')
% Determine which curve has the most line segments.
if n1 >= n2
% Curve 1 has more segments, loop over segments of curve 2.
ijc = cell(1,n2);
min_x1 = mvmin(x1);
max_x1 = mvmax(x1);
min_y1 = mvmin(y1);
max_y1 = mvmax(y1);
for k = 1:n2
k1 = k + 1;
ijc{k} = find( ...
min_x1 <= max(x2(k),x2(k1)) & max_x1 >= min(x2(k),x2(k1)) & ...
min_y1 <= max(y2(k),y2(k1)) & max_y1 >= min(y2(k),y2(k1)));
ijc{k}(:,2) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
else
% Curve 2 has more segments, loop over segments of curve 1.
ijc = cell(1,n1);
min_x2 = mvmin(x2);
max_x2 = mvmax(x2);
min_y2 = mvmin(y2);
max_y2 = mvmax(y2);
for k = 1:n1
k1 = k + 1;
ijc{k}(:,2) = find( ...
min_x2 <= max(x1(k),x1(k1)) & max_x2 >= min(x1(k),x1(k1)) & ...
min_y2 <= max(y1(k),y1(k1)) & max_y2 >= min(y1(k),y1(k1)));
ijc{k}(:,1) = k;
end
ij = vertcat(ijc{:});
i = ij(:,1);
j = ij(:,2);
end
elseif verLessThan('matlab','9.1')
% Use bsxfun.
[i,j] = find( ...
bsxfun(@le,mvmin(x1),mvmax(x2).') & ...
bsxfun(@ge,mvmax(x1),mvmin(x2).') & ...
bsxfun(@le,mvmin(y1),mvmax(y2).') & ...
bsxfun(@ge,mvmax(y1),mvmin(y2).'));
else
% Use implicit expansion.
[i,j] = find( ...
mvmin(x1) <= mvmax(x2).' & mvmax(x1) >= mvmin(x2).' & ...
mvmin(y1) <= mvmax(y2).' & mvmax(y1) >= mvmin(y2).');
end
% Find segments pairs which have at least one vertex = NaN and remove them.
% This line is a fast way of finding such segment pairs. We take
% advantage of the fact that NaNs propagate through calculations, in
% particular subtraction (in the calculation of dxy1 and dxy2, which we
% need anyway) and addition.
% At the same time we can remove redundant combinations of i and j in the
% case of finding intersections of a line with itself.
if self_intersect
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2)) | j <= i + 1;
else
remove = isnan(sum(dxy1(i,:) + dxy2(j,:),2));
end
i(remove) = [];
j(remove) = [];
% Initialize matrices. We'll put the T's and B's in matrices and use them
% one column at a time. AA is a 3-D extension of A where we'll use one
% plane at a time.
n = length(i);
T = zeros(4,n);
AA = zeros(4,4,n);
AA([1 2],3,:) = -1;
AA([3 4],4,:) = -1;
AA([1 3],1,:) = dxy1(i,:).';
AA([2 4],2,:) = dxy2(j,:).';
B = -[x1(i) x2(j) y1(i) y2(j)].';
% Loop through possibilities. Trap singularity warning and then use
% lastwarn to see if that plane of AA is near singular. Process any such
% segment pairs to determine if they are colinear (overlap) or merely
% parallel. That test consists of checking to see if one of the endpoints
% of the curve 2 segment lies on the curve 1 segment. This is done by
% checking the cross product
%
% (x1(2),y1(2)) - (x1(1),y1(1)) x (x2(2),y2(2)) - (x1(1),y1(1)).
%
% If this is close to zero then the segments overlap.
% If the robust option is false then we assume no two segment pairs are
% parallel and just go ahead and do the computation. If A is ever singular
% a warning will appear. This is faster and obviously you should use it
% only when you know you will never have overlapping or parallel segment
% pairs.
if robust
overlap = false(n,1);
warning_state = warning('off','MATLAB:singularMatrix');
% Use try-catch to guarantee original warning state is restored.
try
lastwarn('')
for k = 1:n
T(:,k) = AA(:,:,k)\B(:,k);
[unused,last_warn] = lastwarn; %#ok<ASGLU>
lastwarn('')
if strcmp(last_warn,'MATLAB:singularMatrix')
% Force in_range(k) to be false.
T(1,k) = NaN;
% Determine if these segments overlap or are just parallel.
overlap(k) = rcond([dxy1(i(k),:);xy2(j(k),:) - xy1(i(k),:)]) < eps;
end
end
warning(warning_state)
catch err
warning(warning_state)
rethrow(err)
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) <= 1 & T(2,:) <= 1).';
% For overlapping segment pairs the algorithm will return an
% intersection point that is at the center of the overlapping region.
if any(overlap)
ia = i(overlap);
ja = j(overlap);
% set x0 and y0 to middle of overlapping region.
T(3,overlap) = (max(min(x1(ia),x1(ia+1)),min(x2(ja),x2(ja+1))) + ...
min(max(x1(ia),x1(ia+1)),max(x2(ja),x2(ja+1)))).'/2;
T(4,overlap) = (max(min(y1(ia),y1(ia+1)),min(y2(ja),y2(ja+1))) + ...
min(max(y1(ia),y1(ia+1)),max(y2(ja),y2(ja+1)))).'/2;
selected = in_range | overlap;
else
selected = in_range;
end
xy0 = T(3:4,selected).';
% Remove duplicate intersection points.
[xy0,index] = unique(xy0,'rows');
x0 = xy0(:,1);
y0 = xy0(:,2);
% Compute how far along each line segment the intersections are.
if nargout > 2
sel_index = find(selected);
sel = sel_index(index);
iout = i(sel) + T(1,sel).';
jout = j(sel) + T(2,sel).';
end
else % non-robust option
for k = 1:n
[L,U] = lu(AA(:,:,k));
T(:,k) = U\(L\B(:,k));
end
% Find where t1 and t2 are between 0 and 1 and return the corresponding
% x0 and y0 values.
in_range = (T(1,:) >= 0 & T(2,:) >= 0 & T(1,:) < 1 & T(2,:) < 1).';
x0 = T(3,in_range).';
y0 = T(4,in_range).';
% Compute how far along each line segment the intersections are.
if nargout > 2
iout = i(in_range) + T(1,in_range).';
jout = j(in_range) + T(2,in_range).';
end
end
% Plot the results (useful for debugging).
% plot(x1,y1,x2,y2,x0,y0,'ok');
function y = mvmin(x)
% Faster implementation of movmin(x,k) when k = 1.
y = min(x(1:end-1),x(2:end));
function y = mvmax(x)
% Faster implementation of movmax(x,k) when k = 1.
y = max(x(1:end-1),x(2:end));
|
github | mohammadzainabbas/Digital-Communication-master | OFDM_AWGN.m | .m | Digital-Communication-master/Project/MIMO OFDM/OFDM_AWGN.m | 14,570 | utf_8 | 4f1deec5c4b46b12bef0fcf0a2e1bb18 | function OFDM_AWGN()
M = 2; % Modulation alphabet
k = log2(M); % Bits/symbol
numSC = 128; % Number of OFDM subcarriers
cpLen = 32; % OFDM cyclic prefix length
maxBitErrors = 100; % Maximum number of bit errors
maxNumBits = 1e7; % Maximum number of bits transmitted
hQPSKMod = comm.DBPSKModulator;
hQPSKDemod = comm.DBPSKDemodulator;
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
hQPSKMod = comm.BPSKModulator;
hQPSKDemod = comm.BPSKDemodulator;
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec1 = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec1(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
M = 4; % Modulation alphabet
k = log2(M); % Bits/symbol
numSC = 128; % Number of OFDM subcarriers
cpLen = 32; % OFDM cyclic prefix length
maxBitErrors = 100; % Maximum number of bit errors
maxNumBits = 1e7; % Maximum number of bits transmitted
hQPSKMod = comm.QPSKModulator('BitInput',true);
hQPSKDemod = comm.QPSKDemodulator('BitOutput',true);
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec3 = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec3(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
hQPSKMod = comm.DQPSKModulator('BitInput',true);
hQPSKDemod = comm.DQPSKDemodulator('BitOutput',true);
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec5 = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec5 = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec5(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec5(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
M = 8; % Modulation alphabet
k = log2(M); % Bits/symbol
numSC = 128; % Number of OFDM subcarriers
cpLen = 32; % OFDM cyclic prefix length
maxBitErrors = 100; % Maximum number of bit errors
maxNumBits = 1e7; % Maximum number of bits transmitted
hQPSKMod = comm.PSKModulator('BitInput',true);
hQPSKDemod = comm.PSKDemodulator('BitOutput',true);
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec4 = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec4(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
hQPSKMod = comm.DPSKModulator('BitInput',true);
hQPSKDemod = comm.DPSKDemodulator('BitOutput',true);
hOFDMmod = comm.OFDMModulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hOFDMdemod = comm.OFDMDemodulator('FFTLength',numSC,'CyclicPrefixLength',cpLen);
hChan = comm.AWGNChannel('NoiseMethod','Variance', ...
'VarianceSource','Input port');
hError = comm.ErrorRate('ResetInputPort',true);
ofdmInfo = info(hOFDMmod)
numDC = ofdmInfo.DataInputSize(1)
frameSize = [k*numDC 1];
EbNoVec = (0:33)';
snrVec = EbNoVec + 10*log10(k) + 10*log10(numDC/numSC);
berVec2 = zeros(length(EbNoVec),3);
errorStats = zeros(1,3);
for m = 1:length(EbNoVec)
snr = snrVec(m);
while errorStats(2) <= maxBitErrors && errorStats(3) <= maxNumBits
dataIn = randi([0,1],frameSize); % Generate binary data
qpskTx = step(hQPSKMod,dataIn); % Apply QPSK modulation
txSig = step(hOFDMmod,qpskTx); % Apply OFDM modulation
powerDB = 10*log10(var(txSig)); % Calculate Tx signal power
noiseVar = 10.^(0.1*(powerDB-snr)); % Calculate the noise variance
rxSig = step(hChan,txSig,noiseVar); % Pass the signal through a noisy channel
qpskRx = step(hOFDMdemod,rxSig); % Apply OFDM demodulation
dataOut = step(hQPSKDemod,qpskRx); % Apply QPSK demodulation
errorStats = step(hError,dataIn,dataOut,0); % Collect error statistics
end
berVec2(m,:) = errorStats; % Save BER data
errorStats = step(hError,dataIn,dataOut,1); % Reset the error rate calculator
end
figure
semilogy(EbNoVec,berVec1(:,1),'--*')
hold on
semilogy(EbNoVec,berVec5(:,1),'--*')
hold on
semilogy(EbNoVec,berVec4(:,1),'--*')
hold on
semilogy(EbNoVec,berVec(:,1),'--*')
hold on
semilogy(EbNoVec,berVec3(:,1),'--*')
hold on
semilogy(EbNoVec,berVec2(:,1),'--*')
hold on
EsN0dB = [0:33]; % symbol to noise ratio
M=16; % 16QAM/64QAM and 256 QAM
k = sqrt(1/((2/3)*(M-1)));
simSer1(1,:) = compute_symbol_error_rate(EsN0dB, M(1));
semilogy(EsN0dB,simSer1(1,:),'r*');
M=64;
k = sqrt(1/((2/3)*(M-1)));
simSer2(2,:) = compute_symbol_error_rate(EsN0dB, M);
hold on
semilogy(EsN0dB,simSer2(2,:),'b*');
M=256;
k = sqrt(1/((2/3)*(M-1)));
simSer3(3,:) = compute_symbol_error_rate(EsN0dB, M);
hold on
semilogy(EsN0dB,simSer3(3,:),'g*');
legend('BPSK','QPSK','8-PSK','DBPSK','DQPSK','8-DPSK','16-QAM','64-QAM','256-QAM','Location','SouthWest')
title('SNR vs BER for BPSK/QPSK/8-PSK/DBPSK/DQPSK/8-DPSK/16,64,256-QAM MIMO OFDM over AWGN')
xlabel('Eb/No (dB)')
ylabel('Bit Error Rate')
grid on
hold off
return ;
function [simSer] = compute_symbol_error_rate(EsN0dB, M);
nFFT = 64; % fft size
nDSC = 52; % number of data subcarriers
nConstperOFDMsym = 52; % number of bits per OFDM symbol (same as the number of subcarriers for BPSK)
nOFDMsym = 10^4; % number of ofdm symbols
k = sqrt(1/((2/3)*(M-1))); % normalizing factor
m = [1:sqrt(M)/2]; % alphabets
alphaMqam = [-(2*m-1) 2*m-1];
EsN0dB_eff = EsN0dB + 10*log10(nDSC/nFFT) + 10*log10(64/80); % accounting for the used subcarriers and cyclic prefix
for ii = 1:length(EsN0dB)
ipMod = randsrc(1,nConstperOFDMsym*nOFDMsym,alphaMqam) + j*randsrc(1,nConstperOFDMsym*nOFDMsym,alphaMqam);
ipMod_norm = k*reshape(ipMod,nConstperOFDMsym,nOFDMsym).'; % grouping into multiple symbolsa
xF = [zeros(nOFDMsym,6) ipMod_norm(:,[1:nConstperOFDMsym/2]) zeros(nOFDMsym,1) ipMod_norm(:,[nConstperOFDMsym/2+1:nConstperOFDMsym]) zeros(nOFDMsym,5)] ;
xt = (nFFT/sqrt(nDSC))*ifft(fftshift(xF.')).';
xt = [xt(:,[49:64]) xt];
xt = reshape(xt.',1,nOFDMsym*80);
nt = 1/sqrt(2)*[randn(1,nOFDMsym*80) + j*randn(1,nOFDMsym*80)];
% Adding noise, the term sqrt(80/64) is to account for the wasted energy due to cyclic prefix
yt = sqrt(80/64)*xt + 10^(-EsN0dB_eff(ii)/20)*nt;
yt = reshape(yt.',80,nOFDMsym).'; % formatting the received vector into symbols
yt = yt(:,[17:80]); % removing cyclic prefix
yF = (sqrt(nDSC)/nFFT)*fftshift(fft(yt.')).';
yMod = sqrt(64/80)*yF(:,[6+[1:nConstperOFDMsym/2] 7+[nConstperOFDMsym/2+1:nConstperOFDMsym] ]);
y_re = real(yMod)/k;
y_im = imag(yMod)/k;
ipHat_re = 2*floor(y_re/2)+1;
ipHat_re(find(ipHat_re>max(alphaMqam))) = max(alphaMqam);
ipHat_re(find(ipHat_re<min(alphaMqam))) = min(alphaMqam);
ipHat_im = 2*floor(y_im/2)+1;
ipHat_im(find(ipHat_im>max(alphaMqam))) = max(alphaMqam);
ipHat_im(find(ipHat_im<min(alphaMqam))) = min(alphaMqam);
ipHat = ipHat_re + j*ipHat_im;
% converting to vector
ipHat_v = reshape(ipHat.',nConstperOFDMsym*nOFDMsym,1).';
% counting the errors
nErr(ii) = size(find(ipMod - ipHat_v ),2);
end
simSer = nErr/(nOFDMsym*nConstperOFDMsym);
return; |
github | mohammadzainabbas/Digital-Communication-master | playing_with_OFDM.m | .m | Digital-Communication-master/Project/Animated OFDM/playing_with_OFDM.m | 40,142 | utf_8 | 71e051b3bd99fb915fe298f8ab87a662 | function varargout = playing_with_OFDM(varargin)
% PLAYING_WITH_OFDM MATLAB code for playing_with_OFDM.fig
% PLAYING_WITH_OFDM, by itself, creates a new PLAYING_WITH_OFDM or raises the existing
% singleton*.
%
% H = PLAYING_WITH_OFDM returns the handle to a new PLAYING_WITH_OFDM or the handle to
% the existing singleton*.
%
% PLAYING_WITH_OFDM('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in PLAYING_WITH_OFDM.M with the given input arguments.
%
% PLAYING_WITH_OFDM('Property','Value',...) creates a new PLAYING_WITH_OFDM or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before playing_with_OFDM_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to playing_with_OFDM_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 playing_with_OFDM
% Last Modified by GUIDE v2.5 12-Oct-2016 17:01:44
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @playing_with_OFDM_OpeningFcn, ...
'gui_OutputFcn', @playing_with_OFDM_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 playing_with_OFDM is made visible.
function playing_with_OFDM_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 playing_with_OFDM (see VARARGIN)
% Choose default command line output for playing_with_OFDM
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes playing_with_OFDM wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = playing_with_OFDM_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 pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function edit11_Callback(hObject, eventdata, handles)
% hObject handle to edit11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit11 as text
% str2double(get(hObject,'String')) returns contents of edit11 as a double
% --- Executes during object creation, after setting all properties.
function edit11_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit6_Callback(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit6 as text
% str2double(get(hObject,'String')) returns contents of edit6 as a double
global snrValNew;
try
snrValNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter a valid SNR');
end
% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit7_Callback(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit7 as text
% str2double(get(hObject,'String')) returns contents of edit7 as a double
global pathGainsNew;
try
pathGainsNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter valid path gains');
end
% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit8_Callback(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit8 as text
% str2double(get(hObject,'String')) returns contents of edit8 as a double
global fdopNew;
try
fdopNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter a valid doppler frequency');
end
% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu2
% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
global fsNew;
try
fsNew = eval(get(hObject,'String')); % sampling frequency
catch
set(handles.text18, 'String','enter a valid sampling frequency');
end
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit2_Callback(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit2 as text
% str2double(get(hObject,'String')) returns contents of edit2 as a double
global bwSigNew;
try
bwSigNew = eval(get(hObject,'String')); % signal bandwidth
catch
set(handles.text18, 'String','enter a valid bandwidth');
end
% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit3_Callback(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit3 as text
% str2double(get(hObject,'String')) returns contents of edit3 as a double
global fsubNew;
try
fsubNew = eval(get(hObject,'String')); % sub-carrier spacing
catch
set(handles.text18, 'String','enter a valid sub-carrier spacing');
end
% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit4_Callback(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit4 as text
% str2double(get(hObject,'String')) returns contents of edit4 as a double
global symRateNew; % symbol rate
try
symRateNew = eval(get(hObject,'String')); % symbol rate
catch
set(handles.text18, 'String','enter a valid OFDM symbol rate');
end
% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit5_Callback(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit5 as text
% str2double(get(hObject,'String')) returns contents of edit5 as a double
global NcpNew; % number of CP samples
global fsubNew;
global bwSigNew;
Nsc = round(bwSigNew/fsubNew);
try
NcpTmp = eval(get(hObject,'String')); % number of CP samples at sampling rate Fs
catch
set(handles.text18, 'String','enter a valid CP length');
end
if NcpTmp >= Nsc
set(handles.text18, 'String','choose a smaller CP length');
else
NcpNew = NcpTmp;
set(handles.text18, 'String','');
end
% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
global modTypeStrNew;
contents = cellstr(get(hObject,'String'));
modTypeStrNew = contents{get(hObject,'Value')};
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit9_Callback(hObject, eventdata, handles)
% hObject handle to edit9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit9 as text
% str2double(get(hObject,'String')) returns contents of edit9 as a double
global dpSpeed;
dpSpeed = eval(get(hObject,'String'));
% --- Executes during object creation, after setting all properties.
function edit9_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit9 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit10_Callback(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit10 as text
% str2double(get(hObject,'String')) returns contents of edit10 as a double
global numOfdmSymsOnGridNew;
try
numOfdmSymsOnGridNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter a valid number of OFDM symbols to display');
end
% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
dbstop if error;
global setDefaultFlag;
if isempty(setDefaultFlag)
set_default_vals();
end
global bwSig;
global fs;
global fsChan;
global fsub;
global symRate;
global fdop;
global modTypeStr;
global pathGains;
global pathDelays;
global Ncp;
global numOfdmSymsOnGrid;
global viewTimeDomainWaveform;
global viewSubCarriers;
global pauseSim;
global exitButton;
global viewChEst3D;
global viewChEstMagPhase;
global useIdealChEstForEq;
global snrVal;
global cfoVal;
global viewEVM;
%%
chStruct.doppFilCoeff = get_dopp_filter(fdop, fsChan);
chanState = [];
sigState = [];
awgnDoppLastSamp = [];
fdopPrev = fdop;
viewSubCarrierOsr = 10;
numViewSubCarriers = 10;
fsubSymRatioPrev = fsub/symRate;
firstTimePlotFlg = 0;
fsPrev = fs;
NcpPrev = Ncp;
bwSigPrev = bwSig;
fsubPrev = fsub;
%doppFilOpArr = [];
pilotSpacing = 3;
viewTimeDomainWaveformPrev = 0;
viewSubCarriersPrev = 0;
viewChEst3DPrev = 0;
viewChEstMagPhasePrev = 0;
% generate FFT input based on modulation type
for loopCnt = 1:10000
try
if loopCnt == 1 || ~isequal(fsPrev, fs) || ~isequal(NcpPrev, Ncp) || ~isequal(fsubPrev, fsub) || ~isequal(bwSigPrev, bwSig)
Nsc = round(bwSig/fsub); % number of sub-carriers = bandwidth/sub-carrier spacing
Nsc = double(mod(Nsc, 2) == 0) * (Nsc-1) + double(mod(Nsc, 2) == 1) * Nsc;
fftOpArr = zeros(Nsc, numOfdmSymsOnGrid); % raw received OFDM symbols (Resource Elements)
fftOpEqArr = zeros(Nsc, numOfdmSymsOnGrid); % equalized OFDM symbols (Zero-forcing)
fftOpEqVec = zeros(1, Nsc*numOfdmSymsOnGrid);
chEstInterpArr = zeros(Nsc, numOfdmSymsOnGrid);
txSigArr = zeros(1, (Nsc+Ncp) * numOfdmSymsOnGrid);
idealChanFreqDomainArr = zeros(Nsc, numOfdmSymsOnGrid); % ideal channel for "numOfdmSymsOnGrid" OFDM symbols
fsPrev = fs;
NcpPrev = Ncp;
fsubPrev = fsub;
bwSigPrev = bwSig;
cfoValPrev = 0;
fsChan = ceil(fs/(Nsc+Ncp));
end
if pauseSim == 1
set(handles.pushbutton5,'string','RESUME','enable','on');
if exitButton == 1;
close(handles.figure1);
return;
end
pause(1);continue;
else
set(handles.pushbutton5,'string','PAUSE','enable','on');
end
switch modTypeStr
case 'BPSK'
fftIp = (2*round(rand(1, Nsc))-1);
evmConstRef = unique((2*round(rand(1, 1e2))-1));
txPwr = 1;
case 'QPSK'
fftIp = (2*round(rand(1, Nsc))-1) + 1j*(2*round(rand(1, Nsc)) -1);
evmConstRef = unique((2*round(rand(1, 1e2))-1) + 1j*(2*round(rand(1, 1e2))-1));
txPwr = 2;
case '16QAM'
fftIp = (2*round(3*rand(1, Nsc))-3) + 1j*(2*round(3*rand(1, Nsc)) -3);
evmConstRef = unique((2*round(3*rand(1, 1e2))-3) + 1j*(2*round(3*rand(1, 1e2))-3));
txPwr = 10;
case '64QAM'
fftIp = (2*round(7*rand(1, Nsc))-7) + 1j*(2*round(7*rand(1, Nsc)) -7);
evmConstRef = unique((2*round(7*rand(1, 1e3))-7) + 1j*(2*round(7*rand(1, 1e3))-7));
txPwr = 42;
case '256QAM'
fftIp = (2*round(15*rand(1, Nsc))-15) + 1j*(2*round(15*rand(1, Nsc)) -15);
evmConstRef = unique((2*round(15*rand(1, 1e3))-15) + 1j*(2*round(15*rand(1, 1e3))-15));
txPwr = 170;
otherwise % DEFAULT is QPSK
fftIp = (2*round(rand(1, Nsc))-1) + 1j*(2*round(rand(1, Nsc)) -1);
evmConstRef = unique((2*round(rand(1, 1e2))-1) + 1j*(2*round(rand(1, 1e2))-1));
txPwr = 2;
end
% insert pilot symbols
%chEstIdeal = (1+1j)/sqrt(2)*sqrt(txPwr);
chEstIdeal = max(real(evmConstRef)) + 1j*max(imag(evmConstRef));
fftIp([1:pilotSpacing:end]) = chEstIdeal;
fftIpIntf = fftIp*sinc(1/symRate*([0:fsub:fsub*Nsc-fsub]'*ones(1,Nsc)-ones(Nsc, 1)*[0:1:Nsc-1]*fsub)).';
if fdop ~= fdopPrev
chStruct.doppFilCoeff = get_dopp_filter(fdop, fsChan);
end
fdopPrev = fdop;
% insert CP and take IFFT
txSig = ifft([fftIpIntf])*sqrt(Nsc);%/Nsc;
txSig = [txSig(end-Ncp+1:end) txSig];
txSigArr(1:(Ncp+Nsc)*(numOfdmSymsOnGrid-1)) = txSigArr(Ncp+Nsc+1:end);
txSigArr((Ncp+Nsc)*(numOfdmSymsOnGrid-1)+1:end) = txSig;
% Apply multipath channel
[multipathChanOp, sigState, chanState, idealChan, doppFilResampled, awgnDoppLastSamp] = myrayleighchan(txSig, chStruct, pathGains, pathDelays, fs, fsChan, sigState, chanState, awgnDoppLastSamp);
% Apply noise
chPwr = sum(10.^(pathGains/10));
noiseVec = sqrt(chPwr*txPwr)*(1/sqrt(2))*(randn(size(multipathChanOp)) + 1j * randn(size(multipathChanOp)))*10^(-snrVal/20);
rxSigNoise = multipathChanOp + noiseVec;
% Apply CFO and sample offset
rxSigNoiseCfo = rxSigNoise.*exp(1j*2*pi*[0:1:Nsc+Ncp-1]*cfoVal/fs + cfoValPrev);
cfoValPrev = 1j*2*pi*(Nsc+Ncp-1)*cfoVal/fs + cfoValPrev;
% CP removal
% FFT
fftOp = fft(rxSigNoiseCfo(Ncp+1:end));
chEstRaw = fftOp(1:pilotSpacing:end)/chEstIdeal;
pilotIndices = [1:pilotSpacing:ceil(Nsc/pilotSpacing)*pilotSpacing];
try
chEstInterp = interp1(pilotIndices,chEstRaw, [1:1:max(pilotIndices)]);
catch
chEstInterp = chEstRaw;
end
chEstInterp(max(pilotIndices)+1:Nsc) = chEstInterp(max(pilotIndices));
% ideal channel frequency domain
idealChanFreqDomain = fft(idealChan(1:end-Ncp))*sqrt(Nsc);
% equalization
if useIdealChEstForEq == 1
fftOpEq = fftOp./idealChanFreqDomain;
else
fftOpEq = fftOp./chEstInterp;
end
idealChanFreqDomainArr(:, 1:end-1) = idealChanFreqDomainArr(:, 2:end);
idealChanFreqDomainArr(:, end) = idealChanFreqDomain.';
fftOpArr(:, 1:end-1) = fftOpArr(:, 2:end);
fftOpArr(:, end) = fftOp.';
fftOpEqArr(:, 1:end-1) = fftOpEqArr(:, 2:end);
fftOpEqArr(:, end) = fftOpEq.';
fftOpEqVec(1:(numOfdmSymsOnGrid-1)*Nsc) = fftOpEqVec([1:(numOfdmSymsOnGrid-1)*Nsc] + Nsc);
fftOpEqVec([1:Nsc]+(numOfdmSymsOnGrid-1)*Nsc) = fftOpEq;
chEstInterpArr(:, 1:end-1) = chEstInterpArr(:, 2:end);
chEstInterpArr(:, end) = chEstInterp.';
surf(handles.axes1, abs(idealChanFreqDomainArr)); zLimit = max(max(abs(idealChanFreqDomainArr)));
xlabel(handles.axes1, 'OFDM symbol');ylabel(handles.axes1, 'sub-carrier');zlabel(handles.axes1, 'Amplitude');
set(handles.axes1, 'zlim', [0 zLimit]);
%drawnow();
plot(handles.axes2, fftOpEqVec, 'k*');
xlabel(handles.axes2, 'Real');ylabel(handles.axes2, 'Imaginary');
set(handles.axes2, 'xlim', [-16 16], 'ylim', [-16 16]);
drawnow();
if viewEVM == 1
[evmVal] = evm_compute(fftOpEq, evmConstRef);
set(handles.edit11,'string',evmVal);
else
set(handles.edit11,'string','NA');
end
% VIEW TIME DOMAIN WAVEFORM
if viewTimeDomainWaveform == 1
figure(1);plot([0:1/fs:(Nsc+Ncp)*numOfdmSymsOnGrid/fs-1/fs], abs(txSigArr), 'b');xlabel('time (seconds)');ylabel('Amplitude');title('OFDM time domain waveform (magnitude) at fs');
else
if viewTimeDomainWaveform ~= viewTimeDomainWaveformPrev
close(figure(1));
end
end
viewTimeDomainWaveformPrev = viewTimeDomainWaveform;
% VIEW SUB-CARRIERS (WIDTH AND SPACING RELATION)
if viewSubCarriers == 1
fsubSymRatio = fsub/symRate;
if fsubSymRatio ~= fsubSymRatioPrev
firstTimePlotFlg = 0;
end
% the sub-carrier plot does not change for every iteration
% it changes only when the symbol rate or the sub-carrier spacing is changed
if firstTimePlotFlg == 0
sincMat = sinc(1/symRate*([0:fsub/viewSubCarrierOsr:numViewSubCarriers*fsub-fsub/viewSubCarrierOsr]'*ones(1,numViewSubCarriers)-ones(numViewSubCarriers*viewSubCarrierOsr, 1)*[0:1:numViewSubCarriers-1]*fsub)).';
figure(2);plot([0:1/viewSubCarrierOsr:numViewSubCarriers-1/viewSubCarrierOsr]*fsub, sincMat);xlabel('frequency (Hz)');ylabel('Amplitutde');title('Sub-carrier spacing and symbol rate relation');
drawnow();
firstTimePlotFlg = 1;
end
fsubSymRatioPrev = fsubSymRatio;
else
if viewSubCarriersPrev ~= viewSubCarriers
close(figure(2));
end
firstTimePlotFlg = 0;
end
viewSubCarriersPrev = viewSubCarriers;
% CHANNEL ESTIMATE
if viewChEst3D == 1
figure(3);
surf(abs(chEstInterpArr));
title('Channel Estimate - 3D view');zLimit = max(max(abs(chEstInterpArr)));xlabel('OFDM symbol');ylabel('sub-carrier');zlabel('Amplitude');
else
if viewChEst3D ~= viewChEst3DPrev
close(figure(3));
end
end
viewChEst3DPrev = viewChEst3D;
if viewChEstMagPhase == 1
figure(4);subplot(211);title('Channel Estimate for each OFDM symbol');
plot(abs(chEstInterp), 'b-x');hold on;plot(abs(idealChanFreqDomain), 'r-o');hold off;xlabel('sub-carrier number');ylabel('Amplitude');grid on;legend('Estimated channel','Ideal channel');
subplot(212);
plot(angle(chEstInterp), 'b-x');hold on;plot(angle(idealChanFreqDomain), 'r-o');hold off;xlabel('sub-carrier number');ylabel('Phase');grid on;legend('Estimated channel','Ideal channel');
else
if viewChEstMagPhase ~= viewChEstMagPhasePrev
close(figure(4));
end
end
viewChEstMagPhasePrev = viewChEstMagPhase;
if exitButton == 1;
close(handles.figure1);
return;
end
catch
if exitButton == 1;
close(handles.figure1);
return;
end
set(handles.text18, 'String','Something has gone wrong! \n Exit and start over again');
continue;
end
end
function set_default_vals()
global bwSig;
global fs;
global fsChan;
global fsub;
global symRate;
global fdop;
global modTypeStr;
global pathGains;
global pathGainsTmp;
global pathDelays;
global pathDelaysTmp;
global Ncp;
global numOfdmSymsOnGrid;
global setDefaultFlag;
global viewTimeDomainWaveform;
global viewSubCarriers;
global pauseSim;
global exitButton;
global viewChEst3D;
global viewChEstMagPhase;
global useIdealChEstForEq;
global snrVal;
global cfoVal;
global phOffsetVal;
global viewEVM;
global bwSigNew;
global fsNew;
global fsChanNew;
global fsubNew;
global symRateNew;
global fdopNew;
global modTypeStrNew;
global pathGainsNew;
global pathDelaysNew;
global NcpNew;
global numOfdmSymsOnGridNew;
global snrValNew;
global cfoValNew;
global phOffsetValNew;
setDefaultFlag = 1;
bwSig = 1.4e6;
fs = 1.92e6;
fsChan = 0.01*fs;
fsub = 15e3;
symRate = fsub*1;
fdop = 300;
modTypeStr = 'QPSK';
pathGains = [0 -3 -6 -9];
pathGainsTmp = pathGains;
pathDelays = [0 0.4e-6 1e-6 1.5e-6]; % path delays in seconds
pathDelaysTmp = pathDelays;
Ncp = 20;
numOfdmSymsOnGrid = 14;
viewTimeDomainWaveform = 0;
viewSubCarriers = 0;
pauseSim = 0;
exitButton = 0;
viewChEst3D = 0;
viewChEstMagPhase = 0;
useIdealChEstForEq = 0;
snrVal = 1000;
cfoVal = 0;
phOffsetVal = 0;
viewEVM = 0;
bwSigNew = bwSig;
fsNew = fs;
fsChanNew = fsChan;
fsubNew = fsub;
symRateNew = symRate;
fdopNew = fdop;
modTypeStrNew = modTypeStr;
pathGainsNew = pathGains;
pathDelaysNew = pathDelays;
NcpNew = Ncp;
numOfdmSymsOnGridNew = numOfdmSymsOnGrid;
snrValNew = snrVal;
cfoValNew = cfoVal;
phOffsetValNew = phOffsetVal;
% EVM COMPUTATION
function [evmVal] = evm_compute(complexSyms, evmConstRef)
M = length(evmConstRef);
% find the reference point closest to the complex symbols
evmConstRefRepMat = (evmConstRef.'*ones(1, length(complexSyms)));
% find euclidean distance and compute EVM
[minDisVec, indexVec] = min((abs((ones(M, 1)*complexSyms) - evmConstRefRepMat).^2));
evmVal = sqrt(sum(minDisVec.^2)./sum(abs(evmConstRefRepMat([0:M:length(complexSyms)*M-1]+indexVec)).^2));
evmVal = round(evmVal*1e4)/1e4;
function edit12_Callback(hObject, eventdata, handles)
% hObject handle to edit12 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit12 as text
% str2double(get(hObject,'String')) returns contents of edit12 as a double
global pathDelaysNew;
try
pathDelaysNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter valid path delays');
end
% --- Executes during object creation, after setting all properties.
function edit12_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit12 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
global viewTimeDomainWaveform;
viewTimeDomainWaveform = get(hObject,'Value');
% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton2
global viewSubCarriers
viewSubCarriers = get(hObject,'Value');
% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global pauseSim;
if pauseSim == 1
pauseSim = 0;
else
pauseSim = 1;
end
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global exitButton;
exitButton = 1;
function edit14_Callback(hObject, eventdata, handles)
% hObject handle to edit14 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit14 as text
% str2double(get(hObject,'String')) returns contents of edit14 as a double
global cfoValNew;
try
cfoValNew = eval(get(hObject,'String'));
catch
set(handles.text18, 'String','enter a valid carrier frequency offset');
end
% --- Executes during object creation, after setting all properties.
function edit14_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit14 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in radiobutton3.
function radiobutton3_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton3
global viewChEst3D;
viewChEst3D = get(hObject,'Value');
% --- Executes on button press in radiobutton4.
function radiobutton4_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton4
global useIdealChEstForEq;
useIdealChEstForEq = get(hObject,'Value');
% --- Executes on button press in radiobutton5.
function radiobutton5_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton5
global viewChEstMagPhase;
viewChEstMagPhase = get(hObject,'Value');
% --- Executes on button press in radiobutton6.
function radiobutton6_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton6
global viewEVM;
viewEVM = get(hObject, 'Value');
% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global bwSig;
global fs;
global fsChan;
global fsub;
global symRate;
global fdop;
global modTypeStr;
global pathGains;
global pathDelays;
global Ncp;
global numOfdmSymsOnGrid;
global snrVal;
global cfoVal;
global phOffsetVal;
global bwSigNew;
global fsNew;
global fsChanNew;
global fsubNew;
global symRateNew;
global fdopNew;
global modTypeStrNew;
global pathGainsNew;
global pathDelaysNew;
global NcpNew;
global numOfdmSymsOnGridNew;
global snrValNew;
global cfoValNew;
global phOffsetValNew;
fsChan = fsChanNew;
modTypeStr = modTypeStrNew;
Ncp = NcpNew;
numOfdmSymsOnGrid = numOfdmSymsOnGridNew;
snrVal = snrValNew;
cfoVal = cfoValNew;
phOffsetVal = phOffsetValNew;
set(handles.text18, 'String','');
if isequal(size(pathGainsNew), size(pathDelaysNew))
if ~isequal(pathGainsNew, pathGains)
set(handles.text18, 'String','path gains are updated');
end
pathGains = pathGainsNew;
pathDelays = pathDelaysNew;
else
set(handles.text18, 'String','the sizes of path gains and path delays are not compatible - consider revision');
pathGainsStr = sprintf('%0.1f,', round(pathGains*10)/10);
pathDelaysStr = sprintf('%0.1f,', round(pathDelays*1e6*10)/10);
set(handles.edit7, 'String', ['[' pathGainsStr(1:end-1) ']']);
set(handles.edit12, 'String', ['[' pathDelaysStr(1:end-1) ']*1e-6']);
pathDelaysNew = pathDelays;
pathGainsNew = pathGains;
end
if fsNew < bwSigNew
set(handles.text18, 'String','choose sampling frequency greater than the bandwidth');
set(handles.edit1, 'String', [num2str(fs/1e6) 'e6']);
set(handles.edit2, 'String', [num2str(bwSig/1e6) 'e6']);
bwSigNew = bwSig;
fsNew = fs;
else
bwSig = bwSigNew;
fs = fsNew;
end
% Caution - DO NOT move the following condition from the current position
% bandwidth value needs to be frozen before sub-carrier spacing is determined
if fsubNew > (bwSig/4) % 4 is by choice
if ~isequal(fsub, fsubNew)
set(handles.text18, 'String','choose a smaller sub-carrier spacing');
set(handles.edit3, 'String', [num2str(fsub/1e3) 'e3']);
fsubNew = fsub;
else
set(handles.text18, 'String','bandwidth too low - forcing a higher bandwidth');
set(handles.edit2, 'String', [num2str(fsub*4/1e3) 'e3']);
bwSig = fsub*4;
bwSigNew = bwSig;
end
else
fsub = fsubNew;
end
% Caution - DO NOT move the following condition from the current position
% bandwidth value needs to be frozen before symbol rate is determined
if symRateNew > (bwSig/4) % 4 is by choice
set(handles.text18, 'String','choose a smaller OFDM symbol rate');
set(handles.edit4, 'String', [num2str(symRate/1e3) 'e3']);
symRateNew = symRate;
else
symRate = symRateNew;
end
% Caution - DO NOT move the following condition from the current position
% Ncp has to be determined based on bandwidth and sub-carrier spacing - the
% order of the code matters
if NcpNew > (bwSig/fsub) % number of CP samples should be stricly less than the number of samples per OFDM symbol
set(handles.text18, 'String','forcing a smaller cyclic prefix length');
Ncp = floor(bwSig/fsub)-1;
if Ncp < 0
Ncp = 0;
end
set(handles.edit5, 'String', num2str(Ncp));drawnow();
NcpNew = Ncp;
else
Ncp = NcpNew;
end
if fdopNew < 5
set(handles.text18, 'String','set doppler to at least 5 Hz');
fdopNew = fdop;
else
fdop = fdopNew;
end
if max(round(pathDelays*fs)) > round(bwSigNew/fsubNew)
set(handles.text18, 'String','Path delays are too high. Forcing to only LOS path');
pathDelays = 0;
pathGains = 0;
set(handles.edit7, 'String', [num2str(pathGains)]);
set(handles.edit12, 'String', [num2str(pathDelays) '*1e-6']);
pathDelaysNew = pathDelays;
pathGainsNew = pathGains;
end
|
github | mohammadzainabbas/Digital-Communication-master | main_polar.m | .m | Digital-Communication-master/Lab 05/main_polar.m | 1,649 | utf_8 | 08ee30612310411d7c77f65f840814b8 | function main_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = -5;
end
i = i + 1;
end
end
function pulse = polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
else
pulse(k: k + (Samples_per_bit_time - 1)/2) = -5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | main_uni_polar.m | .m | Digital-Communication-master/Lab 05/main_uni_polar.m | 1,515 | utf_8 | cc85b26c7c868ea1c2711b547bbacea5 | function main_uni_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
function pulse = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab 05/main.m | 1,515 | utf_8 | cc85b26c7c868ea1c2711b547bbacea5 | function main_uni_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
function pulse = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab/Lab 6/main.m | 1,200 | utf_8 | 298580e6f6d8e6dc468b8e06d85f6c36 | function main()
Fs = 1000;
t = [0:1/Fs:1];
number_of_samples = length(t);
%freq = input('Enter your frequency: ');
freq = 5;
x = sin(2*pi*freq*t);
%x = randn(1,100);
Nyquist = 2*freq;
%At_nyquist = Fs/(Nyquist);
% Less_than_nyquist = Fs/(Nyquist/2);
More_than_nyquist = Fs/(10*Nyquist);
%x = sin(2*pi*max_freq*t);
figure
subplot(3,1,1)
plot(x)
%At nyquist
x1 = x(2:More_than_nyquist:end);
subplot(3,1,2)
stem(x1)
%Qunatization
%partition = [-1:.5:1];
partition = [-1, -.75, -.5, 0 , .5, .75, 1];
codebook = [0,1,2,3,4,5,6,7];
[out,y] = quantiz(x, partition, codebook);
bit_stream = dec2bin(y);
subplot(3,1,3)
stem(y)
end
function main_polar_NRZ()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = -5;
end
i = i + 1;
end
plot(t, pulse);
end |
github | mohammadzainabbas/Digital-Communication-master | main_polar.m | .m | Digital-Communication-master/Lab/Lab 5/main_polar.m | 1,594 | utf_8 | 94cbbd8eadfbfc6992f5e41474602681 | function main_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = -5;
end
i = i + 1;
end
end
function pulse = polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
else
pulse(k: k + (Samples_per_bit_time - 1)/2) = -5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | main_uni_polar.m | .m | Digital-Communication-master/Lab/Lab 5/main_uni_polar.m | 1,463 | utf_8 | 68110bb38cd2bd6652f48edc0c8bbf56 | function main_uni_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
function pulse = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab/Lab 5/main.m | 1,463 | utf_8 | 68110bb38cd2bd6652f48edc0c8bbf56 | function main_uni_polar()
x = [0 0 0 1 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 0 0 1 1 1 1 0 0 0];
Bit_rate = 5;
Samples_per_bit_time = 200;
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse_NRZ = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate);
pulse_RZ = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate);
subplot(2,1,1)
plot(t, pulse_NRZ);
subplot(2,1,2)
plot(t, pulse_RZ);
end
function pulse = uni_polar_NRZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + Samples_per_bit_time - 1) = 5;
else
pulse(k: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
function pulse = uni_polar_RZ(x, Samples_per_bit_time, Bit_rate)
Total_time = length(x)/Bit_rate;
Bit_time = 1/Bit_rate;
Tb = Bit_time;
t = Tb/Samples_per_bit_time:Tb/Samples_per_bit_time:Total_time;
pulse = zeros(1, (length(x)*Samples_per_bit_time));
i = 1;
for k = 1:Samples_per_bit_time:length(x)*Samples_per_bit_time
if (x(i) == 1)
pulse(k: k + (Samples_per_bit_time - 1)/2) = 5;
pulse( k + (Samples_per_bit_time - 1)/2: k + Samples_per_bit_time - 1) = 0;
end
i = i + 1;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | Task_1.m | .m | Digital-Communication-master/Lab/Lab 3/Task_1.m | 851 | utf_8 | 1a46c0d098a870ec5b50b26e690d2bd7 | function Task_1()
%To generate random signal
x = random_signal();
size = length(x);
bins = input('Enter number of bins: ');
%Calculate pdf
pdf = PDF(x, bins);
%Rearranging x-axis of both so that mean appears at 0
x_axis = min(x):(max(x)-min(x))/(bins):max(x) - (max(x)-min(x))/(bins);
%x_axis = x_axis(1:size-1); %coz no. of bins = length - 1
% length(x)
% length(pdf)
%Calculating mean of signal
mean = sum((x) .* pdf);
%Calculating variance of signal
variance = sum(power((x - mean),2)/(length(x)));
%To change mean and variance
y = (100)*x + 1000;
pdf_y = PDF(y, bins);
y_axis = x_axis + 1000;
%Plot
figure
subplot(2,1,1)
bar(x_axis,pdf)
subplot(2,1,2)
bar(y_axis,pdf_y)
end
function x = random_signal()
size = input('Enter signal size: ');
x = randn(1,size);
end
function pdf = PDF(x, bins)
pdf = hist(x,bins)/(length(x));
end |
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab/Lab 2/main.m | 1,420 | utf_8 | abbeb77204d625588c06f820594aa234 | function main()
%Task No. 01
%Generate 2 random signal
[x1,size1] = random_signal();
[x2,size2] = random_signal();
%Calculate pdfs of both
[pdf1, bins1] = PDF(x1);
[pdf2, bins2] = PDF(x2);
%Rearranging x-axis of both so that mean appears at 0
x1_axis = min(x1):(max(x1)-min(x1))/(bins1):max(x1);
x1_axis = x1_axis(1:size1); %coz no. of bins = length - 1
x2_axis = min(x2):(max(x2)-min(x2))/(bins2):max(x2);
x2_axis = x2_axis(1:size2);
% %plot both signals
% figure
% subplot(2,1,1)
% bar(x1_axis,pdf1);
% subplot(2,1,2)
% bar(x2_axis,pdf2);
%Task No. 02
%We already have both the signals x1 and x2, so don't need to generate them
%Calculating mean of both signals
mean1 = sum((x1) .* pdf1);
mean2 = sum((x2) .* pdf2);
%Calculating variance of both signals
variance1 = sum(power((x1 - mean1),2)/(length(x1)))
variance2 = sum(power((x2 - mean2),2)/(length(x2)))
% %Ploting PDFs of both
% figure
% subplot(2,1,1)
% bar(x1_axis,pdf1);
% subplot(2,1,2)
% bar(x2_axis,pdf2);
%Chaning mean of signal x2 from 0 to 300 and -300
new1_x2 = x2 + 300;
new2_x2 = x2 - 300;
figure
subplot(3,1,1)
bar(x2_axis,pdf2)
subplot(3,1,2)
bar(x2_axis,PDF(new1_x2)[1])
subplot(3,1,3)
bar(x2_axis,PDF(new2_x2)[1])
end
function [x, size] = random_signal()
size = input('Enter signal size: ');
x = randn(1,size);
end
function [pdf, bins] = PDF(x)
bins = input('Enter number of bins: ');
pdf = hist(x,bins)/(length(x));
end |
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab/Lab 8/main.m | 2,810 | utf_8 | 667364a1769de5351be54047d2a1476d |
function main()
%Defining common variables
signal_length = 100000;
M = 4;
m = 2;
%Vi = [sqrt(1 + 1) sqrt(1 + 1) sqrt(1 + 1) sqrt(1 + 1)];
%Es = 1/M*sum(abs(Vi)*2)
Es = 2;
Eb = Es/m;
No = 1;
%SNR = Eb/No
SNR = [1:10];
%SNR_t = 10;
%Generate Binary Data
Binary_Data1 = round(rand(1,signal_length));
Real_BD = 2*(Binary_Data1 - 0.5);
Binary_Data2 = round(rand(1,signal_length));
Imaginary_BD = 2*(Binary_Data2 - 0.5);
%Generate complex signal for QPSK
Signal = Real_BD + j*Imaginary_BD;
for k=1:length(SNR)
%Random Noise Generation
factor(k) = 1/(sqrt(2*SNR(k)));
noise = factor(k)*(randn(1, signal_length) + j*randn(1, signal_length));
%For Rayleigh fading channel
Modulated_signal = Signal + noise;
%For demodulation
Received = Modulated_signal;
demodulated_real=[];
demodulated_imaginary =[];
%
% for i=1:2:length(Received)
% current_part = Received(i);
% if i == length(Received)
% next_part = Received(i);
% else
% next_part = Received(i+1);
% end
%
% %real-> +ve and img-> +ve
% if (current_part >= 0 && next_part >= 0)
% demodulated = [demodulated 1 1];
% %real-> -ve and img-> +ve
% else if(current_part <= 0 && next_part >= 0)
% demodulated = [demodulated 1 0];
% %real-> +ve and img-> -ve
% else if(current_part >= 0 && next_part <= 0)
% demodulated = [demodulated 0 1];
% %real-> -ve and img-> -ve
% else
% demodulated = [demodulated 0 0];
% end
% end
% end
% end
for i=1:length(Received)
real_part = real(Received(i));
imaginary_part = imag(Received(i));
%real-> +ve and img-> +ve
if (real_part >= 0 && imaginary_part >= 0)
demodulated_real = [demodulated_real 1];
demodulated_imaginary = [demodulated_imaginary 1];
%real-> -ve and img-> +ve
else if(real_part <= 0 && imaginary_part >= 0)
demodulated_real = [demodulated_real -1];
demodulated_imaginary = [demodulated_imaginary 1];
%real-> +ve and img-> -ve
else if(real_part >= 0 && imaginary_part <= 0)
demodulated_real = [demodulated_real 1];
demodulated_imaginary = [demodulated_imaginary -1];
%real-> -ve and img-> -ve
else
demodulated_real = [demodulated_real -1];
demodulated_imaginary = [demodulated_imaginary -1];
end
end
end
end
length(demodulated_real)
length(Binary_Data1)
length(Signal)
%BER - Bit error rate
Change_in_real = sum((Real_BD ~=demodulated_real));
Change_in_imaginary = sum((Imaginary_BD ~=demodulated_imaginary));
Total_Different = Change_in_real + Change_in_imaginary;
Total_bits = length(Real_BD) + length(Imaginary_BD);
BER(k) = Total_Different/Total_bits;
end
%Plot
semilogy(10*log10(SNR),BER);
end
% function y = BinaryToComplex(x)
% j = 1;
% for i=1:length(x)
% if(x(i)==0 && x(i+1))
% y(j)
% end
% end
% end |
github | mohammadzainabbas/Digital-Communication-master | LTE_channels2.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/LTE_channels2.m | 1,092 | utf_8 | dfa01f96b571c56d572b9f530309cf89 |
% function [ci_imp_out] = LTE_channels (type,bandwidth)
function [delay_a pow_a] = LTE_channels2 (type,bandwidth)
%LTE channels
% % EPA = 0;
% % ETU = 1;
% % EVA = 0;
% %
bandw = bandwidth; % 5MHz
if type == 'EPA' % Low selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 70 80 110 190 410]*1e-9;
pow_a = [0 -1 -2 -3 -8 -17.2 -20.7];
elseif type == 'EVA' % Moderate selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 150 310 370 710 1090 1730 2510 ]*1e-9;
pow_a = [0 -1.5 -1.4 -3.6 -0.6 -9.1 -7.0 -12-0 -16.9];
elseif type == 'ETU' % High selectivity
ci_imp = zeros(1,127);
delay_a = [0 50 120 200 230 500 1600 2300 5000]*1e-9;
pow_a = [-1 -1.0 -1.0 0 0 0 -3 -5 -7];
else
error('Invalid channel profile selection');
end
%
% pow_a_lin = 10.^(pow_a./10);
% %
% % %Making the sampled channel
% tss = 1./bandw;
% pos_a = round(delay_a./tss);
% c_imp_sampled = [];
% for i = min(pos_a):max(pos_a)
% c_imp_sampled(i+1) = sum(pow_a_lin(pos_a==i));
% end
% ci_imp_out = sqrt((c_imp_sampled.^2./sum(c_imp_sampled.^2)));
|
github | mohammadzainabbas/Digital-Communication-master | func_preamble_creation.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/func_preamble_creation.m | 3,244 | utf_8 | fa32e8bcf9b434982533457708d3578c | %% func_preamble_creation: function description
function [preamble,length_preamble,est_col] = func_preamble_creation(M, preamble_sel, zero_pads, extra_zero, user_indices, eq_select, fractional)
%% func_Analysis_Filter_Bank
%
% Burak Dayi
%
% This function will return the preamble.
%
% Created: 25-02-2015
preamble = NaN;
center_preamble = NaN;
est_col = 0;
length_preamble = 0;
% define preambles here
switch preamble_sel
case 0
center_preamble = repmat([1 -j -1 j].',M/4,1); % IAM-I
est_col = 1+zero_pads; % estimation on this column
case 1
center_preamble = repmat([1 1 -1 -1].',M/4,1); % IAM-R
est_col = 1+zero_pads; % estimation on this column
case 2
center_preamble = repmat(repmat([1 -j -1 j].',M/4,1),1,3); % IAM-I with triple repetition.
est_col = 2+zero_pads; % estimation on middle column
otherwise
error('Invalid preamble selection.')
end
if fractional
% now according to equalizer and user indices,
% the preamble will be prepared
% the unused subchannels will be sieved out.
if eq_select == 1 % 1: one tap
% we need only those indices over which data is transmitted.
if preamble_sel == 2
center_preamble(1:(user_indices(1)-1),:) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+1):(user_indices(2*i+1)-1),:) = 0;
end
center_preamble((user_indices(end)+1):end,:) = 0;
else
center_preamble(1:(user_indices(1)-1)) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+1):(user_indices(2*i+1)-1)) = 0;
end
center_preamble((user_indices(end)+1):end) = 0;
end
elseif (eq_select == 2) | (eq_select == 3) %2: % three taps
% when three taps are applied, in order to get a reliable channel estimation
% on edge frequencies, we need to extend the covered subchannels by one
% from each upper and lower bound
if preamble_sel == 2
center_preamble(1:(user_indices(1)-2),:) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+2):(user_indices(2*i+1)-2),:) = 0;
end
center_preamble((user_indices(end)+2):end,:) = 0;
else
center_preamble(1:(user_indices(1)-2)) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+2):(user_indices(2*i+1)-2)) = 0;
end
center_preamble((user_indices(end)+2):end) = 0;
end
elseif eq_select == 4 % no equalizer
% we need only those indices over which data is transmitted. ?!?!?!?!?!
if preamble_sel == 2
center_preamble(1:(user_indices(1)-1),:) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+1):(user_indices(2*i+1)-1),:) = 0;
end
center_preamble((user_indices(end)+1):end,:) = 0;
else
center_preamble(1:(user_indices(1)-1)) = 0;
for i=1:((length(user_indices)/2)-1)
center_preamble((user_indices(2*i)+1):(user_indices(2*i+1)-1)) = 0;
end
center_preamble((user_indices(end)+1):end) = 0;
end
else
error('Unhandled equalizer selection.')
end
end
% construct preamble with zero pads
pads = repmat(zeros(M,1),1,zero_pads);
early_preamble = [pads center_preamble pads];
if extra_zero
preamble = [early_preamble zeros(M,1)];
else
preamble = early_preamble;
end
length_preamble = size(preamble,1)*size(preamble,2); |
github | mohammadzainabbas/Digital-Communication-master | LTE_channels.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/LTE_channels.m | 1,159 | utf_8 | 6cd1bd3a74ef171521fd74d48d312da8 |
function [ci_imp_out] = LTE_channels (type,bandwidth)
% function [delay_a pow_a] = LTE_channels (type,bandwidth)
%LTE channels
% % EPA = 0;
% % ETU = 1;
% % EVA = 0;
% %
bandw = bandwidth; % 5MHz
if type == 'EPA' % Low selectivity
% disp('epa')
ci_imp = zeros(1,127);
delay_a = [0 30 70 80 110 190 410]*1e-9;
pow_a = [0 -1 -2 -3 -8 -17.2 -20.7];
elseif type == 'EVA' % Moderate selectivity
% disp('eva')
ci_imp = zeros(1,127);
delay_a = [0 30 150 310 370 710 1090 1730 2510 ]*1e-9;
pow_a = [0 -1.5 -1.4 -3.6 -0.6 -9.1 -7.0 -12-0 -16.9];
elseif type == 'ETU' % High selectivity
% disp('etu')
ci_imp = zeros(1,127);
delay_a = [0 50 120 200 230 500 1600 2300 5000]*1e-9;
pow_a = [-1 -1.0 -1.0 0 0 0 -3 -5 -7];
else
error('Invalid channel profile selection');
end
pow_a_lin = 10.^(pow_a./10);
%
% %Making the sampled channel
tss = 1./bandw;
pos_a = round(delay_a./tss);
c_imp_sampled = [];
for i = min(pos_a):max(pos_a)
c_imp_sampled(i+1) = sum(pow_a_lin(pos_a==i));
end
ci_imp_out = sqrt((c_imp_sampled.^2./sum(c_imp_sampled.^2)));
% figure
% plot(ci_imp_out);
|
github | mohammadzainabbas/Digital-Communication-master | showplot.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/showplot.m | 25,776 | utf_8 | 150d907ace499d22ace62fa483c60169 | function varargout = showplot(varargin)
% SHOWPLOT MATLAB code for showplot.fig
% SHOWPLOT, by itself, creates a new SHOWPLOT or raises the existing
% singleton*.
%
% H = SHOWPLOT returns the handle to a new SHOWPLOT or the handle to
% the existing singleton*.
%
% SHOWPLOT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SHOWPLOT.M with the given input arguments.
%
% SHOWPLOT('Property','Value',...) creates a new SHOWPLOT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before showplot_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to showplot_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 showplot
% Last Modified by GUIDE v2.5 13-May-2014 14:56:19
% Created: 19-03-2014
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @showplot_OpeningFcn, ...
'gui_OutputFcn', @showplot_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 showplot is made visible.
function showplot_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 showplot (see VARARGIN)
% Choose default command line output for showplot
handles.output = hObject;
% obtain BER file
[fname, pname] = uigetfile({['BER*.mat;MSE_db*.mat']},'Choose BER/MSE file');
if fname
if strcmp(fname(1:3),'BER')
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file='BER';
handles.BER = BER;
elseif strcmp(fname(1:6),'MSE_db')
try
load(strcat(pname, fname));
catch
error('MSE data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(9:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file=fname(1:8);
if strcmp(handles.file,'MSE_db_a')
handles.MSE_db = MSE_db_a;
elseif strcmp(handles.file,'MSE_db_f')
handles.MSE_db = MSE_db_f;
elseif strcmp(handles.file,'MSE_db_r')
handles.MSE_db = MSE_db_r;
end
elseif strcmp(fname(1:3),'MSE')
%not implemented yet.
else
error('Invalid file.')
end
else
warning('A BER/MSE file should be selected');
[fname, pname] = uigetfile({'BER*.mat;MSE_db*.mat'},'Choose BER file');
if ~fname
error('Could not reach a BER/MSE file');
else
if strcmp(fname(1:3),'BER')
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file='BER';
handles.BER = BER;
elseif strcmp(fname(1:6),'MSE_db')
try
load(strcat(pname, fname));
catch
error('MSE data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(9:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file=fname(1:8);
if strcmp(handles.file,'MSE_db_a')
handles.MSE_db = MSE_db_a;
elseif strcmp(handles.file,'MSE_db_f')
handles.MSE_db = MSE_db_f;
elseif strcmp(handles.file,'MSE_db_r')
handles.MSE_db = MSE_db_r;
end
elseif strcmp(fname(1:3),'MSE')
%not implemented yet.
else
end
end
end
% new_data_process(hObject,handles,BER,conf,fname);
new_data_process(hObject,handles,handles.file,conf,fname);
% UIWAIT makes showplot wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --------------------------------------------------------------------
function uipushtool2_ClickedCallback(hObject, eventdata, handles)
% hObject handle to uipushtool2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% obtain BER file
[fname, pname] = uigetfile({'BER*.mat;MSE_db*.mat'},'Choose BER file');
if fname
if strcmp(fname(1:3),'BER')
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file='BER';
handles.BER = BER;
elseif strcmp(fname(1:6),'MSE_db')
try
load(strcat(pname, fname));
catch
error('MSE data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(9:length(fname))));
catch
error('CONF data could not be found.')
end
handles.file=fname(1:8);
if strcmp(handles.file,'MSE_db_a')
handles.MSE_db = MSE_db_a;
elseif strcmp(handles.file,'MSE_db_f')
handles.MSE_db = MSE_db_f;
elseif strcmp(handles.file,'MSE_db_r')
handles.MSE_db = MSE_db_r;
end
elseif strcmp(fname(1:3),'MSE')
%not implemented yet.
else
error('Invalid file.')
end
new_data_process(hObject,handles,handles.file,conf,fname);
end
% --- Outputs from this function are returned to the command line.
function varargout = showplot_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 togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
update_plot(handles)
% --- Executes on button press in togglebutton2.
function togglebutton2_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton2
update_plot(handles)
% --- Executes on button press in togglebutton3.
function togglebutton3_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton3
update_plot(handles)
% --- Executes on button press in togglebutton4.
function togglebutton4_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton4
update_plot(handles)
% --- Executes on button press in togglebutton20.
function togglebutton20_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton20 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton20
update_plot(handles)
% --- Executes on button press in togglebutton21.
function togglebutton21_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton21 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton21
update_plot(handles)
% --- Executes on button press in togglebutton22.
function togglebutton22_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton22 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton22
update_plot(handles)
% --- Executes on button press in togglebutton23.
function togglebutton23_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton23 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton23
update_plot(handles)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_mod
if strcmp(get(i,'Enable'),'on')
set(i,'Value',0);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_mod
if strcmp(get(i,'Enable'),'on')
set(i,'Value',1);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_M
if strcmp(get(i,'Enable'),'on')
set(i,'Value',0);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_M
if strcmp(get(i,'Enable'),'on')
set(i,'Value',1);
end
end
update_plot(handles);
% --- Executes on button press in togglebutton13.
function togglebutton13_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton13 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton13
update_plot(handles)
% --- Executes on button press in togglebutton14.
function togglebutton14_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton14 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton14
update_plot(handles)
% --- Executes on button press in togglebutton15.
function togglebutton15_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton15 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton15
update_plot(handles)
% --- Executes on button press in togglebutton16.
function togglebutton16_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton16 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton16
update_plot(handles)
% --- Executes on button press in togglebutton17.
function togglebutton17_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton17 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton17
update_plot(handles)
% --- Executes on button press in togglebutton18.
function togglebutton18_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton18 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton18
update_plot(handles)
% --- Executes on button press in togglebutton19.
function togglebutton19_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton19 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton19
update_plot(handles)
% --- Executes on button press in togglebutton24.
function togglebutton24_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton24 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton24
update_plot(handles)
% --- Executes on button press in togglebutton25.
function togglebutton25_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton25 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton25
update_plot(handles);
% --- Executes on button press in togglebutton26.
function togglebutton26_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton26 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton26
update_plot(handles);
% --- Executes on button press in togglebutton27.
function togglebutton27_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton27 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton27
update_plot(handles);
% --- Executes on button press in togglebutton28.
function togglebutton28_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton28 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton28
update_plot(handles);
% --------------------------------------------------------------------
function uipushtool3_ClickedCallback(hObject, eventdata, handles)
% hObject handle to uipushtool3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
msgbox(strcat(evalc('handles.conf'),sprintf('\n'),evalc('handles.conf.resp'),sprintf('\nexplanation:\n'),handles.conf.explanation))
% --------------------------------------------------------------------
function uipushtool4_ClickedCallback(hObject, eventdata, handles)
% hObject handle to uipushtool4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
figu=handles.figure1;
% c1=clock;
name=get(handles.figure1,'Name');
savefig(figu,name(1:end-4));
function update_plot(handles)
% toggle1: M=4
% toggle13-19: M=8,16,32,64,128,256,512
% toggle20-24: 4-16-64-128-256-QAM
% plot data
% line modifiers
markers= ['+' 'o' '*' 's' '^'];
lines = ['-' ':' '-.' '--'];
colors = ['r' 'g' 'b' 'm' 'k'];
combined = ['--g' '-m' '--b' '-r' '--k' '-g' '--m' '-b' '--r' '-k'];
%colors and styles
flag_at_least_one = false;
%plot OFDM data if desired
%QAM data
if get(handles.togglebutton25,'Value')
for zx=handles.CONF_OFDM_QAM.mod_sch
modifier = strcat('--k',markers(mod(find(handles.all_mod==zx)-1,5)+1));
% find(handles.CONF_OFDM_QAM.mod_sch==zx)
% handles.CONF_OFDM_QAM.SNR_val
semilogy(handles.CONF_OFDM_QAM.SNR_val,handles.BER_OFDM_QAM(find(handles.CONF_OFDM_QAM.mod_sch==zx),:)...
,modifier,'LineWidth',2,'MarkerSize',8);
flag_at_least_one = true;
hold on
grid on
end
end
%PSK data
if get(handles.togglebutton26,'Value')
for zx=handles.CONF_OFDM_PSK.mod_sch
% modifier = strcat('--k',markers(mod(find(handles.all_mod==zx)-1,5)+1));
% find(handles.CONF_OFDM_QAM.mod_sch==zx)
% handles.CONF_OFDM_QAM.SNR_val
semilogy(handles.CONF_OFDM_PSK.SNR_val,handles.BER_OFDM_PSK(find(handles.CONF_OFDM_PSK.mod_sch==zx),:)...
,'-.p','LineWidth',2,'MarkerSize',8);
flag_at_least_one = true;
hold on
grid on
end
end
for qw=handles.conf(1).M_val
for zx=handles.conf(1).mod_sch
if strcmp(handles.file,'BER')
if get(handles.handles_M(log2(qw)-1),'Value')==1 && get(handles.handles_mod(find(handles.all_mod==zx)),'Value')==1 && ...
strcmp(get(handles.handles_M(log2(qw)-1),'Enable'),'on') && strcmp(get(handles.handles_mod(find(handles.all_mod==zx)),'Enable'),'on')
% handles.conf(1).SNR_val
% disp('annen')
% handles.data(length(handles.conf(1).mod_sch)*(find(handles.conf(1).M_val==qw)-1)+find(handles.conf(1).mod_sch==zx))
modifier = strcat(lines(mod(log2(qw)-1-1,2)+1),colors(mod(log2(qw)-1,5)+1),markers(mod(find(handles.all_mod==zx)-1,5)+1));
semilogy(handles.conf(1).SNR_val,handles.data(length(handles.conf(1).mod_sch)*(find(handles.conf(1).M_val==qw)-1)+find(handles.conf(1).mod_sch==zx),:),modifier,...
'LineWidth',1.5,'MarkerSize',8);
flag_at_least_one = true;
hold on
grid on
end
ylabel('BER');
else
if get(handles.handles_M(log2(qw)-1),'Value')==1 && get(handles.handles_mod(find(handles.all_mod==zx)),'Value')==1 && ...
strcmp(get(handles.handles_M(log2(qw)-1),'Enable'),'on') && strcmp(get(handles.handles_mod(find(handles.all_mod==zx)),'Enable'),'on')
% handles.conf(1).SNR_val
% disp('annen')
% handles.data(length(handles.conf(1).mod_sch)*(find(handles.conf(1).M_val==qw)-1)+find(handles.conf(1).mod_sch==zx))
modifier = strcat(lines(mod(log2(qw)-1-1,2)+1),colors(mod(log2(qw)-1,5)+1),markers(mod(find(handles.all_mod==zx)-1,5)+1));
plot(handles.conf(1).SNR_val,handles.data(length(handles.conf(1).mod_sch)*(find(handles.conf(1).M_val==qw)-1)+find(handles.conf(1).mod_sch==zx),:),modifier,...
'LineWidth',1.5,'MarkerSize',8);
flag_at_least_one = true;
hold on
grid on
end
ylabel('NMSE');
end
end
end
xlabel('SNR (dB)');
hold off
if ~flag_at_least_one
semilogy(1,1);
end
function new_data_process(hObject,handles,file,conf,fname)
handles.conf = conf;
%OFDM data retrieval
os = computer; %os we are running showplot on.
if isempty(findstr(os,'LNX'))
% on windows
try
load('BER_archive\BER_OFDM_QAM.mat');
try
load('BER_archive\CONF_OFDM_QAM.mat');
catch
error('CONF_OFDM_QAM data could not be found.')
end
set(handles.togglebutton25,'Enable','on','Value',0);
handles.BER_OFDM_QAM=BER_OFDM_QAM;
handles.CONF_OFDM_QAM=CONF_OFDM_QAM;
catch
warning('BER_OFDM_QAM could not be loaded. This option will be disabled.')
set(handles.togglebutton25,'Enable','off','Value',0);
end
try
load('BER_archive\BER_OFDM_PSK.mat');
try
load('BER_archive\CONF_OFDM_PSK.mat');
catch
error('CONF_OFDM_PSK data could not be found.')
end
set(handles.togglebutton25,'Enable','on','Value',0);
handles.BER_OFDM_PSK=BER_OFDM_PSK;
handles.CONF_OFDM_PSK=CONF_OFDM_PSK;
catch
warning('BER_OFDM_PSK could not be loaded. This option will be disabled.')
set(handles.togglebutton26,'Enable','off','Value',0);
end
else
%on linux
try
load('BER_archive/BER_OFDM_QAM.mat');
try
load('BER_archive/CONF_OFDM_QAM.mat');
catch
error('CONF_OFDM_QAM data could not be found.')
end
set(handles.togglebutton25,'Enable','on','Value',0);
handles.BER_OFDM_QAM=BER_OFDM_QAM;
handles.CONF_OFDM_QAM=CONF_OFDM_QAM;
catch
warning('BER_OFDM_QAM could not be loaded. This option will be disabled.')
set(handles.togglebutton25,'Enable','off','Value',0);
end
try
load('BER_archive/BER_OFDM_PSK.mat');
try
load('BER_archive/CONF_OFDM_PSK.mat');
catch
error('CONF_OFDM_PSK data could not be found.')
end
set(handles.togglebutton25,'Enable','on','Value',0);
handles.BER_OFDM_PSK=BER_OFDM_PSK;
handles.CONF_OFDM_PSK=CONF_OFDM_PSK;
catch
warning('BER_OFDM_PSK could not be loaded. This option will be disabled.')
set(handles.togglebutton26,'Enable','off','Value',0);
end
end
set(handles.figure1,'Name',fname)
% toggle button handles belonging to different M values
handles.handles_M =[handles.togglebutton1,handles.togglebutton13,...
handles.togglebutton14,handles.togglebutton15,handles.togglebutton16,...
handles.togglebutton17, handles.togglebutton18,handles.togglebutton19,...
handles.togglebutton27, handles.togglebutton28];
% toggle button handles belonging to different modulation values
handles.handles_mod=[handles.togglebutton20,handles.togglebutton21, ...
handles.togglebutton22, handles.togglebutton23, handles.togglebutton24];
handles.all_mod =[4 16 64 128 256];
handles.all_M =[4 8 16 32 64 128 256 512 1024 2048];
%active buttons
for i=handles.all_M
if ~ismember(i, handles.conf(1).M_val)
set(handles.handles_M(log2(i)-1),'Value',0,'Enable','off');
else
set(handles.handles_M(log2(i)-1),'Value',1,'Enable','on');
end
end
for i=handles.all_mod
if ~ismember(i, handles.conf(1).mod_sch)
set(handles.handles_mod(find(handles.all_mod==i)),'Value',0,'Enable','off');
else
set(handles.handles_mod(find(handles.all_mod==i)),'Value',1,'Enable','on');
end
end
% retrieve data
% data contains BER for (16) different SNR values and oriented in following
% fashion:
% M=4/4-QAM/SNR=0 M=4/4-QAM/SNR=1 M=4/4-QAM/SNR=2 ..........
% M=4/16-QAM/SNR=0 ...... ...... ...... ...... ......
% ...... ...... ...... ...... ...... ...... ......
% ...... ...... ...... ...... ...... ...... ......
% M=512/128-QAM/SNR=0............................M=512/128-QAM/SNR=15
handles.data=zeros(length(handles.conf(1).M_val)*length(handles.conf(1).mod_sch),length(handles.conf(1).SNR_val));
for qw=1:length(handles.conf(1).M_val)
for zx=1:length(handles.conf(1).mod_sch)
if strcmp(file,'BER')
handles.data(length(handles.conf(1).mod_sch)*(qw-1)+zx,:)=...
handles.BER(log2(handles.conf(1).M_val(qw))-1,...
find(handles.all_mod==handles.conf(1).mod_sch(zx)),...
1:length(handles.conf(1).SNR_val));
else
handles.data(length(handles.conf(1).mod_sch)*(qw-1)+zx,:)=...
handles.MSE_db(log2(handles.conf(1).M_val(qw))-1,...
find(handles.all_mod==handles.conf(1).mod_sch(zx)),...
1:length(handles.conf(1).SNR_val));
end
end
end
% Update handles structure
guidata(hObject, handles);
%initial plot
pushbutton2_Callback(hObject, 0, handles)
pushbutton4_Callback(hObject, 0, handles)
update_plot(handles) |
github | mohammadzainabbas/Digital-Communication-master | LTE_channels.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/tests/LTE_channels.m | 1,069 | utf_8 | 214e89d4dfc04fcfdf1e73088ca803f8 |
function [ci_imp_out] = LTE_channels (type,bandwidth)
% function [delay_a pow_a] = LTE_channels (type,bandwidth)
%LTE channels
% % EPA = 0;
% % ETU = 1;
% % EVA = 0;
% %
bandw = bandwidth; % 5MHz
if type == 'EPA' % Low selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 70 80 110 190 410]*1e-9;
pow_a = [0 -1 -2 -3 -8 -17.2 -20.7];
elseif type == 'EVA' % Moderate selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 150 310 370 710 1090 1730 2510 ]*1e-9;
pow_a = [0 -1.5 -1.4 -3.6 -0.6 -9.1 -7.0 -12-0 -16.9];
elseif type == 'ETU' % High selectivity
ci_imp = zeros(1,127);
delay_a = [0 50 120 200 230 500 1600 2300 5000]*1e-9;
pow_a = [-1 -1.0 -1.0 0 0 0 -3 -5 -7];
else
error('Invalid channel profile selection');
end
pow_a_lin = 10.^(pow_a./10);
%
% %Making the sampled channel
tss = 1./bandw;
pos_a = round(delay_a./tss);
c_imp_sampled = [];
for i = min(pos_a):max(pos_a)
c_imp_sampled(i+1) = sum(pow_a_lin(pos_a==i));
end
ci_imp_out = sqrt((c_imp_sampled.^2./sum(c_imp_sampled.^2)));
|
github | mohammadzainabbas/Digital-Communication-master | simpleAM.m | .m | Digital-Communication-master/FBMC-master/00_FBMC/tests/simpleGUI/simpleAM.m | 15,132 | utf_8 | 9b0e04b34858cffdc6f36b449a8fe965 | function varargout = simpleAM(varargin)
% simpleAM MATLAB code for simpleAM.fig
% simpleAM, by itself, creates a new simpleAM or raises the existing
% singleton*.
%
% H = simpleAM returns the handle to a new simpleAM or the handle to
% the existing singleton*.
%
% simpleAM('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in simpleAM.M with the given input arguments.
%
% simpleAM('Property','Value',...) creates a new simpleAM or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before simpleAM_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to simpleAM_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 simpleAM
% Last Modified by GUIDE v2.5 13-Jan-2014 14:13:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @simpleAM_OpeningFcn, ...
'gui_OutputFcn', @simpleAM_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 simpleAM is made visible.
function simpleAM_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 simpleAM (see VARARGIN)
% Choose default command line output for simpleAM
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
%create data
tmin=0;
tmax=0.01;
increment=0.000001;
t=tmin:increment:tmax;
A=1;
B=4;
display_offset = 1;
handles.carrier = A.*cos(2*pi*2000.*t+pi/20);
handles.message = B.*cos(2*pi*300.*t+pi/10);
modulated = (1+handles.message).*handles.carrier;
handles.current_data = modulated;
plot(t,handles.current_data,'LineWidth',1.2);
hold all
plot(t,A.*handles.message+A,'r--');
plot(t,-A-A.*handles.message,'g--');
axis([tmin, tmax, -((B+1)*A)-display_offset, ((B+1)*A)+display_offset]);
hold off
% UIWAIT makes simpleAM wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = simpleAM_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit2_Callback(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit2 as text
% str2double(get(hObject,'String')) returns contents of edit2 as a double
% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit3_Callback(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit3 as text
% str2double(get(hObject,'String')) returns contents of edit3 as a double
% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit4_Callback(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit4 as text
% str2double(get(hObject,'String')) returns contents of edit4 as a double
% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit5_Callback(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit5 as text
% str2double(get(hObject,'String')) returns contents of edit5 as a double
% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit6_Callback(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit6 as text
% str2double(get(hObject,'String')) returns contents of edit6 as a double
% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit7_Callback(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit7 as text
% str2double(get(hObject,'String')) returns contents of edit7 as a double
% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit7 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit8_Callback(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit8 as text
% str2double(get(hObject,'String')) returns contents of edit8 as a double
% --- Executes during object creation, after setting all properties.
function edit8_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit8 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
tmin=str2double(get(handles.edit10,'String'));
tmax=str2double(get(handles.edit12,'String'));
increment=str2double(get(handles.edit11,'String'));
t=tmin:increment:tmax;
A=str2double(get(handles.edit3,'String'));
fc=str2double(get(handles.edit4,'String'));
phic=str2num(get(handles.edit5,'String'));
B=str2double(get(handles.edit6,'String'));
fm=str2double(get(handles.edit7,'String'));
phim=str2num(get(handles.edit8,'String'));
display_offset = 1;
handles.carrier = A.*cos(2*pi*fc.*t+phic);
handles.message = B.*cos(2*pi*fm.*t+phim);
%modulated = (handles.message).*handles.carrier;
modulated = (1+handles.message).*handles.carrier;
handles.current_data = modulated;
plot(t,handles.current_data,'LineWidth',1.2);
hold all
plot(t,A.*handles.message+A,'r--');
plot(t,-A-A.*handles.message,'g--');
axis([tmin, tmax, -((B+1)*A)-display_offset, ((B+1)*A)+display_offset]);
hold off
function edit11_Callback(hObject, eventdata, handles)
% hObject handle to edit11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit11 as text
% str2double(get(hObject,'String')) returns contents of edit11 as a double
% --- Executes during object creation, after setting all properties.
function edit11_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit11 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit10_Callback(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit10 as text
% str2double(get(hObject,'String')) returns contents of edit10 as a double
% --- Executes during object creation, after setting all properties.
function edit10_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit10 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit12_Callback(hObject, eventdata, handles)
% hObject handle to edit12 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit12 as text
% str2double(get(hObject,'String')) returns contents of edit12 as a double
% --- Executes during object creation, after setting all properties.
function edit12_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit12 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on key press with focus on pushbutton1 and none of its controls.
function pushbutton1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata structure with the following fields (see UICONTROL)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
|
github | mohammadzainabbas/Digital-Communication-master | LTE_channels2.m | .m | Digital-Communication-master/FBMC-master/01_OFDM/LTE_channels2.m | 1,092 | utf_8 | dfa01f96b571c56d572b9f530309cf89 |
% function [ci_imp_out] = LTE_channels (type,bandwidth)
function [delay_a pow_a] = LTE_channels2 (type,bandwidth)
%LTE channels
% % EPA = 0;
% % ETU = 1;
% % EVA = 0;
% %
bandw = bandwidth; % 5MHz
if type == 'EPA' % Low selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 70 80 110 190 410]*1e-9;
pow_a = [0 -1 -2 -3 -8 -17.2 -20.7];
elseif type == 'EVA' % Moderate selectivity
ci_imp = zeros(1,127);
delay_a = [0 30 150 310 370 710 1090 1730 2510 ]*1e-9;
pow_a = [0 -1.5 -1.4 -3.6 -0.6 -9.1 -7.0 -12-0 -16.9];
elseif type == 'ETU' % High selectivity
ci_imp = zeros(1,127);
delay_a = [0 50 120 200 230 500 1600 2300 5000]*1e-9;
pow_a = [-1 -1.0 -1.0 0 0 0 -3 -5 -7];
else
error('Invalid channel profile selection');
end
%
% pow_a_lin = 10.^(pow_a./10);
% %
% % %Making the sampled channel
% tss = 1./bandw;
% pos_a = round(delay_a./tss);
% c_imp_sampled = [];
% for i = min(pos_a):max(pos_a)
% c_imp_sampled(i+1) = sum(pow_a_lin(pos_a==i));
% end
% ci_imp_out = sqrt((c_imp_sampled.^2./sum(c_imp_sampled.^2)));
|
github | mohammadzainabbas/Digital-Communication-master | LTE_channels.m | .m | Digital-Communication-master/FBMC-master/01_OFDM/LTE_channels.m | 1,159 | utf_8 | 6cd1bd3a74ef171521fd74d48d312da8 |
function [ci_imp_out] = LTE_channels (type,bandwidth)
% function [delay_a pow_a] = LTE_channels (type,bandwidth)
%LTE channels
% % EPA = 0;
% % ETU = 1;
% % EVA = 0;
% %
bandw = bandwidth; % 5MHz
if type == 'EPA' % Low selectivity
% disp('epa')
ci_imp = zeros(1,127);
delay_a = [0 30 70 80 110 190 410]*1e-9;
pow_a = [0 -1 -2 -3 -8 -17.2 -20.7];
elseif type == 'EVA' % Moderate selectivity
% disp('eva')
ci_imp = zeros(1,127);
delay_a = [0 30 150 310 370 710 1090 1730 2510 ]*1e-9;
pow_a = [0 -1.5 -1.4 -3.6 -0.6 -9.1 -7.0 -12-0 -16.9];
elseif type == 'ETU' % High selectivity
% disp('etu')
ci_imp = zeros(1,127);
delay_a = [0 50 120 200 230 500 1600 2300 5000]*1e-9;
pow_a = [-1 -1.0 -1.0 0 0 0 -3 -5 -7];
else
error('Invalid channel profile selection');
end
pow_a_lin = 10.^(pow_a./10);
%
% %Making the sampled channel
tss = 1./bandw;
pos_a = round(delay_a./tss);
c_imp_sampled = [];
for i = min(pos_a):max(pos_a)
c_imp_sampled(i+1) = sum(pow_a_lin(pos_a==i));
end
ci_imp_out = sqrt((c_imp_sampled.^2./sum(c_imp_sampled.^2)));
% figure
% plot(ci_imp_out);
|
github | mohammadzainabbas/Digital-Communication-master | showplot.m | .m | Digital-Communication-master/FBMC-master/01_OFDM/showplot.m | 15,617 | utf_8 | cd7a44aa3364963c386c214a0f538843 | function varargout = showplot(varargin)
% SHOWPLOT MATLAB code for showplot.fig
% SHOWPLOT, by itself, creates a new SHOWPLOT or raises the existing
% singleton*.
%
% H = SHOWPLOT returns the handle to a new SHOWPLOT or the handle to
% the existing singleton*.
%
% SHOWPLOT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SHOWPLOT.M with the given input arguments.
%
% SHOWPLOT('Property','Value',...) creates a new SHOWPLOT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before showplot_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to showplot_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 showplot
% Last Modified by GUIDE v2.5 23-Mar-2014 17:29:52
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @showplot_OpeningFcn, ...
'gui_OutputFcn', @showplot_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 showplot is made visible.
function showplot_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 showplot (see VARARGIN)
% Choose default command line output for showplot
handles.output = hObject;
% obtain BER file
[fname, pname] = uigetfile({'BER*.mat'},'Choose BER file');
if fname
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
else
warning('A BER file should be selected');
[fname, pname] = uigetfile({'BER*.mat'},'Choose BER file');
if ~fname
error('Could not reach a BER file');
else
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
end
end
new_data_process(hObject,handles,BER,conf);
% UIWAIT makes showplot wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = showplot_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 togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
update_plot(handles)
% --- Executes on button press in togglebutton2.
function togglebutton2_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton2
update_plot(handles)
% --- Executes on button press in togglebutton3.
function togglebutton3_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton3
update_plot(handles)
% --- Executes on button press in togglebutton4.
function togglebutton4_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton4
update_plot(handles)
% --- Executes on button press in togglebutton20.
function togglebutton20_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton20 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton20
update_plot(handles)
% --- Executes on button press in togglebutton21.
function togglebutton21_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton21 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton21
update_plot(handles)
% --- Executes on button press in togglebutton22.
function togglebutton22_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton22 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton22
update_plot(handles)
% --- Executes on button press in togglebutton23.
function togglebutton23_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton23 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton23
update_plot(handles)
% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_mod
if strcmp(get(i,'Enable'),'on')
set(i,'Value',0);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_mod
if strcmp(get(i,'Enable'),'on')
set(i,'Value',1);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_M
if strcmp(get(i,'Enable'),'on')
set(i,'Value',0);
end
end
update_plot(handles);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
for i=handles.handles_M
if strcmp(get(i,'Enable'),'on')
set(i,'Value',1);
end
end
update_plot(handles);
% --- Executes on button press in togglebutton13.
function togglebutton13_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton13 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton13
update_plot(handles)
% --- Executes on button press in togglebutton14.
function togglebutton14_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton14 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton14
update_plot(handles)
% --- Executes on button press in togglebutton15.
function togglebutton15_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton15 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton15
update_plot(handles)
% --- Executes on button press in togglebutton16.
function togglebutton16_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton16 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton16
update_plot(handles)
% --- Executes on button press in togglebutton17.
function togglebutton17_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton17 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton17
update_plot(handles)
% --- Executes on button press in togglebutton18.
function togglebutton18_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton18 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton18
update_plot(handles)
% --- Executes on button press in togglebutton19.
function togglebutton19_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton19 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton19
update_plot(handles)
% --- Executes on button press in togglebutton24.
function togglebutton24_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton24 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton24
update_plot(handles)
function update_plot(handles)
% toggle1: M=4
% toggle13-19: M=8,16,32,64,128,256,512
% toggle20-24: 4-16-64-128-256-QAM
% plot data
% line modifiers
markers= ['+' 'o' '*' 's' '^'];
lines = ['-' ':' '-.' '--'];
colors = ['r' 'g' 'b' 'm' 'k'];
combined = ['--g' '-m' '--b' '-r' '--k' '-g' '--m' '-b' '--r' '-k'];
%colors and styles
flag_at_least_one = false;
for qw=handles.conf(1).M_val
for zx=handles.conf(1).mod_sch
if get(handles.handles_M(log2(qw)-1),'Value')==1 && get(handles.handles_mod(find(handles.all_mod==zx)),'Value')==1 && ...
strcmp(get(handles.handles_M(log2(qw)-1),'Enable'),'on') && strcmp(get(handles.handles_mod(find(handles.all_mod==zx)),'Enable'),'on')
% disp(sprintf('qw%d zx%d',qw,zx))
modifier = strcat(lines(mod(log2(qw)-1-1,2)+1),colors(mod(log2(qw)-1,5)+1),markers(mod(find(handles.all_mod==zx)-1,5)+1));
semilogy(handles.conf(1).SNR_val,handles.data(length(handles.conf(1).mod_sch)*(find(handles.conf(1).M_val==qw)-1)+find(handles.conf(1).mod_sch==zx),:),modifier,...
'LineWidth',1.5,'MarkerSize',8);
flag_at_least_one = true;
hold on
grid on
end
end
end
xlabel('SNR (dB)');
ylabel('BER');
hold off
if ~flag_at_least_one
semilogy(1,1);
end
% --------------------------------------------------------------------
function uipushtool2_ClickedCallback(hObject, eventdata, handles)
% hObject handle to uipushtool2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% obtain BER file
[fname, pname] = uigetfile({'BER*.mat'},'Choose BER file');
if fname
try
load(strcat(pname, fname));
catch
error('BER data could not be loaded.')
end
try
load(strcat(pname,'CONF',fname(4:length(fname))));
catch
error('CONF data could not be found.')
end
new_data_process(hObject,handles,BER,conf);
end
function new_data_process(hObject,handles,BER,conf)
handles.BER = BER;
handles.conf = conf;
% toggle button handles belonging to different M values
handles.handles_M =[handles.togglebutton1,handles.togglebutton13,...
handles.togglebutton14,handles.togglebutton15,handles.togglebutton16,...
handles.togglebutton17, handles.togglebutton18,handles.togglebutton19];
% toggle button handles belonging to different modulation values
handles.handles_mod=[handles.togglebutton20,handles.togglebutton21, ...
handles.togglebutton22, handles.togglebutton23, handles.togglebutton24];
handles.all_mod =[4 16 64 128 256];
handles.all_M =[4 8 16 32 64 128 256 512];
%active buttons
for i=handles.all_M
if ~ismember(i, handles.conf(1).M_val)
set(handles.handles_M(log2(i)-1),'Value',0,'Enable','off');
else
set(handles.handles_M(log2(i)-1),'Value',1,'Enable','on');
end
end
for i=handles.all_mod
if ~ismember(i, handles.conf(1).mod_sch)
set(handles.handles_mod(find(handles.all_mod==i)),'Value',0,'Enable','off');
else
set(handles.handles_mod(find(handles.all_mod==i)),'Value',1,'Enable','on');
end
end
% retrieve data
% data contains BER for (16) different SNR values and oriented in following
% fashion:
% M=4/4-QAM/SNR=0 M=4/4-QAM/SNR=1 M=4/4-QAM/SNR=2 ..........
% M=4/16-QAM/SNR=0 ...... ...... ...... ...... ......
% ...... ...... ...... ...... ...... ...... ......
% ...... ...... ...... ...... ...... ...... ......
% M=512/128-QAM/SNR=0............................M=512/128-QAM/SNR=15
handles.data=zeros(length(handles.conf(1).M_val)*length(handles.conf(1).mod_sch),length(handles.conf(1).SNR_val));
for qw=1:length(handles.conf(1).M_val)
for zx=1:length(handles.conf(1).mod_sch)
handles.data(length(handles.conf(1).mod_sch)*(qw-1)+zx,:)=...
handles.BER(log2(handles.conf(1).M_val(qw))-1,...
find(handles.all_mod==handles.conf(1).mod_sch(zx)),...
handles.conf(1).SNR_val+1);
end
end
% Update handles structure
guidata(hObject, handles);
%initial plot
pushbutton2_Callback(hObject, 0, handles)
pushbutton4_Callback(hObject, 0, handles)
update_plot(handles)
|
github | mohammadzainabbas/Digital-Communication-master | main.m | .m | Digital-Communication-master/Lab 02/main.m | 1,488 | utf_8 | 8489ed6eda6ec2344e9a48a58a36e4e1 | function main()
%Task No. 01
%Generate 2 random signal
[x1,size1] = random_signal();
[x2,size2] = random_signal();
%Calculate pdfs of both
[pdf1, bins1] = PDF(x1);
[pdf2, bins2] = PDF(x2);
%Rearranging x-axis of both so that mean appears at 0
x1_axis = min(x1):(max(x1)-min(x1))/(bins1):max(x1);
x1_axis = x1_axis(1:size1); %coz no. of bins = length - 1
x2_axis = min(x2):(max(x2)-min(x2))/(bins2):max(x2);
x2_axis = x2_axis(1:size2);
% %plot both signals
% figure
% subplot(2,1,1)
% bar(x1_axis,pdf1);
% subplot(2,1,2)
% bar(x2_axis,pdf2);
%Task No. 02
%We already have both the signals x1 and x2, so don't need to generate them
%Calculating mean of both signals
mean1 = sum((x1) .* pdf1);
mean2 = sum((x2) .* pdf2);
%Calculating variance of both signals
variance1 = sum(power((x1 - mean1),2)/(length(x1)))
variance2 = sum(power((x2 - mean2),2)/(length(x2)))
% %Ploting PDFs of both
% figure
% subplot(2,1,1)
% bar(x1_axis,pdf1);
% subplot(2,1,2)
% bar(x2_axis,pdf2);
%Chaning mean of signal x2 from 0 to 300 and -300
new1_x2 = x2 + 300;
new2_x2 = x2 - 300;
figure
subplot(3,1,1)
bar(x2_axis,pdf2)
subplot(3,1,2)
bar(x2_axis,PDF(new1_x2)[1])
subplot(3,1,3)
bar(x2_axis,PDF(new2_x2)[1])
end
function [x, size] = random_signal()
size = input('Enter signal size: ');
x = randn(1,size);
end
function [pdf, bins] = PDF(x)
bins = input('Enter number of bins: ');
pdf = hist(x,bins)/(length(x));
end |
github | mohammadzainabbas/Digital-Communication-master | FBMC.m | .m | Digital-Communication-master/FBMC/+Modulation/FBMC.m | 41,490 | utf_8 | 9ce6c2fc7c3c9554a06c7a9e494abba9 | classdef FBMC < handle
% =====================================================================
% This MATLAB class represents an implementation of FBMC. The
% modulation parameters are initialized by the class contructor.
% The modulation of data symbols x and the demodulation of the
% received samples r is then performed by the methods ".Modulation(x)"
% and ".Demodulation(r)".
% Additionally, there exist some other useful methods, such as,
% ".PlotPowerSpectralDensity" or ".GetTXMatrix".
% =====================================================================
% Ronald Nissel, [email protected]
% (c) 2017 by Institute of Telecommunications, TU Wien
% www.nt.tuwien.ac.at
% =====================================================================
properties (SetAccess = private)
Method % defines the modulation method (prototype filter)
Nr % for dimensionless parameters
PHY % for parameters with physical interpretation
PrototypeFilter % for prototype filter parameters
Implementation % implmentation relevent parameters
end
methods
% Class constructor, define default values.
function obj = FBMC(varargin)
% Initialize parameters, set default values
if numel(varargin) == 10
obj.Nr.Subcarriers = varargin{1}; % Number of subcarriers
obj.Nr.MCSymbols = varargin{2}; % Number FBMC symbols in time
obj.PHY.SubcarrierSpacing = varargin{3}; % Subcarrier spacing (Hz)
obj.PHY.SamplingRate = varargin{4}; % Sampling rate (Samples/s)
obj.PHY.IntermediateFrequency = varargin{5}; % Intermediate frequency of the first subcarrier (Hz). Must be a multiple of the subcarrier spacing
obj.PHY.TransmitRealSignal = varargin{6}; % Transmit real valued signal (sampling theorem must be fulfilled!)
obj.Method = varargin{7}; % Prototype filter (Hermite, PHYDYAS, RRC) and OQAM or QAM. The data rate of QAM is reduced by a factor of two compared to OQAM, but robustness in doubly-selective channels is inceased
obj.PrototypeFilter.OverlappingFactor = varargin{8}; % Overlapping factor (also determines oversampling in the frequency domain)
obj.Implementation.InitialPhaseShift = varargin{9}; % Initial phase shift
obj.Implementation.UsePolyphase = varargin{10}; % Efficient IFFT implementation, true or false
elseif numel(varargin) == 0
% Default Values (can later be changed using FBMC.Set...)
obj.Nr.Subcarriers = 12;
obj.Nr.MCSymbols = 30;
obj.PHY.SubcarrierSpacing = 15e3;
obj.PHY.SamplingRate = obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing;
obj.PHY.IntermediateFrequency = 0;
obj.PHY.TransmitRealSignal = false;
obj.Method = 'Hermite-OQAM';
obj.PrototypeFilter.OverlappingFactor = 8;
obj.Implementation.InitialPhaseShift = 0;
obj.Implementation.UsePolyphase = true;
else
error('Number of input variables must be either 0 (default values) or 10');
end
% calculate and set all dependent parameters
obj.SetDependentParameters();
end
function SetDependentParameters(obj)
% method that sets all parameters which are dependent on other parameters
% Check Parameters
if mod(obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing),1)~=0
obj.PHY.SubcarrierSpacing=obj.PHY.SamplingRate/(2*round(obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing)));
disp('Sampling Rate divided by (Subcarrier spacing times 2) must be must be an integer!');
disp(['Therefore, the subcarrier spacing is set to: ' int2str(obj.PHY.SubcarrierSpacing) 'Hz']);
end
if mod(obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing,1)~=0
obj.PHY.IntermediateFrequency = round(obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing)*obj.PHY.SubcarrierSpacing;
disp('The intermediate frequency must be a multiple of the subcarrier spacing!');
disp(['Therefore, the intermediate frequency is set to ' int2str(obj.PHY.IntermediateFrequency) 'Hz']);
end
if (obj.PHY.SamplingRate<obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing)
error('Sampling Rate must be higher: at least Number of Subcarriers times Subcarrier Spacing');
end
% dependent parameters
obj.PHY.dt = 1/obj.PHY.SamplingRate;
% Different Prototype Filters and OQAM or QAM
switch obj.Method
case 'Hermite-OQAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing);
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_Hermite(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2);
case 'Hermite-QAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2;
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_Hermite(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor);
case 'Rectangle-QAM' % OFDM without cyclic prefix
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing);
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*2;
TimeDomain = zeros(2*obj.PrototypeFilter.OverlappingFactor*obj.Implementation.TimeSpacing,1);
TimeDomain(1:obj.Implementation.TimeSpacing) = 1/sqrt(obj.PHY.TimeSpacing);
TimeDomain = circshift(TimeDomain,length(TimeDomain)/2-obj.Implementation.TimeSpacing/2);
obj.PrototypeFilter.TimeDomain = TimeDomain;
case 'RRC-OQAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing);
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_RootRaisedCosine(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2);
case 'RRC-QAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2;
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_RootRaisedCosine(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor);
case 'PHYDYAS-OQAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(2*obj.PHY.SubcarrierSpacing);
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_PHYDYAS(obj.PHY.TimeSpacing*2,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor/2);
case 'PHYDYAS-QAM'
obj.Implementation.TimeSpacing = obj.PHY.SamplingRate/(obj.PHY.SubcarrierSpacing)*2;
obj.PHY.TimeSpacing = obj.Implementation.TimeSpacing*obj.PHY.dt;
obj.Implementation.FrequencySpacing = obj.PrototypeFilter.OverlappingFactor*4;
obj.PrototypeFilter.TimeDomain = PrototypeFilter_PHYDYAS(obj.PHY.TimeSpacing,obj.PHY.dt,obj.PrototypeFilter.OverlappingFactor);
otherwise
error(['Method (prototype filter) "' obj.Method '" is not supported']);
end
obj.Nr.SamplesPrototypeFilter = length(obj.PrototypeFilter.TimeDomain);
obj.Nr.SamplesTotal = obj.Nr.SamplesPrototypeFilter+(obj.Nr.MCSymbols-1)*obj.Implementation.TimeSpacing;
% We assume a symmetric filter (=> real) and set small values to zero (=> lower computational complexity)
PrototypefilterFFT = obj.PHY.dt*real(fft(circshift(obj.PrototypeFilter.TimeDomain,obj.Nr.SamplesPrototypeFilter/2)));
PrototypefilterFFT = obj.PHY.dt*(fft(circshift(obj.PrototypeFilter.TimeDomain,obj.Nr.SamplesPrototypeFilter/2)));
PrototypefilterFFT(abs(PrototypefilterFFT)./PrototypefilterFFT(1)<10^-14)=0;
obj.PrototypeFilter.FrequencyDomain = PrototypefilterFFT;
% Prepare paramters for an efficient implementation
% Phase shift to guarentee that the interference is purely imaginary
[k,l] = meshgrid(0:obj.Nr.MCSymbols-1,0:obj.Nr.Subcarriers-1);
obj.Implementation.PhaseShift = exp(1j*pi/2*(l+k))*exp(1j*obj.Implementation.InitialPhaseShift);
% index for the time shift of different FBMC symbols
IndexAfterIFFT =[ones(obj.Nr.SamplesPrototypeFilter,obj.Nr.MCSymbols);zeros(obj.Implementation.TimeSpacing*(obj.Nr.MCSymbols-1),obj.Nr.MCSymbols)];
IndexNumberAfterIFFT = zeros(obj.Nr.SamplesPrototypeFilter,obj.Nr.MCSymbols);
for i_k = 1:obj.Nr.MCSymbols
IndexAfterIFFT(:,i_k) = circshift(IndexAfterIFFT(:,i_k),(i_k-1)*obj.Implementation.TimeSpacing);
IndexNumberAfterIFFT(:,i_k) = find(IndexAfterIFFT(:,i_k));
end
obj.Implementation.IndexAfterIFFT = logical(IndexAfterIFFT);
obj.Implementation.IndexNumberAfterIFFT = IndexNumberAfterIFFT;
% index for the polyphase implementation
obj.Implementation.FFTSize = round(obj.Nr.SamplesPrototypeFilter./obj.Implementation.FrequencySpacing);
obj.Implementation.IntermediateFrequency = round(obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing);
obj.Implementation.IndexPolyphaseMap = logical(circshift([ones(obj.Nr.Subcarriers,obj.Nr.MCSymbols);...
zeros(obj.Implementation.FFTSize-obj.Nr.Subcarriers,obj.Nr.MCSymbols)],...
[obj.Implementation.IntermediateFrequency 1]));
% Normalization factor so that the default power = 1
obj.Implementation.NormalizationFactor = sqrt(obj.PHY.SamplingRate^2/obj.PHY.SubcarrierSpacing^2*obj.PHY.TimeSpacing/obj.Nr.Subcarriers);
end
% Set Functions
function SetNrSubcarriers(varargin)
% set the number of subcarriers
obj = varargin{1};
% set specific property
obj.Nr.Subcarriers = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetNrMCSymbols(varargin)
% set the number of symbols
obj = varargin{1};
% set specific property
obj.Nr.MCSymbols = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetSubcarrierSpacing(varargin)
% set the subcarrier spacing
obj = varargin{1};
% set specific property
obj.PHY.SubcarrierSpacing = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetSamplingRate(varargin)
% set the sampling rate
obj = varargin{1};
% set specific property
obj.PHY.SamplingRate = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetIntermediateFrequency(varargin)
% set intermediate frequency
obj = varargin{1};
% set specific property
obj.PHY.IntermediateFrequency = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetTransmitRealSignal(varargin)
% set real transmit signal indicator
obj = varargin{1};
obj.PHY.TransmitRealSignal = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetMethod(varargin)
% set method (prototype filter)
obj = varargin{1};
% set specific property
obj.Method = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetOverlappingFactor(varargin)
% set overlapping factor
obj = varargin{1};
% set specific property
obj.PrototypeFilter.OverlappingFactor = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetInitialPhaseShift(varargin)
% set initial phase shift
obj = varargin{1};
% set specific property
obj.Implementation.InitialPhaseShift = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
function SetUsePolyphase(varargin)
% set polyphase filter indicator
obj = varargin{1};
% set specific property
obj.Implementation.UsePolyphase = varargin{2};
% recalculate dependent parameters
obj.SetDependentParameters;
end
% Modulation and Demodulation
function TransmitSignal = Modulation(obj, DataSymbols)
% modulates the data symbols. The input argument is a matrix
% of size "Number of subcarriers" \times "Number of FBMC symbols"
% which represents the transmit data symbols
TransmitSignal = zeros(size(obj.Implementation.IndexAfterIFFT));
if obj.Implementation.UsePolyphase
DataSymbolsTemp = zeros(size(obj.Implementation.IndexPolyphaseMap));
DataSymbolsTemp(obj.Implementation.IndexPolyphaseMap) = DataSymbols.*obj.Implementation.PhaseShift.*obj.Implementation.NormalizationFactor;
if obj.PHY.TransmitRealSignal
DataSymbolsTemp = (DataSymbolsTemp+conj(DataSymbolsTemp([1 end:-1:2],:)))/sqrt(2);
end
TransmitSignal(obj.Implementation.IndexAfterIFFT) = repmat(ifft(DataSymbolsTemp),[obj.Implementation.FrequencySpacing 1]).*repmat(obj.PrototypeFilter.TimeDomain,[1 obj.Nr.MCSymbols]);
TransmitSignal = sum(TransmitSignal,2);
else
% Include also the design in the frequency domain because it provides an alternative understanding of FBMC, but is less efficient!
% Note that this matrix could be precomputed!
FrequencyGeneration = zeros(size(obj.PrototypeFilter.FrequencyDomain,1),obj.Nr.Subcarriers);
for i_l=1:obj.Nr.Subcarriers
FrequencyGeneration(:,i_l) = circshift(obj.PrototypeFilter.FrequencyDomain, obj.Implementation.FrequencySpacing*(i_l-1+obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing));
end
% normalized to have power 1
FrequencyGeneration = FrequencyGeneration*sqrt(1/obj.Nr.Subcarriers*obj.PHY.TimeSpacing)*obj.PHY.SamplingRate;
FrequencyDomain = FrequencyGeneration*(DataSymbols.*obj.Implementation.PhaseShift);
if obj.PHY.TransmitRealSignal
FrequencyDomain = (FrequencyDomain+conj(FrequencyDomain([1 end:-1:2],:)))/sqrt(2);
end
TransmitSignal(obj.Implementation.IndexAfterIFFT) = circshift(ifft(FrequencyDomain),[-obj.Nr.SamplesPrototypeFilter/2 0]);
TransmitSignal = sum(TransmitSignal,2);
end
end
function ReceivedSymbols = Demodulation(obj, ReceivedSignal)
% demodulates the received time signal and returns a matrix of
% size "Number of subcarriers" \times "Number of FBMC symbols"
% which represents the received symbols after demodulation but
% before channel equalization
% ReceivedSignal_CorrespondingSamplesToFBMCSymbol=reshape(ReceivedSignal(obj.Implementation.IndexNumberAfterIFFT(:)),[obj.Nr.SamplesPrototypeFilter obj.Nr.MCSymbols]);
ReceivedSignal_CorrespondingSamplesToFBMCSymbol = ReceivedSignal(obj.Implementation.IndexNumberAfterIFFT);
if obj.Implementation.UsePolyphase
% similar to the transmitter, just in reversed order
FilteredReceivedSignal = ReceivedSignal_CorrespondingSamplesToFBMCSymbol.*repmat(obj.PrototypeFilter.TimeDomain,[1 obj.Nr.MCSymbols]);
ReceivedSymbolsTemp = fft(sum(reshape(FilteredReceivedSignal,[size(obj.Implementation.IndexPolyphaseMap,1) obj.Implementation.FrequencySpacing obj.Nr.MCSymbols]),2));
if obj.PHY.TransmitRealSignal
ReceivedSymbolsTemp = ReceivedSymbolsTemp *sqrt(2);
end
ReceivedSymbols = reshape(ReceivedSymbolsTemp(obj.Implementation.IndexPolyphaseMap),size(obj.Implementation.PhaseShift)).*conj(obj.Implementation.PhaseShift)/(obj.Implementation.NormalizationFactor*obj.PHY.SubcarrierSpacing);
else
% same as before
FrequencyGeneration = zeros(size(obj.PrototypeFilter.FrequencyDomain,1),obj.Nr.Subcarriers);
for i_l=1:obj.Nr.Subcarriers
FrequencyGeneration(:,i_l) = circshift(obj.PrototypeFilter.FrequencyDomain, obj.Implementation.FrequencySpacing*(i_l-1+obj.PHY.IntermediateFrequency/obj.PHY.SubcarrierSpacing));
end
% normalized to have power 1
FrequencyGeneration = FrequencyGeneration*sqrt(1/obj.Nr.Subcarriers*obj.PHY.TimeSpacing)*obj.PHY.SamplingRate;
FrequencyDomain = fft(circshift(ReceivedSignal_CorrespondingSamplesToFBMCSymbol,[obj.Nr.SamplesPrototypeFilter/2 0]));
ReceivedSymbols = (FrequencyGeneration'*FrequencyDomain).*conj(obj.Implementation.PhaseShift)*(obj.Nr.Subcarriers*obj.PHY.SubcarrierSpacing)/(obj.PHY.SamplingRate^2*obj.PHY.TimeSpacing*obj.Implementation.FrequencySpacing);
end
end
% Matrix Description
function TXMatrix = GetTXMatrix(obj)
% returns a matrix G so that s=G*x(:) is the same as
% s=obj.Modulation(x)
TransmitRealSignal=false;
if obj.PHY.TransmitRealSignal
obj.PHY.TransmitRealSignal = false;
TransmitRealSignal=true;
end
TXMatrix=zeros(obj.Nr.SamplesTotal,obj.Nr.Subcarriers*obj.Nr.MCSymbols);
TXMatrixTemp=zeros(obj.Nr.SamplesTotal,obj.Nr.Subcarriers);
x = zeros(obj.Nr.Subcarriers, obj.Nr.MCSymbols);
for i_l= 1:obj.Nr.Subcarriers;
x(i_l)=1;
TXMatrixTemp(:,i_l) = obj.Modulation(x);
x(i_l)=0;
end
for i_k=1:obj.Nr.MCSymbols
TXMatrix(:,(1:obj.Nr.Subcarriers)+(i_k-1)*obj.Nr.Subcarriers)=circshift(TXMatrixTemp,[(i_k-1)*obj.Implementation.TimeSpacing,0])*1j^(i_k-1);
end
if TransmitRealSignal
obj.PHY.TransmitRealSignal = true;
TXMatrix = real(TXMatrix)*sqrt(2);
end
end
function RXMatrix = GetRXMatrix(obj)
% returns a matrix Q so that y=Q*r is the same as
% y=reshape(obj.Demodulation(r),[],1)
if obj.PHY.TransmitRealSignal
obj.PHY.TransmitRealSignal = false;
RXMatrix = sqrt(2)*obj.GetTXMatrix'*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing));
obj.PHY.TransmitRealSignal = true;
else
RXMatrix = obj.GetTXMatrix'*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing));
end
end
function FBMCMatrix = GetFBMCMatrix(obj,FastCalculation)
% returns a matrix D, so that y=D*x is the same as
% y=reshape(obj.Demodulation(obj.Modulation(x)),[],1)
if not(exist('FastCalculation','var'))
FastCalculation = true;
end
if FastCalculation
InterferenceMatrix = obj.GetInterferenceMatrix;
[Symbol_i,Subcarrier_i] = meshgrid(1:obj.Nr.MCSymbols,1:obj.Nr.Subcarriers);
LK = obj.Nr.Subcarriers*obj.Nr.MCSymbols;
Index_DeltaSubcarrier = repmat(Subcarrier_i(:),1,LK)-repmat(Subcarrier_i(:)',LK,1);
Index_DeltaSymbols = repmat(Symbol_i(:),1,LK)-repmat(Symbol_i(:)',LK,1);
Index_Subcarrier = repmat(Subcarrier_i(:),1,LK)-1;
FBMCMatrix=reshape(InterferenceMatrix(Index_DeltaSubcarrier(:)+obj.Nr.Subcarriers+(Index_DeltaSymbols(:)+obj.Nr.MCSymbols-1)*size(InterferenceMatrix,1)),LK,LK);
if obj.Method(end-3)=='-'
% QAM, works only for an odd number of subcarriers, needs to be fixed! Hower it does not really matter because values are too small to have any effect!
FBMCMatrix=FBMCMatrix.*exp(-1j*pi/2*(Index_DeltaSubcarrier+Index_DeltaSymbols)).*exp(-1j*pi*3/2*Index_DeltaSymbols.*Index_DeltaSubcarrier);
else
% OQAM, this works
FBMCMatrix=FBMCMatrix.*exp(-1j*pi/2*(Index_DeltaSubcarrier+Index_DeltaSymbols)).*exp(-1j*2*pi*(obj.PHY.TimeSpacing*obj.PHY.SubcarrierSpacing)*Index_DeltaSymbols.*(Index_Subcarrier+Index_DeltaSubcarrier/2));
end
else
% straightforward slow implementation
FBMCMatrix = zeros(obj.Nr.Subcarriers*obj.Nr.MCSymbols);
DataImpulse=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols);
for i_lk=1:obj.Nr.Subcarriers*obj.Nr.MCSymbols
DataImpulse(i_lk)=1;
FBMCMatrix(:,i_lk) = reshape(obj.Demodulation(obj.Modulation(DataImpulse)),[],1);
DataImpulse(i_lk)=0;
end
end
end
function InterferenceMatrix = GetInterferenceMatrix(obj)
% returns a matrix which represents the imaginary interference
% weights in FBMC
DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols);
DataSymbols(1,1)=1;
Y11=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols);
[k_all,l_all] = meshgrid(0:obj.Nr.MCSymbols-1,0:obj.Nr.Subcarriers-1);
Y11=Y11.*(exp(1j*pi/2*(l_all+k_all)).*exp(-1j*pi*k_all.*(l_all/2)));
InterferenceMatrix = [Y11(end:-1:2,end:-1:2),Y11(end:-1:2,1:end);Y11(:,end:-1:2),Y11(1:end,1:end)];
end
function TimePos = GetTimeIndexMidPos(obj)
% returns a vector which represents the discete time position
% of the corresponding FBMC symbol (middle position)
TimePos = round(size(obj.PrototypeFilter.TimeDomain,1)/2)+1+(0:obj.Nr.MCSymbols-1)*obj.Implementation.TimeSpacing;
end
% Plot
function [TransmitPower,Time]=PlotTransmitPower(obj, Rx)
% plot the expected transmit power over time. The input
% argument represents the correlation of the data symbols.
% If no input argument is specified, an identity matrix is
% assumed (uncorrelated data)
if exist('Rx','var')
[V,D] = eig(Rx);
else
% assume that Rx is an identity matrix, that is,
% uncorrelated symbols
V = eye(obj.Nr.Subcarriers*obj.Nr.MCSymbols);
D = V;
end
D=sqrt(D);
TransmitPower = zeros(obj.Nr.SamplesTotal,1);
for i_lk = 1:obj.Nr.Subcarriers*obj.Nr.MCSymbols
TransmitPower = TransmitPower+abs(obj.Modulation(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols))*D(i_lk,i_lk)).^2;
if mod(i_lk,1000)==0
disp([int2str(i_lk/(obj.Nr.Subcarriers*obj.Nr.MCSymbols )*100) '%']);
end
end
Time = (0:length(TransmitPower)-1)*obj.PHY.dt;
if nargout==0
plot(Time,TransmitPower);
ylabel('Transmit Power');
xlabel('Time(s)');
end
end
function [PowerSpectralDensity,Frequency] = PlotPowerSpectralDensity(obj,Rx)
% plot the power spectral density. The input argument
% represents the correlation of the data symbols. If no input
% argument is specified, an identity matrix is assumed
% (uncorrelated data)
if exist('Rx','var')
[V,D] = eig(Rx);
else
V = eye(obj.Nr.Subcarriers*obj.Nr.MCSymbols);
D = V;
end
D=sqrt(D);
PowerSpectralDensity = zeros(obj.Nr.SamplesTotal,1);
for i_lk = 1:obj.Nr.Subcarriers*obj.Nr.MCSymbols
PowerSpectralDensity = PowerSpectralDensity+abs(fft(obj.Modulation(reshape(V(:,i_lk),obj.Nr.Subcarriers,obj.Nr.MCSymbols))*D(i_lk,i_lk))).^2;
if mod(i_lk,1000)==0
disp([int2str(i_lk/(obj.Nr.Subcarriers*obj.Nr.MCSymbols )*100) '%']);
end
end
Frequency = (0:length(PowerSpectralDensity)-1)*1/(length(PowerSpectralDensity)*obj.PHY.dt);
PowerSpectralDensity=PowerSpectralDensity/length(PowerSpectralDensity)^2/Frequency(2)^2;
if nargout==0
plot(Frequency,10*log10(PowerSpectralDensity));
ylabel('Power Spectral Density (dB/Hz)');
xlabel('Frequency (Hz)');
end
end
function [PowerSpectralDensity,Frequency] = PlotPowerSpectralDensityUncorrelatedData(obj)
% plot the power spectral density in case of uncorrelated data
% symbols. Faster than FBMC.PlotPowerSpectralDensity
PowerSpectralDensity = zeros(obj.Nr.SamplesTotal,1);
for i_lk = 1:obj.Nr.Subcarriers
V = zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols);
V(i_lk,round(obj.Nr.MCSymbols/2))=1;
PowerSpectralDensity = PowerSpectralDensity+abs(fft(obj.Modulation(V))).^2;
end
Frequency = (0:length(PowerSpectralDensity)-1)*1/(length(PowerSpectralDensity)*obj.PHY.dt);
PowerSpectralDensity=obj.Nr.MCSymbols*PowerSpectralDensity/length(PowerSpectralDensity)^2/Frequency(2)^2;
if nargout==0
plot(Frequency,10*log10(PowerSpectralDensity));
ylabel('Power Spectral Density (dB/Hz)');
xlabel('Frequency (Hz)');
end
end
% SIR and Noise power
function [SIR_dB] = GetSIRdBDoublyFlat(obj)
% returns the SIR [dB] in case of a doubly-flat channel. The
% inferference is caused by the imperfect prototype filter.
% Increasing the overlapping factor also increased the SIR.
DataSymbols=zeros(obj.Nr.Subcarriers,obj.Nr.MCSymbols);
DataSymbols(ceil(end/2),ceil(end/2))=1;
Y=reshape(obj.Demodulation(obj.Modulation(DataSymbols)),obj.Nr.Subcarriers,obj.Nr.MCSymbols);
if obj.Method(end-3)=='O'
Y = real(Y);
end
S = abs(Y(ceil(end/2),ceil(end/2))).^2;
Y(ceil(end/2),ceil(end/2))=0;
I =sum(sum(abs(Y).^2));
SIR_dB = 10*log10(S/I);
end
function Pn = GetSymbolNoisePower(obj,Pn_time)
% returns the symbol noise power, that is, the noise power
% after demodulation. The input argument is the noise power
% in the time domain.
Pn = (Pn_time*(obj.Nr.Subcarriers/(obj.PHY.SamplingRate*obj.PHY.TimeSpacing)));
end
function [SignalPower,InterferencePower] = GetSignalAndInterferencePowerQAM(...
obj,... % FBMC object
VectorizedChannelCorrelationMatrix,... % Let the received signal be r=H*s with H representing a time-variant convolution matrix. Then "VectorizedChannelCorrelationMatrix" represents the expectation E{{H(:)*H(:)'}. We can obtain such matrix by ChannelModel.GetCorrelationMatrix
DataSymbolCorrelationMatrix,... % Correlation matrix of the vectorized data symbols
TimeSamplesOffset,... % Time offset in samples (to improve the SIR)
SubcarrierPosition,... % Subcarrier position for which the SIR is calculated.
FBMCSymbolPosition... % FBMC symbol position in time for which the SIR is calculated.
)
% returns the signal and interference power for a
% doubly-selective channel in case of QAM transmissions
TXMatrix = obj.GetTXMatrix;
RXMatrix = obj.GetRXMatrix;
RXMatrix = [zeros(size(RXMatrix,1),TimeSamplesOffset),RXMatrix(:,1:end-TimeSamplesOffset)]; % Time offset compensation
Index = SubcarrierPosition+(FBMCSymbolPosition-1)*obj.Nr.Subcarriers;
% TempOld = kron(TXMatrix.',RXMatrix(Index,:))*VectorizedChannelCorrelationMatrix*kron(TXMatrix.',RXMatrix(Index,:))';
% Much more efficient
RXVectorRep = kron(sparse(eye(length(RXMatrix(Index,:)))),RXMatrix(Index,:)');
Temp = RXVectorRep'*VectorizedChannelCorrelationMatrix*RXVectorRep;
CorrMatrixNoData = TXMatrix.'*Temp*conj(TXMatrix);
SignalDataSymbolCorrelationMatrix = zeros(size(DataSymbolCorrelationMatrix));
SignalDataSymbolCorrelationMatrix(Index,Index) = DataSymbolCorrelationMatrix(Index,Index);
InterferenceDataSymbolCorrelationMatrix = DataSymbolCorrelationMatrix;
InterferenceDataSymbolCorrelationMatrix(Index,:)=0;
InterferenceDataSymbolCorrelationMatrix(:,Index)=0;
SignalPower = abs(sum(sum(CorrMatrixNoData.*SignalDataSymbolCorrelationMatrix)));
InterferencePower = abs(sum(sum(CorrMatrixNoData.*InterferenceDataSymbolCorrelationMatrix)));
end
function [SignalPower,InterferencePower] = GetSignalAndInterferencePowerOQAM(...
obj,... % FBMC object
VectorizedChannelCorrelationMatrix,... % Let the received signal be r=H*s with H representing a time-variant convolution matrix. Then "VectorizedChannelCorrelationMatrix" represents the expectation E{{H(:)*H(:)'}. We can obtain such matrix by ChannelModel.GetCorrelationMatrix
DataSymbolCorrelationMatrix,... % Correlation matrix of the vectorized data symbols
TimeSamplesOffset,... % Time offset in samples (to improve the SIR)
SubcarrierPosition,... % Subcarrier position for which the SIR is calculated.
FBMCSymbolPosition... % FBMC symbol position in time for which the SIR is calculated.
)
% returns the signal and interference power for a
% doubly-selective channel in case of OQAM transmissions, that
% is, real valued data symbols
TXMatrix = obj.GetTXMatrix;
RXMatrix = obj.GetRXMatrix;
RXMatrix = [zeros(size(RXMatrix,1),TimeSamplesOffset),RXMatrix(:,1:end-TimeSamplesOffset)]; % Time offset compensation
Index = SubcarrierPosition+(FBMCSymbolPosition-1)*obj.Nr.Subcarriers;
% TempOld = kron(TXMatrix.',RXMatrix(Index,:))*VectorizedChannelCorrelationMatrix*kron(TXMatrix.',RXMatrix(Index,:))';
% Much more efficient
RXVectorRep = kron(sparse(eye(length(RXMatrix(Index,:)))),RXMatrix(Index,:)');
Temp = RXVectorRep'*VectorizedChannelCorrelationMatrix*RXVectorRep;
CorrMatrixNoData = TXMatrix.'*Temp*conj(TXMatrix);
% additional processing for OQAM: we need to correct the phase
[V,D] = eig(CorrMatrixNoData);
Half = V*sqrt(D);
Phase = exp(-1j*angle(Half(Index,:)));
Half = Half.*repmat(Phase,[size(Half,1) 1]);
CorrMatrixNoData = real(Half)*real(Half)';
SignalDataSymbolCorrelationMatrix = zeros(size(DataSymbolCorrelationMatrix));
SignalDataSymbolCorrelationMatrix(Index,Index) = DataSymbolCorrelationMatrix(Index,Index);
InterferenceDataSymbolCorrelationMatrix = DataSymbolCorrelationMatrix;
InterferenceDataSymbolCorrelationMatrix(Index,:)=0;
InterferenceDataSymbolCorrelationMatrix(:,Index)=0;
SignalPower = abs(sum(sum(CorrMatrixNoData.*SignalDataSymbolCorrelationMatrix)));
InterferencePower = abs(sum(sum(CorrMatrixNoData.*InterferenceDataSymbolCorrelationMatrix)));
end
function CodingMatrix = GetPrecodingMatrixForQAMinOQAM(obj,TimeSpreading,StartIndex)
% Returns a precoding matrix C which allows QAM transmission
% in FBMC-OQAM by spreading data symbols in time or frequency.
% For spreading in time, the first argument must be set to true.
% For spreading in frequency, it must be set to false.
% The second argument represents the start index of the
% Hadamard matrix and can be set to 1 or 2.
% Let D = obj.GetFBMCMatrix, then we have C'*D*C=eye(.)
% For more information, see "Enabling Low-Complexity MIMO in
% FBMC-OQAM", R.Nissel et al, 2016, GC Wkshps
% Chose between time or frequency spreading
if TimeSpreading
if rem(log2(obj.Nr.MCSymbols),1)
error('Number of time-symbols must be a power of 2');
end
HadamardMatrix = fwht(eye(obj.Nr.MCSymbols),obj.Nr.MCSymbols,'sequency')*sqrt(obj.Nr.MCSymbols);
CodingMatrix_Basis(:,:,1) = HadamardMatrix(:,1:2:end);
CodingMatrix_Basis(:,:,2) = HadamardMatrix(:,2:2:end);
IndexSpreading = repmat((1:obj.Nr.Subcarriers)',[1,obj.Nr.MCSymbols]);
IndexSpreadingHalf = IndexSpreading(:,1:2:end);
CodingMatrix = zeros(obj.Nr.Subcarriers*obj.Nr.MCSymbols,obj.Nr.Subcarriers*obj.Nr.MCSymbols/2);
for i_CodeMapping = 1:max(max(IndexSpreading))
CodingMatrix(IndexSpreading(:)==i_CodeMapping,IndexSpreadingHalf(:)==i_CodeMapping) = CodingMatrix_Basis(:,:,mod(i_CodeMapping+StartIndex,2)+1);
end
else % Frequency spreading
if rem(log2(obj.Nr.Subcarriers),1)
error('Number of subcarriers must be a power of 2');
end
HadamardMatrix = fwht(eye(obj.Nr.Subcarriers),obj.Nr.Subcarriers,'sequency')*sqrt(obj.Nr.Subcarriers);
CodingMatrix_Basis(:,:,1) = HadamardMatrix(:,1:2:end);
CodingMatrix_Basis(:,:,2) = HadamardMatrix(:,2:2:end);
CodingMatrix = kron(sparse(eye(obj.Nr.MCSymbols)),CodingMatrix_Basis(:,:,mod(StartIndex-1,2)+1));
end
end
end
end
function PrototypeFilter = PrototypeFilter_Hermite(T0,dt,OF)
% The pulse is orthogonal for a time-spacing of T=T_0 and a frequency-spacing of F=2/T_0
% Values taken from: R.Nissel et al. "ON PILOT-SYMBOL AIDED CHANNEL ESTIMATION IN FBMC-OQAM"
t_filter=-(OF*T0):dt:(OF*T0-dt);
D0=1/sqrt(T0)*HermiteH(0,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
D4=1/sqrt(T0)*HermiteH(4,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
D8=1/sqrt(T0)*HermiteH(8,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))) .*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
D12=1/sqrt(T0)*HermiteH(12,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
D16=1/sqrt(T0)*HermiteH(16,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
D20=1/sqrt(T0)*HermiteH(20,sqrt(2*pi)*(t_filter./(T0/sqrt(2)))).*exp(-pi*(t_filter./(T0/sqrt(2))).^2);
H0= 1.412692577;
H4= -3.0145e-3;
H8=-8.8041e-6;
H12=-2.2611e-9;
H16=-4.4570e-15;
H20 = 1.8633e-16;
PrototypeFilter=(D0.*H0+D4.*H4+D8.*H8+D12.*H12+D16.*H16+D20.*H20).';
PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt);
end
function PrototypeFilter = PrototypeFilter_RootRaisedCosine(T0,dt,OF)
% The pulse is orthogonal for a time-spacing of T=T0 and a frequency-spacing of F=2/T0
t_filter=-(OF*T0):dt:(OF*T0-dt);
PrototypeFilter=(1/sqrt(T0)*(4*t_filter/T0.*cos(2*pi*t_filter/T0))./(pi*t_filter/T0.*(1-(4*t_filter/T0).^2)));
PrototypeFilter(abs(t_filter)<10^-14) =1/sqrt(T0)*(4/pi);
PrototypeFilter(abs(abs(t_filter)-T0/4)<10^-14)=1/sqrt(2*T0)*((1+2/pi)*sin(pi/4)+(1-2/pi)*cos(pi/4));
PrototypeFilter=PrototypeFilter.';
PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt);
end
function PrototypeFilter = PrototypeFilter_PHYDYAS(T0,dt,OF)
% The pulse is orthogonal for a time-spacing of T=T0 and a frequency-spacing of F=2/T0
t_filter=-(OF*T0):dt:(OF*T0-dt);
switch OF*2
case 2
H= [sqrt(2)/2];
case 3
H = [0.91143783 0.41143783];
case 4
H = [0.97195983 sqrt(2)/2 0.23514695];
case 5
H = [0.99184131 0.86541624 0.50105361 0.12747868];
case 6
H = [0.99818572 0.94838678 sqrt(2)/2 0.31711593 0.06021021];
case 7
H = [0.99938080 0.97838560 0.84390076 0.53649931 0.20678881 0.03518546];
case 8
H = [0.99932588 0.98203168 0.89425129 sqrt(2)/2 0.44756522 0.18871614 0.03671221];
otherwise
error('Oversampling factor must be an integer between 1 and 8 for OQAM or betwen 1 and 4 for QAM');
end
PrototypeFilter = 1+2*sum(repmat(H,length(t_filter),1).*cos(2*pi*repmat(t_filter',1,length(H)).*repmat(1:length(H),length(t_filter),1)/((length(H)+1)*T0)),2);
PrototypeFilter = PrototypeFilter/sqrt(sum(abs(PrototypeFilter).^2)*dt);
end
function Hermite = HermiteH(n,x)
% Hermite polynomials (obtained by Mathematica, "ToMatlab[HermiteH[n, x]]")
if n==0
Hermite=ones(size(x));
elseif n==4
Hermite=12+(-48).*x.^2+16.*x.^4;
elseif n==8
Hermite = 1680+(-13440).*x.^2+13440.*x.^4+(-3584).*x.^6+256.*x.^8;
elseif n==12
Hermite = 665280+(-7983360).*x.^2+13305600.*x.^4+(-7096320).*x.^6+1520640.* ...
x.^8+(-135168).*x.^10+4096.*x.^12;
elseif n==16
Hermite = 518918400+(-8302694400).*x.^2+19372953600.*x.^4+(-15498362880).* ...
x.^6+5535129600.*x.^8+(-984023040).*x.^10+89456640.*x.^12+( ...
-3932160).*x.^14+65536.*x.^16;
elseif n==20
Hermite = 670442572800+(-13408851456000).*x.^2+40226554368000.*x.^4+( ...
-42908324659200).*x.^6+21454162329600.*x.^8+(-5721109954560).* ...
x.^10+866834841600.*x.^12+(-76205260800).*x.^14+3810263040.*x.^16+ ...
(-99614720).*x.^18+1048576.*x.^20;
end
end
|
github | mohammadzainabbas/Digital-Communication-master | BitErrorProbabilityDoublyFlatRayleigh.m | .m | Digital-Communication-master/FBMC/Theory/BitErrorProbabilityDoublyFlatRayleigh.m | 5,433 | utf_8 | dad0d52f13e8cc151062cd0b3fa6f8f4 | % Ronald Nissel, [email protected]
% (c) 2017 by Institute of Telecommunications, TU Wien
% www.tc.tuwien.ac.at
% This function calculates the bit error probability for an arbitrary
% signal constellation in a doubly flat rayleigh channel.
% It is based on "OFDM and FBMC-OQAM in doubly-selective channels:
% Calculating the bit error probability", R. Nissel and M. Rupp, IEEE
% Communications Letters, 2017
function BitErrorProbability = BitErrorProbabilityDoublyFlatRayleigh(...
SNR_dB, ... % The SNR in the complex domain => SNR_FBMC = SNR_OFDM-3dB.
SymbolMapping, ...% The symbol mapping with mean(SymbolMapping.*conj(SymbolMapping))==1. For example in 4QAM we have: SymbolMapping=[0.7071 + 0.7071i;-0.7071 + 0.7071i;0.7071 - 0.7071i;-0.7071 - 0.7071i];
BitMapping) % The bitmapping corresponding to the symbol mapping. For example for 4QAM we have: BitMapping = [0 0;1 0;0 1;1 1];
% For the decision regions we assume a rectangular regular grid! The rest
% of the function could also be used for an irregular grid but
% the decision regions would have to be rewritten!
HalfDecisionInterval = min(abs(real(SymbolMapping)));
DecisionRegions = [...
real(SymbolMapping)- HalfDecisionInterval ...
real(SymbolMapping)+ HalfDecisionInterval ...
imag(SymbolMapping)- HalfDecisionInterval ...
imag(SymbolMapping)+ HalfDecisionInterval ];
DecisionRegions(min(real(SymbolMapping))==real(SymbolMapping),1) = -inf;
DecisionRegions(max(real(SymbolMapping))==real(SymbolMapping),2) = +inf;
DecisionRegions(min(imag(SymbolMapping))==imag(SymbolMapping),3) = -inf;
DecisionRegions(max(imag(SymbolMapping))==imag(SymbolMapping),4) = +inf;
BitErrorProbability = nan(length(SNR_dB),1);
for i_SNR = 1:length(SNR_dB)
Pn = 10^(-SNR_dB(i_SNR)/10);
ProbabilityMatrix = nan(size(SymbolMapping,1),size(SymbolMapping,1));
for i_symbol = 1:size(SymbolMapping,1)
x = SymbolMapping(i_symbol);
Ey2 = abs(x).^2+Pn;
Eh2 = 1;
Eyh = x;
ProbabilityMatrix(:,i_symbol)=GaussianRatioProbabilityRectangularRegion(Ey2,Eh2,Eyh,DecisionRegions(:,1),DecisionRegions(:,2),DecisionRegions(:,3),DecisionRegions(:,4));
end
ErrorProbability = nan(2,size(BitMapping,2));
for i_bit= 1:size(BitMapping,2)
for i_zero_one = [0 1]
index_x = (BitMapping(:,i_bit)==i_zero_one);
ErrorProbability(i_zero_one+1,i_bit) = mean(sum(ProbabilityMatrix(not(index_x),index_x)));
end
end
BitErrorProbability(i_SNR) = mean(mean(ErrorProbability));
end
end
% This function calculates the Probability that the complex Gaussian ratio
% y/h is within the rectrangular region "(zRlower zIlower] x (zRupper
% zIupper]". It requires the function "GaussianRatioCDF"
function Probability = GaussianRatioProbabilityRectangularRegion(...
Ey2,... % Expectation{|y|^2}
Eh2,... % Expectation{|h|^2}
Eyh,... % Expectation{y*conj(h)}
zRlower,... % Determines the rectangular region
zRupper,...
zIlower,...
zIupper)
CDF_RegionA = GaussianRatioCDF(Ey2,Eh2,Eyh,zRupper,zIupper);
CDF_RegionB = GaussianRatioCDF(Ey2,Eh2,Eyh,zRlower,zIlower);
CDF_RegionC = GaussianRatioCDF(Ey2,Eh2,Eyh,zRlower,zIupper);
CDF_RegionD = GaussianRatioCDF(Ey2,Eh2,Eyh,zRupper,zIlower);
Probability = CDF_RegionA+CDF_RegionB-CDF_RegionC-CDF_RegionD;
end
% This function calculates the CDF of the complex Gaussian ratio y/h, that
% is Pr(real(y/h)<zR & imag(y/h)<zR), whereas y and h are complex Gaussian random variables
function CDF = GaussianRatioCDF(...
Ey2,... % Expectation{|y|^2}
Eh2,... % Expectation{|h|^2}
Eyh,... % Expectation{y*conj(h)}
zR,... % Real part of the CDF, i.e, Pr(real(y/h)<zR &...)
zI) % Imaginary part of the CDF, i.e, Pr(... & imag(y/h)<zR)
a = Eyh/Eh2; % alpha
b = Ey2/Eh2; % beta
Index0 = (zR == -inf) | (zI == -inf);
Index1 = (zR == inf) & (zI == inf);
IndexReal = (zI == inf) & isfinite(zR);
IndexImag = (zR == inf) & isfinite(zI);
IndexNormal = isfinite(zR) & isfinite(zI);
% See "Bit error probability for pilot-symbol aided channel estimation in
% FBMC-OQAM", R. Nissel and M. Rupp, 2016
CDF_Real = 1/2-...
(real(a)-zR(IndexReal))./...
(2*sqrt((real(a)-zR(IndexReal)).^2+b-abs(a).^2));
CDF_Imag = 1/2-...
(imag(a)-zI(IndexImag))./...
(2*sqrt((imag(a)-zI(IndexImag)).^2+b-abs(a).^2));
% General Case, see "OFDM and FBMC-OQAM in Doubly-Selective Channels:
% Calculating the Bit Error Probability" R. Nissel and M. Rupp, 2017
CDF_Normal = 1/4+...
(zR(IndexNormal)-real(a)).*...
(2*atan(...
(zI(IndexNormal)-imag(a))./sqrt((zR(IndexNormal)-real(a)).^2+b-abs(a).^2)...
)+pi)./...
(4*pi*sqrt((zR(IndexNormal)-real(a)).^2+b-abs(a).^2))+...
(zI(IndexNormal)-imag(a)).*...
(2*atan(...
(zR(IndexNormal)-real(a))./sqrt((zI(IndexNormal)-imag(a)).^2+b-abs(a).^2)...
)+pi)./...
(4*pi*sqrt((zI(IndexNormal)-imag(a)).^2+b-abs(a).^2));
% Map CDF to correct one
CDF = nan(size(zR));
CDF(Index0) = 0;
CDF(Index1) = 1;
CDF(IndexReal) = CDF_Real;
CDF(IndexImag) = CDF_Imag;
CDF(IndexNormal) = CDF_Normal;
end |
github | mohammadzainabbas/Digital-Communication-master | BitErrorProbabilityAWGN.m | .m | Digital-Communication-master/FBMC/Theory/BitErrorProbabilityAWGN.m | 3,640 | utf_8 | 7c47a1abaea050d1e6e70b73ddd94551 | % Ronald Nissel, [email protected]
% (c) 2017 by Institute of Telecommunications, TU Wien
% www.tc.tuwien.ac.at
% This function calculates the bit error probability for an arbitrary
% signal constellations in an AWGN channel
function BitErrorProbability = BitErrorProbabilityAWGN(...
SNR_dB, ... % The SNR in the complex domain => SNR_FBMC = SNR_OFDM-3dB.
SymbolMapping, ...% The symbol mapping with mean(SymbolMapping.*conj(SymbolMapping))==1. For example in 4QAM we have: SymbolMapping=[0.7071 + 0.7071i;-0.7071 + 0.7071i;0.7071 - 0.7071i;-0.7071 - 0.7071i];
BitMapping) % The bitmapping corresponding to the symbol mapping. For example for 4QAM we have: BitMapping = [0 0;1 0;0 1;1 1];
% For the decision regions we assume a rectangular regular grid. The rest
% of the function could also be used for an irregular grid but
% the decision regions would have to be rewritten!
HalfedDecisionInterval = min(abs(real(SymbolMapping)));
DecisionRegions = [...
real(SymbolMapping)- HalfedDecisionInterval ...
real(SymbolMapping)+ HalfedDecisionInterval ...
imag(SymbolMapping)- HalfedDecisionInterval ...
imag(SymbolMapping)+ HalfedDecisionInterval ];
DecisionRegions(min(real(SymbolMapping))==real(SymbolMapping),1) = -inf;
DecisionRegions(max(real(SymbolMapping))==real(SymbolMapping),2) = +inf;
DecisionRegions(min(imag(SymbolMapping))==imag(SymbolMapping),3) = -inf;
DecisionRegions(max(imag(SymbolMapping))==imag(SymbolMapping),4) = +inf;
BitErrorProbability = nan(length(SNR_dB),1);
for i_SNR = 1:length(SNR_dB)
Pn = 10^(-SNR_dB(i_SNR)/10);
ProbabilityMatrix = nan(size(SymbolMapping,1),size(SymbolMapping,1));
for i_symbol = 1:size(SymbolMapping,1)
x = SymbolMapping(i_symbol);
ProbabilityMatrix(:,i_symbol)=GaussianRatioProbabilityRectangularRegion(x,Pn,DecisionRegions(:,1),DecisionRegions(:,2),DecisionRegions(:,3),DecisionRegions(:,4));
end
ErrorProbability = nan(2,size(BitMapping,2));
for i_bit= 1:size(BitMapping,2)
for i_zero_one = [0 1]
index_x = (BitMapping(:,i_bit)==i_zero_one);
ErrorProbability(i_zero_one+1,i_bit) = mean(sum(ProbabilityMatrix(not(index_x),index_x)));
end
end
BitErrorProbability(i_SNR) = mean(mean(ErrorProbability));
end
end
% This function calculates the Probability that y=x+n is within the
% rectrangular region "(zRlower zIlower] \times (zRupper zIupper]".
% It requires the function "GaussianRatioCDF"
function Probability = GaussianRatioProbabilityRectangularRegion(...
x,... % Transmitted symbol
Pn,... % Complex noise power
zRlower,... % Determines the rectangular region
zRupper,...
zIlower,...
zIupper)
CDF_RegionA = GaussianCDF(x,Pn,zRupper,zIupper);
CDF_RegionB = GaussianCDF(x,Pn,zRlower,zIlower);
CDF_RegionC = GaussianCDF(x,Pn,zRlower,zIupper);
CDF_RegionD = GaussianCDF(x,Pn,zRupper,zIlower);
Probability = CDF_RegionA+CDF_RegionB-CDF_RegionC-CDF_RegionD;
end
% This function calculates the CDF, that is Pr(real(x)<zR & imag(x)<zR),
% whereas x is a complex Gaussian random variable
function CDF = GaussianCDF(...
x,... % ....
Pn,... % ...
zR,... % Real part of the CDF, i.e, Pr(real(y/h)<zR &...)
zI) % Imaginary part of the CDF, i.e, Pr(... & imag(y/h)<zR)
CDF = normcdf(zR,real(x),sqrt(Pn/2)).*normcdf(zI,imag(x),sqrt(Pn/2));
end |
github | mohammadzainabbas/Digital-Communication-master | TurboCoding.m | .m | Digital-Communication-master/FBMC/+Coding/TurboCoding.m | 5,605 | utf_8 | 0d8994721a04fe4be8e040fa698bc99d | classdef TurboCoding < handle
% =====================================================================
% This MATLAB class represents a turbo coder (LTE).
% It requires the MATLAB Communications System Toolbox!
% Usage:
% 1) CodingObject = Coding.TurboCoding(NrDataBits,NrCodedBits)
% 2) CodingObject.TurboEncoder(Bitstream)
% 3) CodingObject.TurboDecoder(LLR)
% Additionally, we might want to update the internal interleaver by
% CodingObject.UpdateInterleaving;
% The code is based on the book
% "Understanding LTE with MATLAB", Houman Zarrinkoub
% =====================================================================
% Ronald Nissel, [email protected]
% (c) 2017 by Institute of Telecommunications, TU Wien
% www.nt.tuwien.ac.at
% =====================================================================
properties (SetAccess = private)
CommTurboEncoder
CommTurboDecoder
NrDataBits
NrCodedBits
CodeRate
Interleaving
end
methods
function obj = TurboCoding(varargin)
if varargin{2}>varargin{1}
obj.NrDataBits = varargin{1};
obj.NrCodedBits = varargin{2};
else
obj.NrDataBits = varargin{2};
obj.NrCodedBits = varargin{1};
end
obj.CodeRate = obj.NrDataBits/obj.NrDataBits;
obj.Interleaving = randperm(obj.NrDataBits);
obj.CommTurboEncoder = comm.TurboEncoder('TrellisStructure', poly2trellis(4, [13 15], 13),'InterleaverIndicesSource','Input port');
obj.CommTurboDecoder = comm.TurboDecoder('TrellisStructure', poly2trellis(4, [13 15], 13),'InterleaverIndicesSource','Input port', 'NumIterations', 10);
end
function CodedBits = TurboEncoder( obj , DataBits )
ImplementationCodeRate = (obj.NrDataBits+4)/obj.NrCodedBits;
CodedBits_1_3 = step(obj.CommTurboEncoder,DataBits,obj.Interleaving);
if ImplementationCodeRate>=1/3
CodedBits=RateMatcher(CodedBits_1_3,length(DataBits),ImplementationCodeRate);
else
IndexTurboRepetition = repmat(1:length(CodedBits_1_3),1,ceil(obj.NrCodedBits/length(CodedBits_1_3)));
IndexTurboRepetition=IndexTurboRepetition(1:obj.NrCodedBits);
CodedBits = CodedBits_1_3(IndexTurboRepetition);
end
end
function UpdateInterleaving(varargin)
obj = varargin{1};
if numel(varargin)>=2
obj.Interleaving = varargin{2};
else
obj.Interleaving = randperm(obj.NrDataBits);
end
end
function DecodedDataBits = TurboDecoder( obj , LLR )
NrCodedBits_1_3 = (obj.NrDataBits+4)*3;
ImplementationCodeRate = (obj.NrDataBits+4)/obj.NrCodedBits;
if ImplementationCodeRate>=1/3
LLR_RateMatched = RateDematcher(LLR, obj.NrDataBits);
else
IndexTurboRepetition = repmat(1:NrCodedBits_1_3,1,ceil(obj.NrCodedBits/NrCodedBits_1_3));
IndexTurboRepetition=IndexTurboRepetition(1:obj.NrCodedBits);
LLR_RateMatched = Coding.LTE_common_turbo_rate_matching_bit_selection_and_pruning(LLR,...
IndexTurboRepetition-1,...
2,...
NrCodedBits_1_3).';
end
DecodedDataBits = step(obj.CommTurboDecoder,LLR_RateMatched,obj.Interleaving);
end
end
end
function CodedBits = RateMatcher(CodedBits_1_3, NrDataBits, CodeRate)
NrDataBitsP4 = NrDataBits+4;
a = 32;
b = ceil(NrDataBitsP4/a);
PermutationPattern = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23, 15, 31];
Temp = reshape([nan(1,a*b-NrDataBitsP4),1:NrDataBitsP4],a,b).';
Temp2 = reshape(Temp.',[],1);
Index1 = reshape(Temp(:,PermutationPattern+1),[],1);
Index2 = Temp2(PermutationPattern(floor((0:a*b-1)/b)+1)+a*mod(0:a*b-1,b)+1);
c0 = SubBlockInterleaving(CodedBits_1_3(1:3:end),Index1);
c12 = reshape([SubBlockInterleaving(CodedBits_1_3(2:3:end),Index1),SubBlockInterleaving(CodedBits_1_3(3:3:end),Index2)].',[],1);
c = [c0(isfinite(c0));c12(isfinite(c12))];
CodedBits = c(1:round(NrDataBitsP4/CodeRate));
end
function LLR_RateMatched = RateDematcher(LLR, NrDataBits)
NrDataBitsP4 = NrDataBits+4;
a = 32;
b = ceil(NrDataBitsP4/a);
PermutationPattern = [0, 16, 8, 24, 4, 20, 12, 28, 2, 18, 10, 26, 6, 22, 14, 30, 1, 17, 9, 25, 5, 21, 13, 29, 3, 19, 11, 27, 7, 23, 15, 31];
Temp = reshape([nan(1,a*b-NrDataBitsP4),1:NrDataBitsP4],a,b).';
Temp2 = reshape(Temp.',[],1);
Index1 = reshape(Temp(:,PermutationPattern+1),[],1);
Index2 = Temp2(PermutationPattern(floor((0:a*b-1)/b)+1)+a*mod(0:a*b-1,b)+1);
LLR0 = zeros(3*NrDataBitsP4,1);
LLR0(1:numel(LLR)) = LLR;
l0 = SubBlockDeInterleaving(LLR0(1:NrDataBitsP4), Index1);
l12 = reshape(SubBlockDeInterleaving(LLR0(NrDataBitsP4+1:end), reshape([Index1,Index2+NrDataBitsP4].',[],1)), NrDataBitsP4 , 2);
LLR_RateMatched = reshape([l0 l12].',[],1);
end
function c = SubBlockInterleaving(c_in,Index)
c = zeros(size(Index));
c(~isnan(Index)==1) = c_in(Index(~isnan(Index)==1));
c(isnan(Index)==1) = nan*ones(sum(isnan(Index)==1),1);
end
function l = SubBlockDeInterleaving(LLR0,Index)
l = zeros(size(LLR0));
l(Index(~isnan(Index)==1)) = LLR0;
end
|
github | mohammadzainabbas/Digital-Communication-master | Task_1.m | .m | Digital-Communication-master/Lab 03/Task_1.m | 894 | utf_8 | b2c12a7fc937158391de0f871d09b843 | function Task_1()
%To generate random signal
x = random_signal();
size = length(x);
bins = input('Enter number of bins: ');
%Calculate pdf
pdf = PDF(x, bins);
%Rearranging x-axis of both so that mean appears at 0
x_axis = min(x):(max(x)-min(x))/(bins):max(x) - (max(x)-min(x))/(bins);
%x_axis = x_axis(1:size-1); %coz no. of bins = length - 1
% length(x)
% length(pdf)
%Calculating mean of signal
mean = sum((x) .* pdf);
%Calculating variance of signal
variance = sum(power((x - mean),2)/(length(x)));
%To change mean and variance
y = (100)*x + 1000;
pdf_y = PDF(y, bins);
y_axis = x_axis + 1000;
%Plot
figure
subplot(2,1,1)
bar(x_axis,pdf)
subplot(2,1,2)
bar(y_axis,pdf_y)
end
function x = random_signal()
size = input('Enter signal size: ');
x = randn(1,size);
end
function pdf = PDF(x, bins)
pdf = hist(x,bins)/(length(x));
end |
github | Simshang/cdc_data_prepare-master | intervaloverlapvalseconds.m | .m | cdc_data_prepare-master/THUMOS14/eval/TemporalActionLocalization/intervaloverlapvalseconds.m | 918 | utf_8 | 953715c547006494b896a8730ad7a9a9 | function ov=intervaloverlapvalseconds(i1,i2,normtype,gt,det)
%
if nargin<3 normtype=0; end
ov=zeros(size(i1,1),size(i2,1));
for i=1:size(i1,1)
for j=1:size(i2,1)
ov(i,j)=intervalsingleoverlapvalseconds(i1(i,:),i2(j,:),normtype);
if nargin==5
ov(i,j)=ov(i,j)*strcmp(gt(i).class,det(j).class);
end
end
end
function ov=intervalsingleoverlapvalseconds(i1,i2,normtype)
i1=[min(i1) max(i1)];
i2=[min(i2) max(i2)];
ov=0;
if normtype<0 ua=1;
elseif normtype==1
ua=(i1(2)-i1(1));
elseif normtype==2
ua=(i2(2)-i2(1));
else
bu=[min(i1(1),i2(1)) ; max(i1(2),i2(2))];
ua=(bu(2)-bu(1));
end
bi=[max(i1(1),i2(1)) ; min(i1(2),i2(2))];
iw=bi(2)-bi(1);
if iw>0
if normtype<0 % no normalization!
ov=iw;
else
ov=iw/ua;
end
end
%i1=i1(:)';
%i2=i2(:)';
%ov=0;
%[vs,is]=sort([i1(1:2) i2(1:2)]);
%ind=[1 1 2 2];
%inds=ind(is);
%if inds(1)~=inds(2)
% ov=vs(3)-vs(2);
%end
|
github | Simshang/cdc_data_prepare-master | TH14evalDet_Updated.m | .m | cdc_data_prepare-master/THUMOS14/eval/TemporalActionLocalization/TH14evalDet_Updated.m | 6,265 | utf_8 | 45f8f56f72274a8bf85d5373785e4762 | function [pr_all,ap_all,map]=TH14evalDet_Updated(detfilename,gtpath,subset,threshold)
% [pr_all,ap_all,map]=TH14evalDet_Updated(detfilename,gtpath,subset,[threshold])
%
% Input: detfilename: file path of the input file
% gtpath: the path of the groundtruth directory
% subset: 'test' or 'val', means the testset or validation set
% threshold: overlap threshold (0.5 in default)
%
% Output: pr_all: precision-recall curves
% ap_all: AP for each class
% map: MAP
%
%
% Evaluation of the temporal detection for 20 classes in the THUMOS 2014
% action detection challenge http://crcv.ucf.edu/THUMOS14/
%
% The function produces precision-recall curves and average precision
% values for each action class and five values of thresholds for
% the overlap between ground-truth action intervals and detected action
% intervals. Mean average precision values over classes are also returned.
%
%
%
% Example:
%
% [pr_all,ap_all,map]=TH14evalDet('results/Run-2-det.txt','annotation','test',0.5);
%
%
% Plotting precision-recall results:
%
% overlapthresh=0.1;
% ind=find([pr_all.overlapthresh]==overlapthresh);
% clf
% for i=1:length(ind)
% subplot(4,5,i)
% pr=pr_all(ind(i));
% plot(pr.rec,pr.prec)
% axis([0 1 0 1])
% title(sprintf('%s AP:%1.3f',pr.class,pr.ap))
% end
%
% THUMOS14 detection classes
%
if nargin<4
threshold=0.5;
end
if nargin<3
error('At least 3 parameters!')
end
[th14classids,th14classnames]=textread([gtpath '/detclasslist.txt'],'%d%s');
% read ground truth
%
clear gtevents
gteventscount=0;
th14classnamesamb=cat(1,th14classnames,'Ambiguous');
for i=1:length(th14classnamesamb)
class=th14classnamesamb{i};
gtfilename=[gtpath '/' class '_' subset '.txt'];
if exist(gtfilename,'file')~=2
error(['TH14evaldet: Could not find GT file ' gtfilename])
end
[videonames,t1,t2]=textread(gtfilename,'%s%f%f');
for j=1:length(videonames)
gteventscount=gteventscount+1;
gtevents(gteventscount).videoname=videonames{j};
gtevents(gteventscount).timeinterval=[t1(j) t2(j)];
gtevents(gteventscount).class=class;
gtevents(gteventscount).conf=1;
end
end
% parse detection results
%
if exist(detfilename,'file')~=2
error(['TH14evaldet: Could not find file ' detfilename])
end
[videonames,t1,t2,clsid,conf]=textread(detfilename,'%s%f%f%d%f');
videonames=regexprep(videonames,'\.mp4','');
clear detevents
for i=1:length(videonames)
ind=find(clsid(i)==th14classids);
if length(ind)
detevents(i).videoname=videonames{i};
detevents(i).timeinterval=[t1(i) t2(i)];
detevents(i).class=th14classnames{ind};
detevents(i).conf=conf(i);
else
fprintf('WARNING: Reported class ID %d is not among THUMOS14 detection classes.\n')
end
end
% Evaluate per-class PR for multiple overlap thresholds
%
ap_all=[];
clear pr_all
for i=1:length(th14classnames)
class=th14classnames{i};
classid=strmatch(class,th14classnames,'exact');
assert(length(classid)==1);
[rec,prec,ap]=TH14eventdetpr(detevents,gtevents,class,threshold);
pr_all(i,1).class=class;
pr_all(i,1).classid=classid;
pr_all(i,1).overlapthresh=threshold;
pr_all(i,1).prec=prec;
pr_all(i,1).rec=rec;
pr_all(i,1).ap=ap;
ap_all(i,1)=ap;
fprintf('AP:%1.3f at overlap %1.1f for %s\n',ap,threshold,class)
end
map=mean(ap_all,1);
ap_all=ap_all';
fprintf('\n\nMAP: %f \n\n',map);
function [rec,prec,ap]=TH14eventdetpr(detevents,gtevents,class,overlapthresh)
gtvideonames={gtevents.videoname};
detvideonames={detevents(:).videoname};
videonames=unique(cat(2,gtvideonames,detvideonames));
%tpconf=[];
%fpconf=[];
unsortConf=[];
unsortFlag=[];
npos=length(strmatch(class,{gtevents.class},'exact'));
assert(npos>0)
indgtclass=strmatch(class,{gtevents.class},'exact');
indambclass=strmatch('Ambiguous',{gtevents.class},'exact');
inddetclass=strmatch(class,{detevents.class},'exact');
if length(inddetclass)==0
fprintf('Class %s no instance, skip\n',class);
rec=0;
prec=0;
ap=0;
return;
end
correctPortion=zeros(length(videonames),1);
groundNum=zeros(length(videonames),1);
for i=1:length(videonames)
correctPortionName{i,1}=videonames{i};
gt=gtevents(intersect(strmatch(videonames{i},gtvideonames,'exact'),indgtclass));
amb=gtevents(intersect(strmatch(videonames{i},gtvideonames,'exact'),indambclass));
det=detevents(intersect(strmatch(videonames{i},detvideonames,'exact'),inddetclass));
groundNum(i) = length(gt);
if length(det)
[vs,is]=sort(-[det(:).conf]);
det=det(is);
conf=[det(:).conf];
indfree=ones(1,length(det));
indamb=zeros(1,length(det));
% interesct event detection intervals with GT
if length(gt)
ov=intervaloverlapvalseconds(cat(1,gt(:).timeinterval),cat(1,det(:).timeinterval));
for k=1:size(ov,1)
ind=find(indfree);
[vm,im]=max(ov(k,ind));
if vm>overlapthresh
indfree(ind(im))=0;
end
end
end
% respect ambiguous events (overlapping detections will be removed from the FP list)
if length(amb)
ovamb=intervaloverlapvalseconds(cat(1,amb(:).timeinterval),cat(1,det(:).timeinterval));
indamb=sum(ovamb,1);
end
idx1 = find(indfree==0);
idx2 = find(indfree==1 & indamb==0);
flag = [ones(size(idx1)) 2*ones(size(idx2))];
[idxall, ttIdx] = sort([idx1 idx2]);
flagall = flag(ttIdx);
unsortConf = [unsortConf conf(idxall)];
unsortFlag = [unsortFlag flagall];
%tpconf=[tpconf conf(find(indfree==0))];
%fpconf=[fpconf conf(find(indfree==1))];
%fpconf=[fpconf conf(find(indfree==1 & indamb==0))];
if length(gt)~=0
correctPortion(i) = length(find(indfree==0))/length(gt);
end
end
end
%conf=[tpconf fpconf; 1*ones(size(tpconf)) 2*ones(size(fpconf))];
conf=[unsortConf; unsortFlag];
[vs,is]=sort(-conf(1,:));
tp=cumsum(conf(2,is)==1);
fp=cumsum(conf(2,is)==2);
tmp=conf(2,is)==1;
rec=tp/npos;
prec=tp./(fp+tp);
ap=prap(rec,prec,tmp,npos);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ap=prap(rec,prec,tmp,npos)
ap=0;
for i=1:length(prec)
if tmp(i)==1
ap=ap+prec(i);
end
end
ap=ap/npos;
|
github | dariodematties/Dirichlet-master | libsvm_test.m | .m | Dirichlet-master/libsvm_test.m | 2,992 | utf_8 | 2e8a59d245cc070ad3f48f3c51522537 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: libsvm_test.m
# Language: GNU Octave high-level interpreted language.
function libsvm_test()
Average_Accuracy = 0;
Average_Clustering_Accuracy = 0;
# load the files needed to feed libsvm
i=0;
string = ['Testing_Data' num2str(i)];
string = [string '.mat'];
string1 = ['Testing_Output_Data' num2str(i)];
string1 = [string1 '.mat'];
while (exist (string) && exist (string1))
load (string)
disp(['Testing libsvm with data from file ' string])
disp("\n")
testing_instance_matrix = double(data.samples);
testing_label_vector = double(data.labels');
libsvm_options = '';
# test libsvm for Testing_Data
load(['SVM_Model' num2str(i) '.mat'])
model = best_model;
cd ~/Downloads/libsvm-3.22/matlab
[predicted_label, accuracy, prob_estimates] = svmpredict(testing_label_vector, testing_instance_matrix, model, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
disp(['For the SVM_Model' num2str(i) 'inputs to the model we have:']);
disp("accuracy");
disp(accuracy);
Average_Accuracy += accuracy(1);
save(['SVM_Model_Performance' num2str(i) '.mat'], 'predicted_label', 'accuracy', 'prob_estimates')
load (string1)
disp(['Testing libsvm with data from file ' string1])
disp("\n")
testing_instance_matrix = double(data.SDRs);
testing_label_vector = double(data.tags');
libsvm_options = '';
# test libsvm for Testing_Data
load(['Clustering_SVM_Model' num2str(i) '.mat'])
model = best_model;
cd ~/Downloads/libsvm-3.22/matlab
[predicted_label, accuracy, prob_estimates] = svmpredict(testing_label_vector, testing_instance_matrix, model, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
disp(['For the Clustering_SVM_Model' num2str(i) 'inputs to the model we have:']);
disp("accuracy");
disp(accuracy);
Average_Clustering_Accuracy += accuracy(1);
save(['Clustering_SVM_Model_Performance' num2str(i) '.mat'], 'predicted_label', 'accuracy', 'prob_estimates')
i = i+1;
string = ['Testing_Data' num2str(i)];
string = [string '.mat'];
string1 = ['Testing_Output_Data' num2str(i)];
string1 = [string1 '.mat'];
endwhile
disp('Average Accuracy in the input is: ')
Average_Accuracy/i
disp('Average Clustering Accuracy in the input is: ')
Average_Clustering_Accuracy/i
endfunction
|
github | dariodematties/Dirichlet-master | libsvm_train.m | .m | Dirichlet-master/libsvm_train.m | 7,306 | utf_8 | 726572a0c0bca0b6006f73a76ef809d3 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: libsvm_train.m
# Language: GNU Octave high-level interpreted language.
function libsvm_train(kernel_type)
if ( nargin ~= 1 )
error('Bad number of input arguments')
endif
if ( kernel_type ~= 0 && kernel_type ~= 2 )
error('Bad kernel type')
endif
# load the files needed to feed libsvm
i=0;
string = ['Inference_Data' num2str(i)];
string = [string '.mat'];
string1 = ['Inference_Output_Data' num2str(i)];
string1 = [string1 '.mat'];
samples_av_model = 0;
clustering_av_model = 0;
while (exist (string) && exist (string1))
load (string)
disp(['Training libsvm with data from file ' string])
disp("\n")
training_label_vector = double(data.labels');
if ( kernel_type == 2 )
options = '-t 2 -v 5 -q';
else
options = '-t 0 -v 5 -q';
endif
# train libsvm for Inference_Data
best_model = 0;
best_cost = 1;
training_instance_matrix = double(data.samples);
if ( kernel_type == 2 )
% coarse training
for c = -5:15
for g = -15:3
libsvm_options = [options ' -c ' num2str(2^c) ' -g ' num2str(2^g)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
best_gamma = g;
end
end
end
% fine-grained training
costs = [best_cost-1:0.1:best_cost+1];
gammas = [best_gamma-1:0.1:best_gamma+1];
for c = costs
for g = gammas
libsvm_options = [options ' -c ' num2str(2^c) ' -g ' num2str(2^g)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
best_gamma = g;
end
end
end
disp('The best model for inputs gives Accuracy = ');
disp(best_model);
training_options = ['-t 2 -q -c ' num2str(2^best_cost) ' -g ' num2str(2^best_gamma)];
best_model = svmtrain(training_label_vector, training_instance_matrix, [training_options]);
else
# coarse training
for c = -5:15
libsvm_options = [options " -c " num2str(2^c)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
endif
endfor
# fine-grained training
costs = [best_cost-1:0.1:best_cost+1];
for c = costs
libsvm_options = [options " -c " num2str(2^c)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
endif
endfor
disp("The best model for inputs gives Accuracy = ");
disp(best_model);
samples_av_model += best_model;
training_options = ['-t 0 -q -c ' num2str(2^best_cost)];
cd ~/Downloads/libsvm-3.22/matlab
best_model = svmtrain(training_label_vector, training_instance_matrix, [training_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
endif
# Saves the SVM model
fileName = ['SVM_Model' num2str(i) '.mat'];
save(fileName, 'best_model', 'best_cost')
load (string1)
disp("\n")
disp(['Training libsvm with data from file ' string1])
disp("\n")
disp(['The sparsity of the data is: ' num2str(1.0 - (sum(sum(data.SDRs)/prod(size(data.SDRs)))))])
disp("\n")
training_label_vector = double(data.tags');
if ( kernel_type == 2 )
options = '-t 2 -v 5 -q';
else
options = '-t 0 -v 5 -q';
endif
# train libsvm for Inference_Output_Data
best_model = 0;
best_cost = 1;
training_instance_matrix = double(data.SDRs);
if ( kernel_type == 2 )
% coarse training
for c = -5:15
for g = -15:3
libsvm_options = [options ' -c ' num2str(2^c) ' -g ' num2str(2^g)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
best_gamma = g;
end
end
end
% fine-grained training
costs = [best_cost-1:0.1:best_cost+1];
gammas = [best_gamma-1:0.1:best_gamma+1];
for c = costs
for g = gammas
libsvm_options = [options ' -c ' num2str(2^c) ' -g ' num2str(2^g)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
best_gamma = g;
end
end
end
disp('The best model for inputs gives Accuracy = ');
disp(best_model);
cd ~/Downloads/libsvm-3.22/matlab
training_options = ['-t 2 -q -c ' num2str(2^best_cost) ' -g ' num2str(2^best_gamma)];
best_model = svmtrain(training_label_vector, training_instance_matrix, [training_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
else
# coarse training
for c = -5:15
libsvm_options = [options " -c " num2str(2^c)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
endif
endfor
# fine-grained training
costs = [best_cost-1:0.1:best_cost+1];
for c = costs
libsvm_options = [options " -c " num2str(2^c)];
cd ~/Downloads/libsvm-3.22/matlab
model = svmtrain(training_label_vector, training_instance_matrix, [libsvm_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
if (model > best_model)
best_model = model;
best_cost = c;
endif
endfor
disp("The best model for inputs gives Accuracy = ");
disp(best_model);
clustering_av_model += best_model;
training_options = ['-t 0 -q -c ' num2str(2^best_cost)];
cd ~/Downloads/libsvm-3.22/matlab
best_model = svmtrain(training_label_vector, training_instance_matrix, [training_options]);
cd ~/Contenidos/Tomasello/Dirichlet/Software
endif
# Saves the SVM model
fileName = ['Clustering_SVM_Model' num2str(i) '.mat'];
save(fileName, 'best_model', 'best_cost')
i = i+1;
string = ['Inference_Data' num2str(i)];
string = [string '.mat'];
string1 = ['Inference_Output_Data' num2str(i)];
string1 = [string1 '.mat'];
endwhile
disp('Average training from samples is')
samples_av_model/i
disp('Clustering average training is')
clustering_av_model/i
endfunction
|
github | dariodematties/Dirichlet-master | Stick_breaking_process.m | .m | Dirichlet-master/Stick_breaking_process.m | 1,873 | utf_8 | 25553562352c6bca5304da7a3ab5706f | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Stick_breaking_process.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet process through the stick breaking method.
# Those random samples are probability mass functions (pmf).
# Inputs:
# num_weights: This is the number of weightsl in which the stick is breaken.
# alpha: Dispersion parameter of the Dirichlet process. This parameter is a scalar.
# Outputs:
# weights: A vector with the stick weights
# Examples:
#
# Stick_breaking_process(10,1)
#
# 1 2 3 4 1 3 4 3 1 1
function weights = Stick_breaking_process(num_weights, alpha)
# checks the function arguments
if (nargin != 2)
usage ("Stick_breaking_process(num_weights, alpha)");
endif
if (!isscalar(alpha) || alpha<=0)
error("alpha must be a scalar and it must be >0")
endif
if (mod(num_weights,1) != 0 || num_weights <= 0 || !isscalar(num_weights))
error("num_weights must be a scalar natural value >0")
endif
# computes a vector with all betas
betas = betarnd(1, alpha, 1, num_weights-1);
remaining_stick_lengths = cumprod(1-betas);
weights = [betas 1].*[1 remaining_stick_lengths];
endfunction
|
github | dariodematties/Dirichlet-master | Chinese_restaurant_process.m | .m | Dirichlet-master/Chinese_restaurant_process.m | 2,427 | utf_8 | 891e80fc00893ba5ed961a644685ca1c | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Chinese_restaurant_process.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet process through the Chinese restaurant method.
# Those random samples are probability mass functions (pmf).
# Inputs:
# num_customers: This is the number of customers to which assign tables.
# alpha: Dispersion parameter of the Dirichlet process. This parameter is a scalar.
# Outputs:
# table_assignments: A vector with the table assignments in the restaurante.
# Examples:
#
# Chinese_restaurant_process(10,1)
#
# 1 2 3 4 1 3 4 3 1 1
function table_assignments = Chinese_restaurant_process(num_customers, alpha)
# checks the function arguments
if (nargin != 2)
usage ("Chinese_restaurant_process(num_customers, alpha)");
endif
if (!isscalar(alpha) || alpha<=0)
error("alpha must be a scalar and it must be >0")
endif
if (mod(num_customers,1) != 0 || num_customers <= 0 || !isscalar(num_customers))
error("num_customers must be a scalar natural value >0")
endif
table_assignments = [1]; # first customer sits at table 1
next_open_table = 2; # index of the next empty table
# generates the table assignments for the rest of the customers.
for i = 2:num_customers
if (rand < alpha/(alpha + i))
# a new customer sits at a new table.
table_assignments = [table_assignments next_open_table];
next_open_table += 1;
else
# a new customer sits at an existing table.
# this customer chooses which table to sit at by giving equal weight to each
# customer already sitting at a table.
which_table = table_assignments(randi(length(table_assignments)));
table_assignments = [table_assignments which_table];
end
end
endfunction
|
github | dariodematties/Dirichlet-master | Polya_urn_Dir_proc_function.m | .m | Dirichlet-master/Polya_urn_Dir_proc_function.m | 2,545 | utf_8 | a8c9415309f451b626869209d5506950 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Polya_urn_Dir_proc_function.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet process through the Pólya's urn method. Those random samples are probability mass functions (pmf).
# Inputs:
# base_color_distribution: This is a function handle. This must be a color distribution to sample new colors.
# num_balls: This is the number of balls tu put in the urn.
# alpha: Dispersion parameter of the Dirichlet process. This parameter is a scalar.
# Outputs:
# balls_in_urn: A vector with the balls in the urn.
# Examples:
#
# random_color = @() randi(100)/100;
# Polya_urn_Dir_proc_function(random_color,10,1)
#
# 0.56000 0.56000 0.66000 0.88000 0.88000 0.66000 0.55000 0.66000 0.88000 0.66000
function balls_in_urn = Polya_urn_Dir_proc_function(base_color_distribution, num_balls, alpha)
# checks the function arguments
if (nargin != 3)
usage ("Polya_urn_Dir_proc_function(base_color_distribution, num_balls, alpha)");
endif
if (!isscalar(alpha) || alpha<=0)
error("alpha must be a scalar and it must be >0")
endif
if (mod(num_balls,1) != 0 || num_balls <= 0 || !isscalar(num_balls))
error("num_balls must be a scalar natural value >0")
endif
if (!is_function_handle(base_color_distribution))
error("base_color_distribution must be a function handle")
endif
balls_in_urn = []; # this array represents the unr in which the balls are
for i = 1:num_balls
if (rand < alpha/(alpha+length(balls_in_urn)))
# draws a new color, puts a ball of this color in the urn
new_color = base_color_distribution();
balls_in_urn = [balls_in_urn new_color];
else
# draws a ball from the urn, add another ball of the same color
ball = balls_in_urn(randi(length(balls_in_urn)));
balls_in_urn = [balls_in_urn ball];
endif
endfor
endfunction
|
github | dariodematties/Dirichlet-master | Gamma_Dir_dist_function.m | .m | Dirichlet-master/Gamma_Dir_dist_function.m | 1,735 | utf_8 | 435fbd89996a9b39796206b667680fb3 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Gamma_Dir_dist_function.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet distribution through the generating random variables
# from the Gamma distribution. Those random samples are probability mass functions (pmf).
# Inputs:
# alpha: Parameter of the Dirichlet distribution Dir(alpha). This parameter is a column vector of k components.
# Outputs:
# Q_vector: A k components vector which is a pmf.
function Q_vector = Gamma_Dir_dist_function(alpha)
# checks the function arguments
if (nargin != 1)
usage ("Gamma_Dir_dist_function (alpha)");
endif
[k, a]=size(alpha); # Extracts the number of components from the parameter vector alpha and put it in k.
if (a!=1)
error("alpha must be a column vector with a dimensionality (k,1)")
endif
if (any(alpha<=0))
error("alpha components must be >0")
endif
z=gamrnd(alpha',1); # Generates a k drawns from the Gamma distribution.
Q_vector=z/(sum(z)); # Returns the output vector.
endfunction
|
github | dariodematties/Dirichlet-master | Stick_breaking_Dir_dist_function.m | .m | Dirichlet-master/Stick_breaking_Dir_dist_function.m | 2,183 | utf_8 | 6bda883c6e7e4e14d89f65c6f88eb79d | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Stick_breaking_Dir_dist_function.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet distribution through the Stick-breaking method. Those random samples are probability mass functions (pmf).
# Inputs:
# alpha: Parameter of the Dirichlet distribution Dir(alpha). This parameter is a column vector of k components.
# Outputs:
# Q_vector: A k components vector which is a pmf.
function Q_vector = Stick_breaking_Dir_dist_function(alpha)
# checks the function arguments
if (nargin != 1)
usage ("Stick_breaking_Dir_dist_function (alpha)");
endif
[k, a]=size(alpha); # Extracts the number of components from the parameter vector alpha and put it in k.
if (a!=1)
error("alpha must be a column vector with a dimensionality (k,1)")
endif
if (any(alpha<=0))
error("alpha components must be >0")
endif
alpha=alpha'; # tramposes alpha and transforms it into a row vector
alpha_sum=flip(cumsum(flip(alpha(1,2:end)))); # accumulates alpha's components i.e. alpha=[1,2,3,4,5] then alpha_sum=[14,12,9,5]
u=betarnd(alpha(1,1:end-1),alpha_sum); # generates samples from beta dist [u1 u2 u3 u4]=betarnd([1,2,3,4],[14,12,9,5])
remainder=cumprod(1-u); # computes the stick remainders [(1-u1) (1-u1)(1-u2) (1-u1)(1-u2)(1-u3) (1-u1)(1-u2)(1-u3)(1-u4)]
Q_vector=[u 1].*[1 remainder]; # element wise mult [1*u1 (1-u1)*u2 (1-u1)(1-u2)*u3 (1-u1)(1-u2)(1-u3)*u4 (1-u1)(1-u2)(1-u3)(1-u4)*1]
endfunction
|
github | dariodematties/Dirichlet-master | DrawLattice.m | .m | Dirichlet-master/DrawLattice.m | 1,575 | utf_8 | c759ef6c15f031920b17e6c28d9e0933 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: DrawLattice.m
# Language: GNU Octave high-level interpreted language.
#This function draws the lattice.
function DrawLattice(weights, dimensionsOfArray)
hold on;
for i = 0:rows(weights)-2
for j = i+1:rows(weights)-1
coordinates1 = unravelIndex(i, dimensionsOfArray);
coordinates2 = unravelIndex(j, dimensionsOfArray);
distance = sum(abs(coordinates1-coordinates2));
if (distance == 1)
index1 = i+1;
index2 = j+1;
if (columns(weights) == 2)
plot([weights(index1,1) weights(index2,1)],[weights(index1,2) weights(index2,2)],'b');
elseif (columns(weights) == 3)
plot3([weights(index1,1) weights(index2,1)],[weights(index1,2) weights(index2,2)],[weights(index1,3) weights(index2,3)],'b');
else
error("inputDimensionality exceeds the plots' possibilities.")
endif
endif
endfor
endfor
hold off;
endfunction
|
github | dariodematties/Dirichlet-master | ravelMultiIndex.m | .m | Dirichlet-master/ravelMultiIndex.m | 2,222 | utf_8 | bafd20eacc475ea6190e4073e143bb42 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: ravelMultiIndex.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet process through the Chinese restaurant method.
# Those random samples are probability mass functions (pmf).
# Inputs:
# coordinatesOfArray: These are the coordinates of the element in the array from which we want its flat position index.
# dimensionsOfArray: These are the dimensions of the array.
# Outputs:
# index: This is the flat position index of the element in the array.
# Examples:
#
# octave:2> ravelMultiIndex([2,0],[3,5])
# ans = 10
function index = ravelMultiIndex(coordinatesOfArray, dimensionsOfArray)
if length(coordinatesOfArray) != length(dimensionsOfArray)
error("the two input arrays have different number of elements\n")
endif
for i = 1:length(coordinatesOfArray)
if coordinatesOfArray(i) >= dimensionsOfArray(i)
string = ["Coordinate " num2str(i) " overflow its dimension\n"];
error(string)
endif
endfor
numberOfCoordinates = length(dimensionsOfArray);
if numberOfCoordinates == 1
index = coordinatesOfArray;
else
index = 0;
for i = 1:numberOfCoordinates
if dimensionsOfArray(i) <= 0 || coordinatesOfArray(i) < 0
error("at least one array dimension or array coordinate is <= 0\n")
endif
product = 1;
if i < numberOfCoordinates
for j = 2+(i-1):numberOfCoordinates
product *= dimensionsOfArray(j);
endfor
endif
index += product*coordinatesOfArray(i);
endfor
endif
endfunction
|
github | dariodematties/Dirichlet-master | Plot_Dir_proc_points.m | .m | Dirichlet-master/Plot_Dir_proc_points.m | 5,549 | utf_8 | 2b47bce1503ea4a50c4aeadcecf9566e | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Plot_Dir_proc_points.m
# Language: GNU Octave high-level interpreted language.
# This function plots the points generated by a Dirichlet distribution in its simplex
# The Dirichlet distribution can be generated by means of three methods:
# Pólya's urn, stick-breaking and Gamma distribution.
# Inputs:
# alpha: Dispersion parameter of the Dirichlet process. This parameter is a scalar.
# method The method by means of which the process is carried out
# points The number of points to be drawn
# color_dist This is a function handle. This must be a color distribution to sample new colors.
# This is used for the Polya's urn
# Outputs:
# no return value.
function Plot_Dir_proc_points(alpha,method,points,color_dist)
# checks the function arguments
if (nargin != 3 && nargin != 4)
str = ["Plot_Dir_proc_points (alpha,method,points,color_dist)\n"];
str = [str "# Inputs:\n"];
str = [str "# alpha: Dispersion parameter of the Dirichlet process. This parameter is a scalar.\n"];
str = [str "# method The method by means of which the process is carried out\n"];
str = [str "method can be chinese, polya or stick\n"];
str = [str "# points The number of points to be drawn\n"];
str = [str "# color_dist This is a function handle. This must be a color distribution to sample new colors.\n"];
str = [str "# This is used for the Polya's urn\n"];
usage(str);
endif
# alpha must be a scalar greater than 0
if (!isscalar(alpha) || alpha<=0)
error("alpha must be a scalar and it must be >0")
endif
# method argument has to be a string
if (!ischar(method))
error("method must be of class string")
endif
# points has to be a scalar natural value
if (!isscalar(points) || mod(points,1) != 0 || points <= 0)
error("points must be a scalar natural value")
endif
# color_dist must be a function handle
if (nargin == 4 && (!is_function_handle(color_dist)))
error("color_dist must be a function handle")
endif
if (strcmp(method,"polya")) # if polya method is chosen
if (nargin != 4)
error("when you choose 'polya' method you have to provide 'color_dist' as the fourth argument")
endif
subplot(2,2,1);
urn = Polya_urn_Dir_proc_function(color_dist,points,alpha);
hist(urn,100);
xlabel("color of balls")
ylabel("number of balls in every color")
subplot(2,2,2);
plot(1:points,urn,"*");
xlabel("ball number","fontsize", 12)
ylabel("color of the balls","fontsize", 12)
balls_per_color=[];
for i=1:length(urn)
balls_per_color=[balls_per_color i/length(unique(urn(1,1:i)))];
endfor
subplot(2,2,3);
plot(1:points,balls_per_color,"*");
xlabel("ball number","fontsize", 12)
ylabel("balls per color","fontsize", 12)
balls_per_color=[];
color_hist=hist(urn,unique(urn));
for i=1:length(color_hist)
balls_per_color=[balls_per_color sum(color_hist(1,1:i))/i];
endfor
subplot(2,2,4);
plot(1:length(color_hist),balls_per_color,"*");
xlabel("number of colors","fontsize", 12)
ylabel("balls per color","fontsize", 12)
str = ["Polya's urn Dirichlet process, number of balls: " num2str(points) ", alpha: " num2str(alpha) "."];
suptitle(str)
elseif (strcmp(method,"stick")) # if stick method is chosen
if (nargin != 3)
error("when you choose 'stick' method you have to provide three arguments")
endif
weights = Stick_breaking_process(points, alpha);
bar(weights)
xlabel("number of bar","fontsize", 12);
ylabel("bar weghts","fontsize", 12);
str = ["Stick breaking process. Number of weights is: " num2str(points) ", alpha is: " num2str(alpha) "."];
title(str);
elseif (strcmp(method, "chinese")) # if chinese method is chosen
if (nargin != 3)
error("when you choose 'chinese' method you have to provide three arguments")
endif
subplot(2,2,1);
rest = Chinese_restaurant_process(points,alpha);
hist(rest,100);
xlabel("table of customers","fontsize", 12)
ylabel("number of customers in every table","fontsize", 12)
subplot(2,2,2);
plot(1:points,rest,"*");
xlabel("customer number","fontsize", 12)
ylabel("table of the customers","fontsize", 12)
customers_per_table=[];
for i=1:length(rest)
customers_per_table=[customers_per_table i/length(unique(rest(1,1:i)))];
endfor
subplot(2,2,3);
plot(1:points,customers_per_table,"*");
xlabel("customer number","fontsize", 12)
ylabel("customers per table","fontsize", 12)
customers_per_table=[];
table_hist=hist(rest,unique(rest));
for i=1:length(table_hist)
customers_per_table=[customers_per_table sum(table_hist(1,1:i))/i];
endfor
subplot(2,2,4);
plot(1:length(table_hist),customers_per_table,"*");
xlabel("number of tables","fontsize", 12)
ylabel("customers per table","fontsize", 12)
str = ["Chinese restaurant process, number of customers: " num2str(points) ", alpha: " num2str(alpha) "."];
suptitle(str)
else
error("incorrect method: you can choose polya, stick or chinese as allowed methods")
endif
endfunction
|
github | dariodematties/Dirichlet-master | Polya_urn_Dir_dist_function.m | .m | Dirichlet-master/Polya_urn_Dir_dist_function.m | 2,518 | utf_8 | 313944ef7a5ec59c47af1a3f5ba66df3 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Polya_urn_Dir_dist_function.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet distribution through the Pólya's urn method. Those random samples are probability mass functions (pmf).
# Inputs:
# alpha: Parameter of the Dirichlet distribution Dir(alpha). This parameter is a column vector of k components.
# N_iterations: Number of iterations to generate a random sample.
# Outputs:
# Q_vector: A k components vector which is a pmf.
function Q_vector = Polya_urn_Dir_dist_function(alpha, N_iterations)
# checks the function arguments
if (nargin != 2)
usage ("Polya_urn_Dir_dist_function (alpha, N_iterations)");
endif
[k, a]=size(alpha); # Extracts the number of components from the parameter vector alpha and put it in k.
if (a!=1)
error("alpha must be a column vector with a dimensionality (k,1)")
endif
if (any(alpha<=0))
error("alpha components must be >0")
endif
if (mod(N_iterations,1) != 0 || N_iterations <= 0 || !isscalar(N_iterations))
error("N_iterations must be a scalar natural value >0")
endif
alpha_0=sum(alpha); # Sums all the components of alpha.
p=alpha/alpha_0; # Determines a pmf vector for use it in the multinomial distribution.
q=zeros(k,1); # Prepares the output vector
for i=1:N_iterations
x=mnrnd(1,p); # Extracts a ball from the urn.
q=q+x'; # Adds the color of the ball.
alpha=alpha+x'; # Return the ball to the urn with another ball of the same color.
alpha_0=sum(alpha); # Sums all the components of alpha.
p=alpha/alpha_0; # Determines a pmf vector for use it in the multinomial distribution.
endfor
q_0=sum(q); # Sums all the components of q.
Q_vector=q/q_0; # Determines a pmf vector for use it in the multinomial distribution.
endfunction
|
github | dariodematties/Dirichlet-master | Plot_Dir_dist_points.m | .m | Dirichlet-master/Plot_Dir_dist_points.m | 4,473 | utf_8 | 1f5c93dc377fca4587a79f5970601d3c | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: Plot_Dir_dist_points.m
# Language: GNU Octave high-level interpreted language.
# This function plots the points generated by a Dirichlet distribution in its simplex
# The Dirichlet distribution can be generated by means of three methods:
# Pólya's urn, stick-breaking and Gamma distribution.
# Inputs:
# alpha: Parameter of the Dirichlet distribution Dir(alpha). This parameter is a column vector of k components.
# method The method by means of which the distribution is generated
# points The number of points to be drawn from the Dirichlet distribution
# iterations This is an optinal parameter only used for Polya's urn method.
# It is the number of iterations to be used in order to generate the distribution
# Outputs:
# no return value.
function Plot_Dir_dist_points(alpha,method,points,iterations)
# checks the function arguments
if (nargin != 3 && nargin != 4)
str = ["Plot_Dir_dist_points (alpha,method,points,iterations)\n"];
str = [str "# Inputs:\n"];
str = [str "# alpha: Parameter of the Dirichlet distribution Dir(alpha). This parameter is a column vector of k components.\n"];
str = [str "# method The method by means of which the distribution is generated\n"];
str = [str "method can be polya, stick or gamm\n"];
str = [str "# points The number of points to be drawn from the Dirichlet distribution\n"];
str = [str "# iterations This is an optinal parameter only used for Polya's urn method (method = polya).\n"];
str = [str "# It is the number of iterations to be used in order to generate the distribution\n"];
usage(str);
endif
[k, a]=size(alpha); # Extracts the number of components from the parameter vector alpha and put it in k.
# alpha has to be a column vector
if (a!=1)
error("alpha must be a column vector with a dimensionality (k,1)")
endif
# alpha has to be a column vector of at most k=3
if (k>3)
error("alpha has to be a column vector of at most k=3")
endif
# every element of alpha has to be >0
if (any(alpha<=0))
error("alpha components must be >0")
endif
# method argument has to be a string
if (!ischar(method))
error("method must be of class string")
endif
# points has to be a scalar natural value
if (!isscalar(points) || mod(points,1) != 0 || points <= 0)
error("points must be a scalar natural value")
endif
# itertion has to be a scalar natural value
if (nargin == 4 && (!isscalar(iterations) || mod(iterations,1) != 0 || iterations <= 0))
error("iterations must be a scalar natural value")
endif
if (strcmp(method,"polya")) # if polya method is chosen
if (nargin != 4)
error("when you choose 'polya' method you have to provide 'iterations' as the fourth argument")
endif
for i=1:points
Q(:,:,i)=Polya_urn_Dir_dist_function(alpha,iterations);
endfor
elseif (strcmp(method,"stick")) # if stick method is chosen
if (nargin != 3)
error("when you choose 'stick' method you have to provide three arguments")
endif
for i=1:points
Q(:,i)=Stick_breaking_Dir_dist_function(alpha);
endfor
elseif (strcmp(method, "gamm")) # if gamm method is chosen
if (nargin != 3)
error("when you choose 'gamm' method you have to provide three arguments")
endif
for i=1:points
Q(:,i)=Gamma_Dir_dist_function(alpha);
endfor
else
error("incorrect method: you can choose polya, stick or gamm as allowed methods")
endif
# reshape the output in order to be ploted
for i=1:points
for j=1:k
if (strcmp(method,"polya"))
A(j,i)=Q(j,1,i);
else
A(j,i)=Q(j,i);
endif
endfor
endfor
figure
if (k==3) # 3D plots
plot3(A(1,:), A(2,:), A(3,:), '*');
hold on
v = patch([1,0,0],[0,1,0],[0,0,1], 'g');
set(v,'facealpha',0.5);
hold off
axis([0 1 0 1 0 1], "square");
elseif (k==2) # 2D plots
plot(A(1,:), A(2,:), '*');
axis([0 1 0 1], "square");
endif
endfunction
|
github | dariodematties/Dirichlet-master | unravelIndex.m | .m | Dirichlet-master/unravelIndex.m | 1,840 | utf_8 | 3ef9fa450032dc8c940ea40df6acc6f9 | ##################################################################################################################
## Author: Dematties Dario Jesus ##
## Contact: [email protected] ##
## [email protected] ##
## [email protected] ##
## Project: Engineering PhD Project ##
## Institution: Universidad de Buenos Aires ##
## Facultad de Ingeniería (FIUBA) ##
## Workplace: Instituto de Ingeniería ##
## Biomédica FIUBA & ##
## CCT CONICET Mendoza INCIHUSA ##
##################################################################################################################
# File Name: unravelIndex.m
# Language: GNU Octave high-level interpreted language.
# This function generates random samples from the Dirichlet process through the Chinese restaurant method.
# Those random samples are probability mass functions (pmf).
# Inputs:
# Index: This is the flat position index of the element in the array.
# dimensionsOfArray: These are the dimensions of the array.
# Outputs:
# coordinates: These are the coordinates of the element in the array from which we want its flat position index.
# Examples:
#
# octave:1> unravelIndex(8,[3,5])
# ans =
# 1 3
function coordinates = unravelIndex(Index, dimensionsOfArray)
numberOfCoordinates = length(dimensionsOfArray);
if Index >= prod(dimensionsOfArray)
error("Index is bigger than the number of elements in the array\n")
endif
if numberOfCoordinates == 1
coordinates = Index;
else
aux = Index;
for i = numberOfCoordinates:-1:1
if dimensionsOfArray(i) <= 0
error("at least one array coordinate is <= 0\n")
endif
coordinates(i) = mod(aux,dimensionsOfArray(i));
aux = floor(aux/dimensionsOfArray(i));
endfor
endif
endfunction
|
github | kpegion/SubX-master | writeNetCDFGlobalAtts.m | .m | SubX-master/Matlab/V2/lib/writeNetCDFGlobalAtts.m | 926 | utf_8 | 05fae2dd2d98259f31b338c741992208 | %================================================================================================
%================================================================================================
function []=writeNetCDFGlobalAtts(fname,title,longtitle,comments,institution,source,matlabSource)
NC_GLOBAL = netcdf.getConstant('NC_GLOBAL');
% Open File
ncid=netcdf.open(char(fname),'WRITE');
% Global Attributes
netcdf.putAtt(ncid,NC_GLOBAL,'title',char(title));
netcdf.putAtt(ncid,NC_GLOBAL,'long_title',char(longtitle));
netcdf.putAtt(ncid,NC_GLOBAL,'comments',char(comments));
netcdf.putAtt(ncid,NC_GLOBAL,'institution',char(institution));
netcdf.putAtt(ncid,NC_GLOBAL,'source',source);
netcdf.putAtt(ncid,NC_GLOBAL,'CreationDate',datestr(now,'yyyy/mm/dd HH:MM:SS'));
netcdf.putAtt(ncid,NC_GLOBAL,'CreatedBy',getenv('LOGNAME'));
netcdf.putAtt(ncid,NC_GLOBAL,'MatlabSource',matlabSource);
% Close File
netcdf.close(ncid);
|
github | kpegion/SubX-master | setupNetCDF3D.m | .m | SubX-master/Matlab/V2/lib/setupNetCDF3D.m | 2,177 | utf_8 | 1909607bfc785f263fdd332db3645711 | %================================================================================================
% This function sets up everything for writing a netcdf file
% It assumes the following:
%
% Data to be written is dimensions (lat,lon,time)
%
% lons: standard name is 'lon'; longname is 'longitude'; units are 'degrees east'
% lats: standard name is 'lat'; longname is 'latitude'; units are 'degrees nort'
% time: standard name is 'time'; longname is 'Time of measurements; units are passed in
% fillValue and missing value for the data are the same and are passed in
% There is no scale_factor and/or offset
% Only dimenstion variables are written
% Global Attributes are not set here
%
% To add variables use: addVarNetCDF3D function
% To set global attributes use: setGlobalAtts
%================================================================================================
function []=setupNetCDF3D(fname,lons,lats,time,unitst,fillValue,type)
% Open File
ncid=netcdf.create(char(fname),'netcdf4');
% Get dimensions
nx=numel(lons);
ny=numel(lats);
nt=numel(time);
% Set file Dimensions
dimlat=netcdf.defDim(ncid,'lat',ny);
dimlon=netcdf.defDim(ncid,'lon',nx);
dimtime = netcdf.defDim(ncid,'time',nt);
% Define lons, lats, time
varid = netcdf.defVar(ncid,'lat',type,[dimlat]);
netcdf.putAtt(ncid,varid,'standard_name','latitude');
netcdf.putAtt(ncid,varid,'long_name','latitude');
netcdf.putAtt(ncid,varid,'units','degrees_north');
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(lats));
varid = netcdf.defVar(ncid,'lon',type,[dimlon]);
netcdf.putAtt(ncid,varid,'standard_name','longitude');
netcdf.putAtt(ncid,varid,'long_name','longitude');
netcdf.putAtt(ncid,varid,'units','degrees_east');
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(lons));
varid = netcdf.defVar(ncid,'time',type,[dimtime]);
netcdf.putAtt(ncid,varid,'standard_name','time');
netcdf.putAtt(ncid,varid,'long_name','Time of measurements');
netcdf.putAtt(ncid,varid,'units',unitst);
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(time));
% Close File
netcdf.close(ncid);
|
github | kpegion/SubX-master | nanfastsmooth.m | .m | SubX-master/Matlab/V2/lib/nanfastsmooth.m | 4,587 | utf_8 | f66f272406af77ed747d388ce53eaff7 | function SmoothY = nanfastsmooth(Y,w,type,tol)
% nanfastsmooth(Y,w,type,tol) smooths vector Y with moving
% average of width w ignoring NaNs in data..
%
% Y is input signal.
% w is the window width.
%
% The argument "type" determines the smooth type:
% If type=1, rectangular (sliding-average or boxcar)
% If type=2, triangular (2 passes of sliding-average)
% If type=3, pseudo-Gaussian (3 passes of sliding-average)
%
% The argument "tol" controls the amount of tolerance to NaNs allowed
% between 0 and 1. A value of zero means that if the window has any NaNs
% in it then the output is set as NaN. A value of 1 allows any number of
% NaNs in the window and will still give an answer for the smoothed signal.
% A value of 0.5 means that there must be at least half
% real values in the window for the output to be valid.
%
% The start and end of the file are treated as if there are NaNs beyond the
% dataset. As such the behaviour depends on the value of 'tol' as above.
% With 'tol' set at 0.5 the smoothed signal will start and end at the same
% time as the orgional signal. However it's accuracy will be reduced and
% the moving average will become more and more one-sided as the beginning
% and end is approached.
%
% fastsmooth(Y,w,type) smooths with tol = 0.5.
% fastsmooth(Y,w) smooths with type = 1 and tol = 0.5
%
% Version 1.0, 26th August 2015. G.M.Pittam
% - First Version
% Version 1.1, 5th October 2015. G.M.Pittam
% - Updated to correctly smooth both even and uneven window length.
% - Issue identified by Erik Benkler 5th September 2015.
% Modified from fastsmooth by T. C. O'Haver, May, 2008.
if nargin == 2, tol = 0.5; type = 1; end
if nargin == 3, tol = 0.5; end
switch type
case 1
SmoothY = sa(Y,w,tol);
case 2
SmoothY = sa(sa(Y,w,tol),w,tol);
case 3
SmoothY = sa(sa(sa(Y,w,tol),w,tol),w,tol);
end
function SmoothY = sa(Y,smoothwidth,tol)
if smoothwidth == 1
SmoothY = Y;
return
end
% Bound Tollerance
if tol<0, tol=0; end
if tol>1, tol=1; end
w = round(smoothwidth);
halfw = floor(w/2);
L = length(Y);
% Make empty arrays to store data
n = size(Y);
s = zeros(n);
np = zeros(n);
if mod(w,2)
% Initialise Sums and counts
SumPoints = NaNsum(Y(1:halfw+1));
NumPoints = sum(~isnan(Y(1:halfw+1)));
% Loop through producing sum and count
s(1) = SumPoints;
np(1) = NumPoints;
for k=2:L
if k > halfw+1 && ~isnan(Y(k-halfw-1))
SumPoints = SumPoints-Y(k-halfw-1);
NumPoints = NumPoints-1;
end
if k <= L-halfw && ~isnan(Y(k+halfw))
SumPoints = SumPoints+Y(k+halfw);
NumPoints = NumPoints+1;
end
s(k) = SumPoints;
np(k) = NumPoints;
end
else
% Initialise Sums and counts
SumPoints = NaNsum(Y(1:halfw))+0.5*Y(halfw+1);
NumPoints = sum(~isnan(Y(1:halfw)))+0.5;
% Loop through producing sum and count
s(1) = SumPoints;
np(1) = NumPoints;
for k=2:L
if k > halfw+1 && ~isnan(Y(k-halfw-1))
SumPoints = SumPoints - 0.5*Y(k-halfw-1);
NumPoints = NumPoints - 0.5;
end
if k > halfw && ~isnan(Y(k-halfw))
SumPoints = SumPoints - 0.5*Y(k-halfw);
NumPoints = NumPoints - 0.5;
end
if k <= L-halfw && ~isnan(Y(k+halfw))
SumPoints = SumPoints + 0.5*Y(k+halfw);
NumPoints = NumPoints+1;
end
s(k) = SumPoints;
np(k) = NumPoints;
end
else
% Initialise Sums and counts
SumPoints = NaNsum(Y(1:halfw))+0.5*Y(halfw+1);
NumPoints = sum(~isnan(Y(1:halfw)))+0.5;
% Loop through producing sum and count
s(1) = SumPoints;
np(1) = NumPoints;
for k=2:L
if k > halfw+1 && ~isnan(Y(k-halfw-1))
SumPoints = SumPoints - 0.5*Y(k-halfw-1);
NumPoints = NumPoints - 0.5;
end
if k > halfw && ~isnan(Y(k-halfw))
SumPoints = SumPoints - 0.5*Y(k-halfw);
NumPoints = NumPoints - 0.5;
end
if k <= L-halfw && ~isnan(Y(k+halfw))
SumPoints = SumPoints + 0.5*Y(k+halfw);
NumPoints = NumPoints + 0.5;
end
if k <= L-halfw+1 && ~isnan(Y(k+halfw-1))
SumPoints = SumPoints + 0.5*Y(k+halfw-1);
NumPoints = NumPoints + 0.5;
end
s(k) = SumPoints;
np(k) = NumPoints;
end
end
% Remove the amount of interpolated datapoints desired
np(np<max((w*(1-tol)),1)) = NaN;
% Calculate Smoothed Signal
SmoothY=s./np;
function y = NaNsum(x)
y = sum(x(~isnan(x)));
|
github | kpegion/SubX-master | writeNetCDFData3D.m | .m | SubX-master/Matlab/V2/lib/writeNetCDFData3D.m | 867 | utf_8 | b700e0acd4020b85aaf18a678c9c48cc | %================================================================================================
% This function write a 3D (lon,lat,tim) dataset to a netcdf file
%================================================================================================
function []=writeNetCDFData3D(fname,data,units,name,longname,fillValue,type)
% Open File
ncid = netcdf.open(char(fname),'WRITE');
% Dimension IDs
dimlat=netcdf.inqDimID(ncid,'lat');
dimlon=netcdf.inqDimID(ncid,'lon');
dimtime=netcdf.inqDimID(ncid,'time');
%Add Variable
varid = netcdf.defVar(ncid,char(name),type,[dimlon,dimlat,dimtime]);
netcdf.putAtt(ncid,varid,'name',char(name)');
netcdf.putAtt(ncid,varid,'long_name',char(longname));
netcdf.putAtt(ncid,varid,'units',char(units));
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,data);
% Close File
netcdf.close(ncid);
|
github | kpegion/SubX-master | writeNetCDFGlobalAtts.m | .m | SubX-master/Matlab/V1/writeNetCDFGlobalAtts.m | 926 | utf_8 | 05fae2dd2d98259f31b338c741992208 | %================================================================================================
%================================================================================================
function []=writeNetCDFGlobalAtts(fname,title,longtitle,comments,institution,source,matlabSource)
NC_GLOBAL = netcdf.getConstant('NC_GLOBAL');
% Open File
ncid=netcdf.open(char(fname),'WRITE');
% Global Attributes
netcdf.putAtt(ncid,NC_GLOBAL,'title',char(title));
netcdf.putAtt(ncid,NC_GLOBAL,'long_title',char(longtitle));
netcdf.putAtt(ncid,NC_GLOBAL,'comments',char(comments));
netcdf.putAtt(ncid,NC_GLOBAL,'institution',char(institution));
netcdf.putAtt(ncid,NC_GLOBAL,'source',source);
netcdf.putAtt(ncid,NC_GLOBAL,'CreationDate',datestr(now,'yyyy/mm/dd HH:MM:SS'));
netcdf.putAtt(ncid,NC_GLOBAL,'CreatedBy',getenv('LOGNAME'));
netcdf.putAtt(ncid,NC_GLOBAL,'MatlabSource',matlabSource);
% Close File
netcdf.close(ncid);
|
github | kpegion/SubX-master | setupNetCDF3D.m | .m | SubX-master/Matlab/V1/setupNetCDF3D.m | 2,185 | utf_8 | 759af610c6f245fec4dc0b39e63de670 | %================================================================================================
% This function sets up everything for writing a netcdf file
% It assumes the following:
%
% Data to be written is dimensions (lat,lon,time)
%
% lons: standard name is 'lon'; longname is 'longitude'; units are 'degrees east'
% lats: standard name is 'lat'; longname is 'latitude'; units are 'degrees nort'
% time: standard name is 'time'; longname is 'Time of measurements; units are passed in
% fillValue and missing value for the data are the same and are passed in
% There is no scale_factor and/or offset
% Only dimenstion variables are written
% Global Attributes are not set here
%
% To add variables use: addVarNetCDF3D function
% To set global attributes use: setGlobalAtts
%================================================================================================
function []=setupNetCDF3D(fname,lons,lats,time,unitst,fillValue)
% Open File
ncid=netcdf.create(char(fname),'netcdf4');
% Get dimensions
nx=numel(lons);
ny=numel(lats);
nt=numel(time);
% Set file Dimensions
dimlat=netcdf.defDim(ncid,'lat',ny);
dimlon=netcdf.defDim(ncid,'lon',nx);
dimtime = netcdf.defDim(ncid,'time',nt);
% Define lons, lats, time
varid = netcdf.defVar(ncid,'lat','double',[dimlat]);
netcdf.putAtt(ncid,varid,'standard_name','latitude');
netcdf.putAtt(ncid,varid,'long_name','latitude');
netcdf.putAtt(ncid,varid,'units','degrees_north');
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(lats));
varid = netcdf.defVar(ncid,'lon','double',[dimlon]);
netcdf.putAtt(ncid,varid,'standard_name','longitude');
netcdf.putAtt(ncid,varid,'long_name','longitude');
netcdf.putAtt(ncid,varid,'units','degrees_east');
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(lons));
varid = netcdf.defVar(ncid,'time','double',[dimtime]);
netcdf.putAtt(ncid,varid,'standard_name','time');
netcdf.putAtt(ncid,varid,'long_name','Time of measurements');
netcdf.putAtt(ncid,varid,'units',unitst);
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,squeeze(time));
% Close File
netcdf.close(ncid);
|
github | kpegion/SubX-master | writeNetCDFData3D.m | .m | SubX-master/Matlab/V1/writeNetCDFData3D.m | 866 | utf_8 | 62f1e1f507f982a7fab6eef811d89c5a | %================================================================================================
% This function write a 3D (lon,lat,tim) dataset to a netcdf file
%================================================================================================
function []=writeNetCDFData3D(fname,data,units,name,longname,fillValue)
% Open File
ncid = netcdf.open(char(fname),'WRITE');
% Dimension IDs
dimlat=netcdf.inqDimID(ncid,'lat');
dimlon=netcdf.inqDimID(ncid,'lon');
dimtime=netcdf.inqDimID(ncid,'time');
%Add Variable
varid = netcdf.defVar(ncid,char(name),'double',[dimlon,dimlat,dimtime]);
netcdf.putAtt(ncid,varid,'name',char(name)');
netcdf.putAtt(ncid,varid,'long_name',char(longname));
netcdf.putAtt(ncid,varid,'units',char(units));
netcdf.defVarFill(ncid,varid,false,fillValue);
netcdf.putVar(ncid,varid,data);
% Close File
netcdf.close(ncid);
|
github | yugt/ComputerVision-master | digitOpSeparate.m | .m | ComputerVision-master/Project/digitOpSeparate.m | 1,415 | utf_8 | d3121f8a12145bdab78c3eeb27084c12 | function [ op_left,op_right,operators,answers ] = digitOpSeparate( eqns,add,minus,times,divide,answers )
operators=zeros(size(eqns,1),1);
op_left=zeros(size(eqns));
op_right=zeros(size(eqns));
for i=1:size(eqns,1)
right=0;
for j=1:size(eqns,2)
if eqns(i,j)==0
break
elseif any((add==eqns(i,j)))
operators(i)=1;
right=1;
elseif any((minus==eqns(i,j)))
operators(i)=2;
right=1;
elseif any((times==eqns(i,j)))
operators(i)=3;
right=1;
elseif any((divide==eqns(i,j)))
operators(i)=4;
right=1;
else
% digits
if right==0
op_left(i,j)=eqns(i,j);
else
op_right(i,j)=eqns(i,j);
end
end
end
end
op_left(:,~any(op_left,1))=[];
op_right(:,~any(op_right,1))=[];
op_left=regularize(op_left);
op_right=regularize(op_right);
answers=regularize(answers);
op_left(:,~any(op_left,1))=[];
op_right(:,~any(op_right,1))=[];
end
function [input]=regularize(input)
for i=1:size(input,1)
while input(i,end)==0
input(i,:)=circshift(input(i,:),1);
end
% for j=size(input,2):-1:1
% if input(i,j)>0
% pos=j;
% end
%
% end
% if pos>0
% input(i,:)=circshift(input(i,:),size(input,2)-j);
% end
end
end |
github | yugt/ComputerVision-master | horizon.m | .m | ComputerVision-master/Project/horizon.m | 4,632 | utf_8 | 43889a5295a61f0b02825266b3cfb251 | function [angle] = horizon(image, varargin)
% HORIZON estimates the horizon rotation in the image.
% ANGLE=HORIZON(I) returns rotation of an estimated horizon
% in the image I. The returned value ANGLE is in the
% range <-45,45> degrees.
%
% ANGLE=HORIZON(I, PRECISION) aligns the image I with
% the predefined precision. The default value is 1 degree. If higher
% precision is required, 0.1 could be a good value.
%
% ANGLE=HORIZON(I, PRECISION, METHOD, DISKSIZE) aligns the image I with
% the specified METHOD. Following methods are supported:
% 'fft' - Fast Fourier Transform, the default method,
% 'hough' - Hough transform, which finds lines in the image,
% 'blot' - Finds blots and estimates their's orientation.
% Blot method allows additional parameter DISKSIZE that
% defines the filter size of morphological transformations.
% The default value is 7. Note that this method
% may not work for all kind of pictures.
%
% Example
% -------
% image = imread('board.tif');
% angle = horizon(rgb2gray(image), 0.1, 'fft')
% imshow(imrotate(image, -angle, 'bicubic'));
%
% The example aligns the default image in Image Processing Toolbox.
% Parameter checking.
numvarargs = length(varargin);
if numvarargs > 3 % only want 3 optional inputs at most
error('myfuns:somefun2Alt:TooManyInputs', ...
'requires at most 2 optional inputs');
end
optargs = {1, 'fft', 2}; % set defaults for optional inputs
optargs(1:numvarargs) = varargin;
[precision, method, diskSize] = optargs{:}; % use memorable variable names
% Check image dimension.
if ndims(image)~=2
error('The image must be two-dimensional (i.e. grayscale).')
end
% Call the selected method
if strcmpi(method, 'fft')
angle = horizonFFT(image, precision);
elseif strcmpi(method, 'hough')
angle = horizonHough(image, precision);
else
angle = horizonBlobs(image, precision, diskSize);
end
% Return the angle
angle = mod(45+angle,90)-45; % rotation in -45..45 range
end
function angle = horizonFFT(image, precision)
% FFT.
maxsize = max(size(image));
T = fftshift(fft2(image, maxsize, maxsize)); % create rectangular transform
T = log(abs(T)+1); % get magnitude in <0..inf)
% Combine two FFT quadrants together (another two quadrants are symetric).
center = ceil((maxsize+1)/2);
evenS = mod(maxsize+1, 2);
T = (rot90(T(center:end, 1+evenS:center), 1) + T(center:end, center:end));
T = T(2:end, 2:end); % remove artifacts for expense of inaccuracy
% Find the dominant orientation
angles = floor(90/precision);
score = zeros(angles, 1);
maxDist = maxsize/2-1;
for angle = 0:angles-1
[y,x] = pol2cart(deg2rad(angle*precision), 0:maxDist-1); % all [x,y]
for i = 1:maxDist
score(angle+1) = score(angle+1) + T(round(y(i)+1), round(x(i)+1));
end
end
% Return the most dominant direction.
[~, position] = max(score);
angle = (position-1)*precision;
end
function angle = horizonHough(image, precision)
% Detect edges.
BW = edge(image,'prewitt');
% Perform the Hough transform.
[H, T, ~] = hough(BW,'Theta',-90:precision:90-precision);
% Find the most dominant line direction.
data=var(H); % measure variance at each angle
fold=floor(90/precision); % assume right angles & fold data
data=data(1:fold) + data(end-fold+1:end);
[~, column] = max(data); % the column with the crispiest peaks
angle = -T(column); % column to degrees
end
function angle = horizonBlobs(image, precision, diskSize)
% perform morphological operations
bw = im2bw(image);
bw = imopen(bw, strel('disk', diskSize)); % fill holes
bw = imclose(bw, strel('disk', diskSize)); % remove spackles
% get region properties
stat = regionprops(~bw, 'Area', 'BoundingBox', 'Orientation');
% select only some blobs
dimensions = cat(1, stat.BoundingBox);
area = cat(1, stat.Area);
boundingBoxArea = dimensions(:,3).*dimensions(:,4);
areaRatio = boundingBoxArea./area;
% create histogram of orientations in the picture
histogram = hist(cat(1, stat(areaRatio>1.2).Orientation), -90:precision:90);
% fold the histogram
len = ceil(length(histogram)/2);
histogram = histogram(1:len)+histogram(len:end);
% find the peak and return the dominant orientation
[~, index] = max(histogram);
angle = mod(-precision*(index-1)+45,90)-45; % index -> angle
end |
github | yugt/ComputerVision-master | ginput2.m | .m | ComputerVision-master/Lectures/0907_math_background/ginput2.m | 6,307 | utf_8 | 9a3aa4e541096e823c927053daa3bc42 | function [out1,out2,out3] = ginput2(arg1)
%GINPUT Graphical input from mouse.
% [X,Y] = GINPUT(N) gets N points from the current axes and returns
% the X- and Y-coordinates in length N vectors X and Y. The cursor
% can be positioned using a mouse (or by using the Arrow Keys on some
% systems). Data points are entered by pressing a mouse button
% or any key on the keyboard except carriage return, which terminates
% the input before N points are entered.
%
% [X,Y] = GINPUT gathers an unlimited number of points until the
% return key is pressed.
%
% [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that
% contains a vector of integers specifying which mouse button was
% used (1,2,3 from left) or ASCII numbers if a key on the keyboard
% was used.
% Copyright (c) 1984-96 by The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 2003/10/07 18:07:16 $
% Fixed version by Jean-Yves Bouguet to have a cross instead of 2 lines
% More visible for images
out1 = []; out2 = []; out3 = []; y = [];
c = computer;
if ~strcmp(c(1:2),'PC') & ~strcmp(c(1:2),'MA')
tp = get(0,'TerminalProtocol');
else
tp = 'micro';
end
if ~strcmp(tp,'none') & ~strcmp(tp,'x') & ~strcmp(tp,'micro'),
if nargout == 1,
if nargin == 1,
eval('out1 = trmginput(arg1);');
else
eval('out1 = trmginput;');
end
elseif nargout == 2 | nargout == 0,
if nargin == 1,
eval('[out1,out2] = trmginput(arg1);');
else
eval('[out1,out2] = trmginput;');
end
if nargout == 0
out1 = [ out1 out2 ];
end
elseif nargout == 3,
if nargin == 1,
eval('[out1,out2,out3] = trmginput(arg1);');
else
eval('[out1,out2,out3] = trmginput;');
end
end
else
fig = gcf;
figure(gcf);
if nargin == 0
how_many = -1;
b = [];
else
how_many = arg1;
b = [];
if isstr(how_many) ...
| size(how_many,1) ~= 1 | size(how_many,2) ~= 1 ...
| ~(fix(how_many) == how_many) ...
| how_many < 0
error('Requires a positive integer.')
end
if how_many == 0
ptr_fig = 0;
while(ptr_fig ~= fig)
ptr_fig = get(0,'PointerWindow');
end
scrn_pt = get(0,'PointerLocation');
loc = get(fig,'Position');
pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
out1 = pt(1); y = pt(2);
elseif how_many < 0
error('Argument must be a positive integer.')
end
end
pointer = get(gcf,'pointer');
set(gcf,'pointer','crosshair');
fig_units = get(fig,'units');
char = 0;
while how_many ~= 0
% Use no-side effect WAITFORBUTTONPRESS
waserr = 0;
eval('keydown = wfbp;', 'waserr = 1;');
if(waserr == 1)
if(ishandle(fig))
set(fig,'pointer',pointer,'units',fig_units);
error('Interrupted');
else
error('Interrupted by figure deletion');
end
end
ptr_fig = get(0,'CurrentFigure');
if(ptr_fig == fig)
if keydown
char = get(fig, 'CurrentCharacter');
button = abs(get(fig, 'CurrentCharacter'));
scrn_pt = get(0, 'PointerLocation');
set(fig,'units','pixels')
loc = get(fig, 'Position');
pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)];
set(fig,'CurrentPoint',pt);
else
button = get(fig, 'SelectionType');
if strcmp(button,'open')
button = b(length(b));
elseif strcmp(button,'normal')
button = 1;
elseif strcmp(button,'extend')
button = 2;
elseif strcmp(button,'alt')
button = 3;
else
error('Invalid mouse selection.')
end
end
pt = get(gca, 'CurrentPoint');
how_many = how_many - 1;
if(char == 13) % & how_many ~= 0)
% if the return key was pressed, char will == 13,
% and that's our signal to break out of here whether
% or not we have collected all the requested data
% points.
% If this was an early breakout, don't include
% the <Return> key info in the return arrays.
% We will no longer count it if it's the last input.
break;
end
out1 = [out1;pt(1,1)];
y = [y;pt(1,2)];
b = [b;button];
end
end
set(fig,'pointer',pointer,'units',fig_units);
if nargout > 1
out2 = y;
if nargout > 2
out3 = b;
end
else
out1 = [out1 y];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key = wfbp
%WFBP Replacement for WAITFORBUTTONPRESS that has no side effects.
% Remove figure button functions
fprops = {'windowbuttonupfcn','buttondownfcn', ...
'windowbuttondownfcn','windowbuttonmotionfcn'};
fig = gcf;
fvals = get(fig,fprops);
set(fig,fprops,{'','','',''})
% Remove all other buttondown functions
ax = findobj(fig,'type','axes');
if isempty(ax)
ch = {};
else
ch = get(ax,{'Children'});
end
for i=1:length(ch),
ch{i} = ch{i}(:)';
end
h = [ax(:)',ch{:}];
vals = get(h,{'buttondownfcn'});
mt = repmat({''},size(vals));
set(h,{'buttondownfcn'},mt);
% Now wait for that buttonpress, and check for error conditions
waserr = 0;
eval(['if nargout==0,', ...
' waitforbuttonpress,', ...
'else,', ...
' keydown = waitforbuttonpress;',...
'end' ], 'waserr = 1;');
% Put everything back
if(ishandle(fig))
set(fig,fprops,fvals)
set(h,{'buttondownfcn'},vals)
end
if(waserr == 1)
error('Interrupted');
end
if nargout>0, key = keydown; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github | yugt/ComputerVision-master | graphcut.m | .m | ComputerVision-master/Homework/hw5/graphcut.m | 4,766 | utf_8 | e049b47f50637ed996a9eeece3177528 | function [B] = graphcut(segmentimage,segments,keyindex)
% function [B] = graphcut(segmentimage,segments,keyindex
%
% EECS 442 Computer Vision;
% Jason Corso
%
% Function to take a superpixel set and a keyindex and convert to a
% foreground/background segmentation.
%
% keyindex is the index to the superpixel we wish to use as foreground and
% find its relevant neighbors that would be in the same macro-segment
%
% Similarity is computed based on segments(i).fv (which is a color histogram)
% and spatial proximity.
%
% segmentimage and segments are returned by the superpixel function
% segmentimage is called S and segments is called Copt
%
% OUTPUT: B is a binary image with 1's for those pixels connected to the
% source node and hence in the same segment as the keyindex.
% B has 0's for those nodes connected to the sink.
% compute basic adjacency information of superpixels
%%%% Note that segNeighbors is code you need to implement
adjacency = segNeighbors(segmentimage);
%debug
%figure; imagesc(adjacency); title('adjacency');
% normalization for distance calculation based on the image size
% for points (x1,y1) and (x2,y2), distance is
% exp(-||(x1,y1)-(x2,y2)||^2/dnorm)
dnorm = 2*prod(size(segmentimage)/2)^2;
% thinking of this like a Gaussian and considering the Std-Dev of the Gaussian
% to be roughly half of the total number of pixels in the image. Just a guess
k = length(segments);
capacity = zeros(k+2,k+2); % initialize the zero-valued capacity matrix
source = k+1; % set the index of the source node
sink = k+2; % set the index of the sink node
% this is a single planar graph with an extra source and sink
%
% Capacity of a present edge in the graph (adjacency) is to be defined as the product of
% 1: the histogram similarity between the two color histogram feature vectors.
% use the provided histintersect function below to compute this similarity
% 2: the spatial proximity between the two superpixels connected by the edge.
% use exp(-D(a,b)/dnorm) where D is the euclidean distance between superpixels a and b,
% dnorm is given above.
%
% source gets connected to every node except sink
% capacity is with respect to the keyindex superpixel
% sink gets connected to every node except source;
% capacity is opposite that of the corresponding source-connection (from each superpixel)
% in our case, the max capacity on an edge is 3; so, 3 minus corresponding capacity
%
% superpixels get connected to each other based on computed adjacency matrix
% capacity defined as above. EXCEPT THAT YOU ALSO NEED TO MULTIPLY BY A SCALAR 0.25 for
% adjacent superpixels.
%%% IMPLEMENT CODE TO fill in the capacity values using the description above.
%debug
%figure; imagesc(capacity); title('capacity');
for i=1:k
for j=i+1:k
if adjacency(i,j)>0
capacity(i,j)=histintersect(segments(i).fv,segments(j).fv)*exp(-D(i,j)/dnorm)/4;
end
end
end
capacity=capacity+capacity';
for i=1:k
capacity(source,i)=histintersect(segments(keyindex).fv,segments(i).fv)...
*exp(-D(keyindex,i)/dnorm);
end
for i=1:k
capacity(i,sink)=3-capacity(source,i);
end
function d=D(a,b)
dx=segments(a).x_sub-segments(b).x_sub;
dy=segments(a).y_sub-segments(b).y_sub;
d=sqrt(dx^2+dy^2);
end
% x=load('capacity.mat');
% ans=x.capacity-capacity;
% figure
% imagesc(capacity);
% compute the cut (this code is provided to you)
[~,current_flow] = ff_max_flow(source,sink,capacity,k+2);
% extract the two-class segmentation.
% the cut will separate all nodes into those connected to the
% source and those connected to the sink.
% The current_flow matrix contains the necessary information about
% the max-flow through the graph.
%
% Populate the binary matrix B with 1's for those nodes that are connected
% to the source (and hence are in the same big segment as our keyindex) in the
% residual graph.
%
% You need to compute the set of reachable nodes from the source. Recall, from
% lecture that these are any nodes that can be reached from any path from the
% source in the graph with residual capacity (original capacity - current flow)
% being positive.
%%% IMPLEMENT code to read the cut into B
residual=(capacity-current_flow);
spixels=find(residual(source,:)>0)';
residual=residual(1:k,1:k);
count=length(spixels);
while(true)
for i=1:length(spixels)
spixels=unique([spixels; find(residual(spixels(i),:)>0)']);
end
if count<length(spixels)
count=length(spixels);
else
break
end
end
B=zeros(size(segmentimage));
for i=1:length(spixels)
B=B+(segmentimage==spixels(i));
end
B=(B>0);
end
function c = histintersect(a,b)
c = sum(min(a,b));
end
|
github | yugt/ComputerVision-master | bfs_augmentpath.m | .m | ComputerVision-master/Homework/hw5/bfs_augmentpath.m | 1,195 | utf_8 | 9c16f5bdd848adf28ab0a2ef4a9d6878 | %WHITE =0;
%GRAY=1;
%BLACK=2
function augmentpath=bfs_augmentpath(start,target,current_flow,capacity,n)
WHITE =0;
GRAY=1;
BLACK=2;
color(1:n)=WHITE;
head=1;
tail=1;
q=[];
augmentpath=[];
%ENQUEUE
q=[start q];
color(start)=GRAY;
pred(start) = -1;
pred=zeros(1,n);
while ~isempty (q)
% [u,q]=dequeue(q);
u=q(end);
q(end)=[];
color(u)=BLACK;
% dequeue end here
for v=1:n
if (color(v)==WHITE && capacity(u,v)>current_flow(u,v) )
%enqueue(v,q)
q=[v q];
color(v)=GRAY;
% enqueue end here
pred(v)=u;
end
end
end
if color(target)==BLACK %if target is accessible
temp=target;
while pred(temp)~=start
augmentpath = [pred(temp) augmentpath]; %augment path doesnt containt the start point AND target point
temp=pred(temp);
end
augmentpath=[start augmentpath target];
else
augmentpath=[]; % default resulte is empty
end
|
github | yugt/ComputerVision-master | stitchImages.m | .m | ComputerVision-master/Homework/hw2/problem3/stitchImages.m | 9,979 | utf_8 | 1a0fad27cea6fbdb8bebd0fdbd42cceb | function [Is, alpha] = stitchImages(It,varargin)
%
% Syntax: [Is, alpha] = stitchImages(It);
% [Is, alpha] = stitchImages(...,'dim',dim,...);
% [Is, alpha] = stitchImages(...,'b0',b0,...);
% [Is, alpha] = stitchImages(...,'view',view,...);
% [Is, alpha] = stitchImages(...,'order',order,...);
% [Is, alpha] = stitchImages(...,'mode',mode,...);
%
% Inputs: It is an n x 1 array of structs, where
%
% It(i).image is an Nyi x Nxi x Nc uint8 image
%
% It(i).tform is the 3 x 3 transformation matrix that
% maps It(i).image into the coordinates specified by the
% mode argument below
%
% [OPTIONAL] dim = [h, w] are the desired height and width,
% respectively, in pixels, of the stitched image. By default
% dim is set to preserve the input resolutions
%
% [OPTIONAL] b0 is a Nc x 1 vector of double values in
% [0, 255] specifying the background (i.e., missing data)
% color. The default value is b0 = 255 * ones(Nc,1)
%
% [OPTIONAL] view = {'left','center','right','default'}
% specifies what view to construct the stitched image from.
% The default is view = 'default' (world coordinates)
%
% [OPTIONAL] order = {'natural','reverse'} specifies the
% order in which to overlay the stitched images. In natural
% ordering, the closest image is displayed on top. The
% default is order = 'natural'
%
% [OPTIONAL] mode = {'absolute','relative'} specifies the
% type of transform used. When mode = 'absolute', It(i).tform
% should map to "world" coordinates. When mode = 'relative',
% It(i).tform should map It(i).image into the coordinates of
% It(i-1).image. Here, It(1).tform can be eye(3) or another
% transformation that maps to the desired world coordinates.
% The default value is mode = 'relative'
%
% Outputs: Is is a h x w x Nc uint8 matrix containing the stitched
% image
%
% alpha is a h x w uint8 matrix containing the alpha channel
% (transparency) values for generating a nice transparent png
% of the stitched image
%
% Author: Brian Moore
% [email protected]
%
% Date: September 30, 2015
%
% Parse inputs
[Ns, Nc, dim, b0, view, order, mode] = parseInputs(It,varargin{:});
% Convert to absolute coordinates, if necessary
if strcmpi(mode,'relative')
It = toAbsoluteCoordinates(It);
end
% Apply view
It = applyView(It,view);
% Apply order
It = applyOrder(It,order);
% Compute stitched image limits
[It, xlim, ylim] = computeStitchedLimits(It);
% Get sample points
[x, y, w, h] = getSamplePoints(xlim,ylim,dim);
% Stitch images
Is = nan(h,w,Nc);
for i = Ns:-1:1
Is = overlayImage(Is,It(i),x,y);
end
% Fill background
[Is, alpha] = fillBackground(Is,b0);
% Convert to unit8
Is = uint8(Is);
%--------------------------------------------------------------------------
function [Ns, Nc, dim, b0, view, order, mode] = parseInputs(It,varargin)
% Parse mandatory inputs
Ns = numel(It);
Nc = size(It(1).image,3);
% Default values
dim = [];
b0 = 255 * ones(Nc,1);
view = 'default';
order = 'natural';
mode = 'relative';
% Parse arguments
for i = 1:2:numel(varargin)
switch lower(varargin{i})
case 'dim'
dim = varargin{i + 1};
case 'b0'
b0 = varargin{i + 1};
case 'view'
view = varargin{i + 1};
case 'order'
order = varargin{i + 1};
case 'mode'
mode = varargin{i + 1};
end
end
%--------------------------------------------------------------------------
function It = toAbsoluteCoordinates(It)
% Map all transforms to coordinates of It(1)
for i = 2:numel(It)
It(i).tform = It(i).tform * It(i - 1).tform;
end
%--------------------------------------------------------------------------
function It = applyView(It,view)
% Get transformed limits
Ns = numel(It);
xc = zeros(Ns,1);
for i = 1:Ns
[xlimi, ~] = getOutputLimits(It(i).image,It(i).tform);
xc(i) = mean(xlimi);
end
% Get ordering
switch lower(view)
case 'left'
% Left view
[~,idx] = sort(xc,'ascend');
case 'center'
% Center view
[~,idx] = sort(abs(xc - mean(xc)));
case 'right'
% Right view
[~,idx] = sort(xc,'descend');
case 'default'
% Use input ordering
idx = 1:Ns;
otherwise
% Unsupported view
error('Unsupported view "%s"',view);
end
% Apply ordering
It = It(idx);
if ~strcmpi(view,'default')
H1 = It(1).tform;
for i = 1:Ns
It(i).tform = It(i).tform / H1;
end
end
%--------------------------------------------------------------------------
function It = applyOrder(It,order)
% Apply order
switch lower(order)
case 'natural'
% Natural ordering
% Empty
case 'reverse'
% Reverse ordering
It = flipud(It(:));
otherwise
% Unsupported order
error('Unsupported order "%s"',order);
end
%--------------------------------------------------------------------------
function [It, xlim, ylim] = computeStitchedLimits(It)
% Compute limits
minx = inf;
maxx = -inf;
miny = inf;
maxy = -inf;
for i = 1:numel(It)
[xlimi, ylimi] = getOutputLimits(It(i).image,It(i).tform);
It(i).xlim = xlimi;
It(i).ylim = ylimi;
minx = min(minx,xlimi(1));
maxx = max(maxx,xlimi(2));
miny = min(miny,ylimi(1));
maxy = max(maxy,ylimi(2));
end
xlim = [floor(minx), ceil(maxx)];
ylim = [floor(miny), ceil(maxy)];
%--------------------------------------------------------------------------
function [xlim, ylim] = getOutputLimits(I,H)
% Compute limits of transformed image
[Ny, Nx, ~] = size(I);
X = [1 Nx Nx 1];
Y = [1 1 Ny Ny];
[Xt, Yt] = applyTransform(X,Y,H);
xlim = [min(Xt), max(Xt)];
ylim = [min(Yt), max(Yt)];
%--------------------------------------------------------------------------
function [Xt, Yt] = applyTransform(X,Y,H)
% Apply transformation
sz = size(X);
n = numel(X);
tmp = [X(:), Y(:), ones(n,1)] * H;
Xt = reshape(tmp(:,1) ./ tmp(:,3),sz);
Yt = reshape(tmp(:,2) ./ tmp(:,3),sz);
%--------------------------------------------------------------------------
function [X, Y] = applyInverseTransform(Xt,Yt,H)
% Apply inverse transformation
sz = size(Xt);
n = numel(Xt);
tmp = [Xt(:), Yt(:), ones(n,1)] / H;
X = reshape(tmp(:,1) ./ tmp(:,3),sz);
Y = reshape(tmp(:,2) ./ tmp(:,3),sz);
%--------------------------------------------------------------------------
function [x, y, w, h] = getSamplePoints(xlim,ylim,dim)
% Get sample dimensions
if isempty(dim)
w = diff(xlim) + 1;
h = diff(ylim) + 1;
else
w = dim(2);
h = dim(1);
end
% Limit resolution to a reasonable value, if necessary
MAX_PIXELS = 2000 * 2000;
[w, h] = limitRes(w,h,MAX_PIXELS);
% Compute sample points
x = linspace(xlim(1),xlim(2),w);
y = linspace(ylim(1),ylim(2),h);
%--------------------------------------------------------------------------
function [w, h] = limitRes(w,h,lim)
if w * h <= lim
% No rescaling needed
return;
end
% Rescale to meet limit
kappa = w / h;
w = round(sqrt(lim * kappa));
h = round(sqrt(lim / kappa));
warning('Output resolution too large, rescaling to %i x %i',h,w); %#ok
%--------------------------------------------------------------------------
function Is = overlayImage(Is,It,x,y)
% Overlay image
Nc = size(Is,3);
If = fillImage(It,x,y);
mask = ~any(isnan(If),3);
for j = 1:Nc
Isj = Is(:,:,j);
Ifj = If(:,:,j);
Isj(mask) = Ifj(mask);
Is(:,:,j) = Isj;
end
%--------------------------------------------------------------------------
function If = fillImage(It,x,y)
% Parse inputs
Nc = size(It.image,3);
w = numel(x);
h = numel(y);
% Get active coordinates
[~, xIdx1] = find(x <= It.xlim(1),1,'last');
[~, xIdx2] = find(x >= It.xlim(2),1,'first');
[~, yIdx1] = find(y <= It.ylim(1),1,'last');
[~, yIdx2] = find(y >= It.ylim(2),1,'first');
wa = xIdx2 + 1 - xIdx1;
ha = yIdx2 + 1 - yIdx1;
% Compute inverse transformed coordinates
[Xta, Yta] = meshgrid(x(xIdx1:xIdx2),y(yIdx1:yIdx2));
[Xa, Ya] = applyInverseTransform(Xta,Yta,It.tform);
% Compute active image
Ia = zeros(ha,wa,Nc);
for j = 1:Nc
Ia(:,:,j) = interp2(double(It.image(:,:,j)),Xa,Ya);
end
% Embed into full image
If = nan(h,w,Nc);
If(yIdx1:yIdx2,xIdx1:xIdx2,:) = Ia;
%--------------------------------------------------------------------------
function [Is, alpha] = fillBackground(Is,b0)
% Fill background
Nc = size(Is,3);
mask = any(isnan(Is),3);
for j = 1:Nc
Isj = Is(:,:,j);
Isj(mask) = b0(j);
Is(:,:,j) = Isj;
end
% Return alpha
alpha = zeros(size(mask),'uint8');
alpha(~mask) = 255;
|
github | yugt/ComputerVision-master | nonmaxsuppts.m | .m | ComputerVision-master/Homework/hw2/problem3/nonmaxsuppts.m | 5,085 | utf_8 | b2a36d9b59c2f7914f7a5c33e132e7a2 | % NONMAXSUPPTS - Non-maximal suppression for features/corners
%
% Non maxima suppression and thresholding for points generated by a feature
% or corner detector.
%
% Usage: [r,c] = nonmaxsuppts(cim, radius, thresh, im)
% /
% optional
%
% [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
%
% Arguments:
% cim - corner strength image.
% radius - radius of region considered in non-maximal
% suppression. Typical values to use might
% be 1-3 pixels.
% thresh - threshold.
% im - optional image data. If this is supplied the
% thresholded corners are overlayed on this
% image. This can be useful for parameter tuning.
% Returns:
% r - row coordinates of corner points (integer valued).
% c - column coordinates of corner points.
% rsubp - If four return values are requested sub-pixel
% csubp - localization of feature points is attempted and
% returned as an additional set of floating point
% coords. Note that you may still want to use the integer
% valued coords to specify centres of correlation windows
% for feature matching.
%
% Copyright (c) 2003-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% September 2003 Original version
% August 2005 Subpixel localization and Octave compatibility
% January 2010 Fix for completely horizontal and vertical lines (by Thomas Stehle,
% RWTH Aachen University)
% January 2011 Warning given if no maxima found
function [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
subPixel = nargout == 4; % We want sub-pixel locations
[rows,cols] = size(cim);
% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.
sze = 2*radius+1; % Size of dilation mask.
mx = ordfilt2(cim,sze^2,ones(sze)); % Grey-scale dilate.
% Make mask to exclude points within radius of the image boundary.
bordermask = zeros(size(cim));
bordermask(radius+1:end-radius, radius+1:end-radius) = 1;
% Find maxima, threshold, and apply bordermask
cimmx = (cim==mx) & (cim>thresh) & bordermask;
[r,c] = find(cimmx); % Find row,col coords.
if subPixel % Compute local maxima to sub pixel accuracy
if ~isempty(r) % ...if we have some ponts to work with
ind = sub2ind(size(cim),r,c); % 1D indices of feature points
w = 1; % Width that we look out on each side of the feature
% point to fit a local parabola
% Indices of points above, below, left and right of feature point
indrminus1 = max(ind-w,1);
indrplus1 = min(ind+w,rows*cols);
indcminus1 = max(ind-w*rows,1);
indcplus1 = min(ind+w*rows,rows*cols);
% Solve for quadratic down rows
rowshift = zeros(size(ind));
cy = cim(ind);
ay = (cim(indrminus1) + cim(indrplus1))/2 - cy;
by = ay + cy - cim(indrminus1);
rowshift(ay ~= 0) = -w*by(ay ~= 0)./(2*ay(ay ~= 0)); % Maxima of quadradic
rowshift(ay == 0) = 0;
% Solve for quadratic across columns
colshift = zeros(size(ind));
cx = cim(ind);
ax = (cim(indcminus1) + cim(indcplus1))/2 - cx;
bx = ax + cx - cim(indcminus1);
colshift(ax ~= 0) = -w*bx(ax ~= 0)./(2*ax(ax ~= 0)); % Maxima of quadradic
colshift(ax == 0) = 0;
rsubp = r+rowshift; % Add subpixel corrections to original row
csubp = c+colshift; % and column coords.
else
rsubp = []; csubp = [];
end
end
if nargin==4 & ~isempty(r) % Overlay corners on supplied image.
figure(1), imshow(im,[]), hold on
if subPixel
plot(csubp,rsubp,'r+'), title('corners detected');
else
plot(c,r,'r+'), title('corners detected');
end
hold off
end
if isempty(r)
% fprintf('No maxima above threshold found\n');
end
|
github | yugt/ComputerVision-master | match.m | .m | ComputerVision-master/Homework/hw2/problem3/match.m | 1,432 | utf_8 | a03ee15e52b0715f903e75b7fde00f78 | function M = match(F1,F2,k)
% function M = match(F1,F2,k)
%
% EECS 442;
% Jason Corso
%
% Wrapper for function to matching extracted feature vectors from a pair
% of images
%
% F1 is the feature matrix (rows -dimensions and cols number of points)
% from image 1
% F2 feature matrix from image 2
% k is the number of matches to take (optional)
%
% M is a k x 2 matrix where k is the number of matches and the first col
% is the index of the match in F1 and the second col in F2
if nargin==2
k=12;
end
n1 = size(F1,2);
n2 = size(F2,2);
n = max(n1,n2);
C = zeros(n,n);
for i=1:n1
C(i,1:n2) = distance(F1(:,i),F2);
end
A = hungarian(C);
D = ones(n1,1);
I = ones(n1,1);
for i=1:n1
I(i) = A(i);
D(i) = C(i,A(i));
end
%for i=1:n1
% [I(i),D(i)] = matchsingle(F1(:,i),F2);
%end
% now, rank and take just the top $k=5$
[Ds,Di] = sort(D,'ascend');
M=zeros(k,2);
for i=1:k
M(i,1) = Di(i);
M(i,2) = I(Di(i));
end
function D = distance(f,F)
n = size(F,2);
ff = repmat(f,[1,n]);
D = ff-F;
D = D.*D;
D = sum(D,1);
D = sqrt(D);
function [m,d] = matchsingle(f,F)
% function [m,d] = matchsingle(f,F)
%
% Wrapper for function to matching an feature vector to a feature matrix
%
% f is the vector
% F is the matrix
%
% m is the matched index
% d is the distance for the match
n = size(F,2);
ff = repmat(f,[1,n]);
D = ff-F;
D = D.*D;
D = sum(D,1);
D = sqrt(D);
[d,m] = min(D);
|
github | yugt/ComputerVision-master | colorcircle.m | .m | ComputerVision-master/Homework/hw3/problem1/colorcircle.m | 661 | utf_8 | c257dd26bb66c52d14de02d1bd93a1f3 | % Color CIRCLE - Draws a circle.
%
% Usage: colorcircle(c, r, s, n)
%
% Arguments: c - A 2-vector [x y] specifying the centre.
% r - The radius.
% n - Optional number of sides in the polygonal approximation.
% (defualt is 16 sides)
% s - color of the line segments to draw [r g b] in [0 1]
function colorcircle(c, r, s, nsides)
if nargin == 2
nsides = 16;
s = [0 0 1];
elseif nargin == 3
nsides = 16;
end
nsides = round(nsides); % make sure it is an integer
a = [0:pi/nsides:2*pi];
h = line(r*cos(a)+c(1), r*sin(a)+c(2));
set(h,'Color',s);
|
github | yugt/ComputerVision-master | colorcircle.m | .m | ComputerVision-master/Homework/hw3/problem2/colorcircle.m | 677 | utf_8 | fc8960bac7b8d86d43fcb447ebcf1370 | % Color CIRCLE - Draws a circle.
%
% Usage: colorcircle(c, r, s, n)
%
% Arguments: c - A 2-vector [x y] specifying the centre.
% r - The radius.
% n - Optional number of sides in the polygonal approximation.
% (defualt is 16 sides)
% s - color of the line segments to draw [r g b] in [0 1]
function colorcircle(c, r, s, nsides)
if nargin == 2
nsides = 16;
s = [0 0 1];
elseif nargin == 3
nsides = 16;
end
nsides = round(nsides); % make sure it is an integer
a = [0:pi/nsides:2*pi];
h = line(r*cos(a)+c(1), r*sin(a)+c(2), 'LineWidth', 2);
set(h,'Color',s);
|
github | yugt/ComputerVision-master | match.m | .m | ComputerVision-master/Homework/hw3/problem2/match.m | 1,432 | utf_8 | a03ee15e52b0715f903e75b7fde00f78 | function M = match(F1,F2,k)
% function M = match(F1,F2,k)
%
% EECS 442;
% Jason Corso
%
% Wrapper for function to matching extracted feature vectors from a pair
% of images
%
% F1 is the feature matrix (rows -dimensions and cols number of points)
% from image 1
% F2 feature matrix from image 2
% k is the number of matches to take (optional)
%
% M is a k x 2 matrix where k is the number of matches and the first col
% is the index of the match in F1 and the second col in F2
if nargin==2
k=12;
end
n1 = size(F1,2);
n2 = size(F2,2);
n = max(n1,n2);
C = zeros(n,n);
for i=1:n1
C(i,1:n2) = distance(F1(:,i),F2);
end
A = hungarian(C);
D = ones(n1,1);
I = ones(n1,1);
for i=1:n1
I(i) = A(i);
D(i) = C(i,A(i));
end
%for i=1:n1
% [I(i),D(i)] = matchsingle(F1(:,i),F2);
%end
% now, rank and take just the top $k=5$
[Ds,Di] = sort(D,'ascend');
M=zeros(k,2);
for i=1:k
M(i,1) = Di(i);
M(i,2) = I(Di(i));
end
function D = distance(f,F)
n = size(F,2);
ff = repmat(f,[1,n]);
D = ff-F;
D = D.*D;
D = sum(D,1);
D = sqrt(D);
function [m,d] = matchsingle(f,F)
% function [m,d] = matchsingle(f,F)
%
% Wrapper for function to matching an feature vector to a feature matrix
%
% f is the vector
% F is the matrix
%
% m is the matched index
% d is the distance for the match
n = size(F,2);
ff = repmat(f,[1,n]);
D = ff-F;
D = D.*D;
D = sum(D,1);
D = sqrt(D);
[d,m] = min(D);
|
github | yugt/ComputerVision-master | hog.m | .m | ComputerVision-master/Homework/hw3/problem2/hog.m | 6,966 | utf_8 | 094b0c972d07da4c8fa2b4fbe25c1170 | function v = hog(im,x,y,Wfull)
% function v = hog(im,x,y,Wfull)
%
% EECS Foundation of Computer Vision;
% Chenliang Xu and Jason Corso
%
% Compute the histogram of oriented gradidents on image (im)
% for a given location (x,y) and scale (Wfull)
%
% v is the output column vector of the hog.
%
% Use Lowe IJCV 2004 Sections 5 and 6 to (1) adapt to local rotation
% and (2) compute the histogram. Use the parameters in the paper
% Within the window a 4 by 4 array of histograms of oriented gradients
% with 8 discretized orientations per bin. Do it separately per color channel
% and then concatenate the resulting vectors.
% Each v should be 3*128 dimensions = 3*4*4*8.
%
v = zeros(3,1152);
%%%%%%%% fill in below
%% Orientation Assignment
margin_long = Wfull/2;
margin_short = Wfull/2-1;
sm = im(y-margin_long-1:y+margin_short+1, ...
x-margin_long-1:x+margin_short+1, :);
gm = rgb2gray(sm);
dy = conv2(gm,[-1 0 1]','same');
dx = conv2(gm,[-1 0 1],'same');
dy = dy(2:end-1, 2:end-1);
dx = dx(2:end-1, 2:end-1);
mag = sqrt(dx.^2+dy.^2);
ang = atan2(dy, dx);
angd = 18-floor(ang/10); % map 180~-180 to 36 bins
cnts = zeros(36,1);
for i=1:36
cnts(i) = sum(mag(angd==i));
end
[~,idx] = max(cnts);
theta = (18-idx)*10+5;
%% HOG Descriptor
for i=1:3
cm = im(y-Wfull:y+Wfull, x-Wfull:x+Wfull, i);
dy = conv2(cm,[-1 0 1]','same');
dx = conv2(cm,[-1 0 1],'same');
% rotate
dy = imrotate(dy, -theta, 'crop', 'bilinear');
dx = imrotate(dx, -theta, 'crop', 'bilinear');
dy = dy(1+margin_long:end-1-margin_long, ...
1+margin_long:end-1-margin_long);
dx = dx(1+margin_long:end-1-margin_long, ...
1+margin_long:end-1-margin_long);
% Approximation
v(i,:) = hog_feature_vector(dx, dy);
end
v = v(:);
function [feature] = hog_feature_vector(Ix, Iy)
% The given code finds the HOG feature vector for any given image. HOG
% feature vector/descriptor can then be used for detection of any
% particular object. The Matlab code provides the exact implementation of
% the formation of HOG feature vector as detailed in the paper "Pedestrian
% detection using HOG" by Dalal and Triggs
% INPUT => im (input image)
% OUTPUT => HOG feature vector for that particular image
% Example: Running the code
% >>> im = imread('cameraman.tif');
% >>> hog = hog_feature_vector (im);
% Modified by Chenliang Xu.
% Change Bi-Linear to Tri-Linear Interpolation for Binning Process.
% Change Iterations and Angle Computation.
rows=size(Ix,1);
cols=size(Ix,2);
angle=atan2(Iy, Ix);
magnitude=sqrt(Ix.^2 + Iy.^2);
% figure,imshow(uint8(angle));
% figure,imshow(uint8(magnitude));
% Remove redundant pixels in an image.
angle(isnan(angle))=0;
magnitude(isnan(magnitude))=0;
feature=[]; %initialized the feature vector
% Iterations for Blocks
for i = 0: rows/8 - 2
for j= 0: cols/8 -2
%disp([i,j])
mag_patch = magnitude(8*i+1 : 8*i+16 , 8*j+1 : 8*j+16);
%mag_patch = imfilter(mag_patch,gauss);
ang_patch = angle(8*i+1 : 8*i+16 , 8*j+1 : 8*j+16);
block_feature=[];
%Iterations for cells in a block
for x= 0:3
for y= 0:3
angleA =ang_patch(4*x+1:4*x+4, 4*y+1:4*y+4);
magA =mag_patch(4*x+1:4*x+4, 4*y+1:4*y+4);
histr =zeros(1,8);
%Iterations for pixels in one cell
for p=1:4
for q=1:4
%
alpha= angleA(p,q);
% Binning Process (Tri-Linear Interpolation)
if alpha>135 && alpha<=180
histr(8)=histr(8)+ magA(p,q)*(1-(157.5+45-alpha)/360);
histr(1)=histr(1)+ magA(p,q)*(1-abs(157.5-alpha)/360);
histr(2)=histr(2)+ magA(p,q)*(1-abs(112.5-alpha)/360);
elseif alpha>90 && alpha<=135
histr(1)=histr(1)+ magA(p,q)*(1-abs(157.5-alpha)/360);
histr(2)=histr(2)+ magA(p,q)*(1-abs(112.5-alpha)/360);
histr(3)=histr(3)+ magA(p,q)*(1-abs(67.5-alpha)/360);
elseif alpha>45 && alpha<=90
histr(2)=histr(2)+ magA(p,q)*(1-abs(112.5-alpha)/360);
histr(3)=histr(3)+ magA(p,q)*(1-abs(67.5-alpha)/360);
histr(4)=histr(4)+ magA(p,q)*(1-abs(22.5-alpha)/360);
elseif alpha>0 && alpha<=45
histr(3)=histr(3)+ magA(p,q)*(1-abs(67.5-alpha)/360);
histr(4)=histr(4)+ magA(p,q)*(1-abs(22.5-alpha)/360);
histr(5)=histr(5)+ magA(p,q)*(1-abs(-22.5-alpha)/360);
elseif alpha>-45 && alpha<=0
histr(4)=histr(4)+ magA(p,q)*(1-abs(22.5-alpha)/360);
histr(5)=histr(5)+ magA(p,q)*(1-abs(-22.5-alpha)/360);
histr(6)=histr(6)+ magA(p,q)*(1-abs(-67.5-alpha)/360);
elseif alpha>-90 && alpha<=-45
histr(5)=histr(5)+ magA(p,q)*(1-abs(-22.5-alpha)/360);
histr(6)=histr(6)+ magA(p,q)*(1-abs(-67.5-alpha)/360);
histr(7)=histr(7)+ magA(p,q)*(1-abs(-112.5-alpha)/360);
elseif alpha>-135 && alpha<=-90
histr(6)=histr(6)+ magA(p,q)*(1-abs(-67.5-alpha)/360);
histr(7)=histr(7)+ magA(p,q)*(1-abs(-112.5-alpha)/360);
histr(8)=histr(8)+ magA(p,q)*(1-abs(-157.5-alpha)/360);
elseif alpha>=-180 && alpha<=-135
histr(7)=histr(7)+ magA(p,q)*(1-abs(-112.5-alpha)/360);
histr(8)=histr(8)+ magA(p,q)*(1-abs(-157.5-alpha)/360);
histr(1)=histr(1)+ magA(p,q)*(1-(157.5+45+alpha)/360);
end
end
end
block_feature=[block_feature histr]; % Concatenation of Four histograms to form one block feature
end
end
% Normalize the values in the block using L1-Norm
block_feature=block_feature/sqrt(norm(block_feature)^2+.01);
feature=[feature block_feature]; %Features concatenation
end
end
feature(isnan(feature))=0; %Removing Infinitiy values
% Normalization of the feature vector using L2-Norm
feature=feature/sqrt(norm(feature)^2+.001);
for z=1:length(feature)
if feature(z)>0.2
feature(z)=0.2;
end
end
feature=feature/sqrt(norm(feature)^2+.001);
% toc;
%%%%%%%% fill in above
|
github | yugt/ComputerVision-master | potts.m | .m | ComputerVision-master/Homework/hw1/problem4/potts.m | 306 | utf_8 | 41094b0510a36731bafe61ad02847dde | % potts.m
% to be completed by students
function E = potts(I,beta)
if nargin==1
beta=1;
end
%%% FILL IN HERE
L=int32(I); % convert to signed long to avoid overflow
X=L(:,:,1)+L(:,:,2)*256+L(:,:,3)*65536;
[m,n]=size(X);
E=beta*(nnz(X(1:m-1,:)-X(2:m,:))+nnz(X(:,1:n-1)-X(:,2:n)));
%%% FILL IN HERE |
github | garrickbrazil/SDS-RCNN-master | roidb_generate.m | .m | SDS-RCNN-master/functions/utils/roidb_generate.m | 4,496 | utf_8 | 67b84b2e5a6f48060c1022d41f9d78b8 | function roidb = roidb_generate(imdb, flip, cache_dir, dataset, min_gt_height)
% roidb = roidb_generate(imdb, flip)
% Package the roi annotations into the imdb.
%
% Inspired by Ross Girshick's imdb and roidb code.
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------
mkdir_if_missing([cache_dir]);
roidb.name = imdb.name;
anno_path = ['./datasets/' dataset '/' roidb.name '/annotations'];
addpath(genpath('./external/code3.2.1'));
pLoad={'lbls',{'person'},'ilbls',{'people', 'ignore'},'squarify',{3,.41}};
pLoad = [pLoad 'hRng',[min_gt_height inf], 'vRng',[1 1] ];
if flip
cache_file = [cache_dir '/roidb_' dataset '_' imdb.name '_flip'];
else
cache_file = [cache_dir '/roidb_' dataset '_' imdb.name];
end
cache_file = [cache_file, '.mat'];
try
load(cache_file);
fprintf('Preloaded roidb %s.. ', roidb.name);
catch
fprintf('Computing roidb %s.. ', roidb.name);
roidb.name = imdb.name;
regions = [];
if isempty(regions)
regions.boxes = cell(length(imdb.image_ids), 1);
end
height = imdb.sizes(1,1);
width = imdb.sizes(1,2);
files=bbGt('getFiles',{anno_path});
num_gts = 0;
num_gt_no_ignores = 0;
for i = 1:length(files)
[~,gts]=bbGt('bbLoad',files{i},pLoad);
ignores = gts(:,end);
num_gts = num_gts + length(ignores);
num_gt_no_ignores = num_gt_no_ignores + (length(ignores)-sum(ignores));
if flip
% for ori
x1 = gts(:,1);
y1 = gts(:,2);
x2 = gts(:,1) + gts(:,3);
y2 = gts(:,2) + gts(:,4);
gt_boxes = [x1 y1 x2 y2];
roidb.rois(i*2-1) = attach_proposals(regions.boxes{i}, gt_boxes, ignores);
% for flip
x1_flip = width - gts(:,1) - gts(:,3);
y1_flip = y1;
x2_flip = width - gts(:,1);
y2_flip = y2;
gt_boxes_flip = [x1_flip y1_flip x2_flip y2_flip];
roidb.rois(i*2) = attach_proposals(regions.boxes{i}, gt_boxes_flip, ignores);
if 0
% debugging visualizations
im = imread(imdb.image_at(i*2-1));
t_boxes = roidb.rois(i*2-1).boxes;
for k = 1:size(t_boxes, 1)
showboxes2(im, t_boxes(k,1:4));
title(sprintf('%s, ignore: %d\n', imdb.image_ids{i*2-1}, roidb.rois(i*2-1).ignores(k)));
pause;
end
im = imread(imdb.image_at(i*2));
t_boxes = roidb.rois(i*2).boxes;
for k = 1:size(t_boxes, 1)
showboxes2(im, t_boxes(k,1:4));
title(sprintf('%s, ignore: %d\n', imdb.image_ids{i*2}, roidb.rois(i*2).ignores(k)));
pause;
end
end
else
% for ori
x1 = gts(:,1);
y1 = gts(:,2);
x2 = gts(:,1) + gts(:,3);
y2 = gts(:,2) + gts(:,4);
gt_boxes = [x1 y1 x2 y2];
roidb.rois(i) = attach_proposals(regions.boxes{i}, gt_boxes, ignores);
end
end
save(cache_file, 'roidb', '-v7.3');
%fprintf('num_gt / num_ignore %d / %d \n', num_gt_no_ignores, num_gts);
end
fprintf('done\n');
end
% ------------------------------------------------------------------------
function rec = attach_proposals(boxes, gt_boxes, ignores)
% ------------------------------------------------------------------------
% gt: [2108x1 double]
% overlap: [2108x20 single]
% dataset: 'voc_2007_trainval'
% boxes: [2108x4 single]
% feat: [2108x9216 single]
% class: [2108x1 uint8]
all_boxes = cat(1, gt_boxes, boxes);
gt_classes = ones(size(gt_boxes, 1), 1); % set pedestrian label as 1
num_gt_boxes = size(gt_boxes, 1);
num_boxes = size(boxes, 1);
rec.gt = cat(1, true(num_gt_boxes, 1), false(num_boxes, 1));
rec.overlap = zeros(num_gt_boxes+num_boxes, 1, 'single');
for i = 1:num_gt_boxes
rec.overlap(:, gt_classes(i)) = ...
max(rec.overlap(:, gt_classes(i)), boxoverlap(all_boxes, gt_boxes(i, :)));
end
rec.boxes = single(all_boxes);
rec.feat = [];
rec.class = uint8(cat(1, gt_classes, zeros(num_boxes, 1)));
rec.ignores = ignores;
end |
github | garrickbrazil/SDS-RCNN-master | evaluate_result_dir.m | .m | SDS-RCNN-master/functions/utils/evaluate_result_dir.m | 22,081 | utf_8 | ca54816fbdcadc7110cf390fb95d574b | function [scores, thres, recall, dts, gts, res, occls, ols] = dbEval(aDirs, db, minh)
% Evaluate and plot all pedestrian detection results.
%
% Set parameters by altering this function directly.
%
% USAGE
% dbEval
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
% dbEval
%
% See also bbGt, dbInfo
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% List of experiment settings: { name, hr, vr, ar, overlap, filter }
% name - experiment name
% hr - height range to test
% vr - visibility range to test
% ar - aspect ratio range to test
% overlap - overlap threshold for evaluation
% filter - expanded filtering (see 3.3 in PAMI11)
scores = 0;
if nargin < 3
minh = 50;
end
exps = {
'Reasonable', [minh inf], [.65 inf], 0, .5, 1.25
'All', [20 inf], [.2 inf], 0, .5, 1.25
'Scale=large', [100 inf], [inf inf], 0, .5, 1.25
'Scale=near', [80 inf], [inf inf], 0, .5, 1.25
'Scale=medium', [30 80], [inf inf], 0, .5, 1.25
'Scale=far', [20 30], [inf inf], 0, .5, 1.25
'Occ=none', [50 inf], [inf inf], 0, .5, 1.25
'Occ=partial', [50 inf], [.65 1], 0, .5, 1.25
'Occ=heavy', [50 inf], [.2 .65], 0, .5, 1.25
'Ar=all', [50 inf], [inf inf], 0, .5, 1.25
'Ar=typical', [50 inf], [inf inf], .1, .5, 1.25
'Ar=atypical', [50 inf], [inf inf], -.1, .5, 1.25
'Overlap=25', [50 inf], [.65 inf], 0, .25, 1.25
'Overlap=50', [50 inf], [.65 inf], 0, .50, 1.25
'Overlap=75', [50 inf], [.65 inf], 0, .75, 1.25
'Expand=100', [50 inf], [.65 inf], 0, .5, 1.00
'Expand=125', [50 inf], [.65 inf], 0, .5, 1.25
'Expand=150', [50 inf], [.65 inf], 0, .5, 1.50 };
exps=cell2struct(exps',{'name','hr','vr','ar','overlap','filter'});
exps = exps(1);
% List of algorithms: { name, resize, color, style }
% name - algorithm name (defines data location)
% resize - if true rescale height of each box by 100/128
% color - algorithm plot color
% style - algorithm plot linestyle
n=1000; clrs=zeros(n,3);
for i=1:n, clrs(i,:)=max(.3,mod([78 121 42]*(i+1),255)/255); end
algs = {
'VJ', 0, clrs(1,:), '--'
'HOG', 1, clrs(2,:), '--'
'FtrMine', 1, clrs(3,:), '-'
'Shapelet', 0, clrs(4,:), '--'
'PoseInv', 1, clrs(5,:), '-'
'MultiFtr', 0, clrs(6,:), '--'
'MultiFtr+CSS', 0, clrs(7,:), '-'
'MultiFtr+Motion', 0, clrs(8,:), '--'
'HikSvm', 1, clrs(9,:), '-'
'Pls', 0, clrs(10,:), '--'
'HogLbp', 0, clrs(11,:), '-'
'LatSvm-V1', 0, clrs(12,:), '--'
'LatSvm-V2', 0, clrs(13,:), '-'
'ChnFtrs', 0, clrs(14,:), '--'
'FPDW', 0, clrs(15,:), '-'
'FeatSynth', 0, clrs(16,:), '--'
'MultiResC', 0, clrs(17,:), '-'
'CrossTalk', 0, clrs(18,:), '--'
'VeryFast', 0, clrs(19,:), '-'
'ConvNet', 0, clrs(20,:), '--'
'SketchTokens', 0, clrs(21,:), '-'
'Roerei', 0, clrs(22,:), '--'
'AFS', 1, clrs(23,:), '-'
'AFS+Geo', 1, clrs(23,:), '--'
'MLS', 1, clrs(24,:), '-'
'MT-DPM', 0, clrs(25,:), '-'
'MT-DPM+Context', 0, clrs(25,:), '--'
'DBN-Isol', 0, clrs(26,:), '-'
'DBN-Mut', 0, clrs(26,:), '--'
'MF+Motion+2Ped', 0, clrs(27,:), '-'
'MultiResC+2Ped', 0, clrs(27,:), '--'
'MOCO', 0, clrs(28,:), '-'
'ACF', 0, clrs(29,:), '-'
'ACF-Caltech', 0, clrs(29,:), '--'
'ACF+SDt', 0, clrs(30,:), '-'
'FisherBoost', 0, clrs(31,:), '--'
'pAUCBoost', 0, clrs(32,:), '-'
'Franken', 0, clrs(33,:), '--'
'JointDeep', 0, clrs(34,:), '-'
'MultiSDP', 0, clrs(35,:), '--'
'SDN', 0, clrs(36,:), '-'
'RandForest', 0, clrs(37,:), '--'
'WordChannels', 0, clrs(38,:), '-'
'InformedHaar', 0, clrs(39,:), '--'
'SpatialPooling', 0, clrs(40,:), '-'
'SpatialPooling+', 0, clrs(42,:), '--'
'Seg+RPN', 0, clrs(43,:), '-'
'ACF-Caltech+', 0, clrs(44,:), '--'
'Katamari', 0, clrs(45,:), '-'
'NAMC', 0, clrs(46,:), '--'
'FastCF', 0, clrs(47,:), '-'
'TA-CNN', 0, clrs(48,:), '--'
'SCCPriors', 0, clrs(49,:), '-'
'DeepParts', 0, clrs(50,:), '--'
'DeepCascade', 0, clrs(51,:), '-'
'DeepCascade+', 0, clrs(51,:), '--'
'LFOV', 0, clrs(52,:), '-'
'Checkerboards', 0, clrs(53,:), '--'
'Checkerboards+', 0, clrs(53,:), '-'
'CCF', 0, clrs(54,:), '--'
'CCF+CF', 0, clrs(54,:), '-'
'CompACT-Deep', 0, clrs(55,:), '--'
'SCF+AlexNet', 0, clrs(56,:), '-'
'RPN-Only', 0, clrs(35,:), '-'
%'Fast-VGG16-ACF', 0, clrs(59,:), '-'
%'Faster-VGG16-seg', 0, clrs(61,:), '-'
'SA-FastRCNN', 0, clrs(57,:), '--'
%'Faster-VGG16', 0, clrs(31,:), '-'
'cityscapes-multitask-comb', 0, clrs(31,:), '-'
};
algs=cell2struct(algs',{'name','resize','color','style'});
% List of database names
dataNames = {'cityscapes', 'UsaTest','UsaTrain','InriaTest',...
'TudBrussels','ETH','Daimler','Japan'};
% select databases, experiments and algorithms for evaluation
dataNames = dataNames(2); % select one or more databases for evaluation
%exps = exps(2); % select one or more experiment for evaluation
algs = algs(:); % select one or more algorithms for evaluation
if nargin > 1
dataNames = {db};
end
% remaining parameters and constants
aspectRatio = .41; % default aspect ratio for all bbs
bnds = [5 5 635 475]; % discard bbs outside this pixel range
plotRoc = 1; % if true plot ROC else PR curves
plotAlg = 0; % if true one plot per alg else one plot per exp
plotNum = 15; % only show best plotNum curves (and VJ and HOG)
samples = 10.^(-2:.25:0); % samples for computing area under the curve
lims = [2e-4 50 .035 1]; % axis limits for ROC plots
bbsShow = 0; % if true displays sample bbs for each alg/exp
bbsType = 'fp'; % type of bbs to display (fp/tp/fn/dt)
algs0=aDirs; bnds0=bnds;
for d=1:length(dataNames), dataName=dataNames{d};
% select algorithms with results for current dataset
[~,set]=dbInfo(dataName); set=['/set' int2str2(set(1),2)];
names={algs0}; n=length(names); keep=true(1,n);
algs=algs0(keep);
% handle special database specific cases
if(any(strcmp(dataName,{'InriaTest','TudBrussels','ETH', 'kitti_fold1', 'kitti_fold2', 'kitti_fold3'})))
bnds=[-inf -inf inf inf]; else bnds=bnds0; end
if(strcmp(dataName,'InriaTest'))
i=find(strcmp({algs.name},'FeatSynth'));
if(~isempty(i)), algs(i).resize=1; end;
end
% name for all plots (and also temp directory for results)
plotName=[fileparts(mfilename('fullpath')) '/results/' dataName];
%if(~exist(plotName,'dir')), mkdir(plotName); end
% load detections and ground truth and evaluate
dts = loadDt( algs, plotName, aspectRatio, aDirs );
[gts, occls, ols] = loadGt( exps, plotName, aspectRatio, bnds );
res = evalAlgs( plotName, algs, exps, gts, dts );
%disp([dbInfo '/res/' names{i} set]);
tp=0; missed=0;
for resi=1:length(res.gtr)
if size(res.gtr{resi}, 1) > 0
if (res.gtr{resi}(5) == 1)
tp=tp+1;
elseif (res.gtr{resi}(5) == 0)
missed=missed+1;
end
end
end
recall = tp/(tp+missed);
% plot curves and bbs
[scores, thres] = plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, reshape([clrs(1,:)]',3,[])', {'-'} );
%plotBbs( res, plotName, bbsShow, bbsType );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = evalAlgs( plotName, algs, exps, gts, dts )
% Evaluate every algorithm on each experiment
%
% OUTPUTS
% res - nGt x nDt cell of all evaluations, each with fields
% .stra - string identifying algorithm
% .stre - string identifying experiment
% .gtr - [n x 1] gt result bbs for each frame [x y w h match]
% .dtr - [n x 1] dt result bbs for each frame [x y w h score match]
%fprintf('Evaluating: %s\n',plotName);
nGt=length(gts); nDt=length(dts);
res=repmat(struct('stra',[],'stre',[],'gtr',[],'dtr',[]),nGt,nDt);
for g=1:nGt
for d=1:nDt
gt=gts{g}; dt=dts{d}; n=length(gt); %assert(length(dt)==n);
stra=algs{d}; stre=exps(g).name;
fName = [plotName '/ev-' [stre '-' stra] '.mat'];
if(exist(fName,'file')), R=load(fName); res(g,d)=R.R; continue; end
%fprintf('\tExp %i/%i, Alg %i/%i: %s/%s\n',g,nGt,d,nDt,stre,stra);
hr = exps(g).hr.*[1/exps(g).filter exps(g).filter];
for f=1:n
bb=dt{f};
dt{f}=bb(bb(:,4)>=hr(1) & bb(:,4)<hr(2),:); end
[gtr,dtr] = bbGt('evalRes',gt,dt,exps(g).overlap);
R=struct('stra',stra,'stre',stre,'gtr',{gtr},'dtr',{dtr});
res(g,d)=R; %save(fName,'R');
end
end
end
function [scores thres] = plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, colors, styles )
% Plot all ROC or PR curves.
%
% INPUTS
% res - output of evalAlgs
% plotRoc - if true plot ROC else PR curves
% plotAlg - if true one plot per alg else one plot per exp
% plotNum - only show best plotNum curves (and VJ and HOG)
% plotName - filename for saving plots
% samples - samples for computing area under the curve
% lims - axis limits for ROC plots
% colors - algorithm plot colors
% styles - algorithm plot linestyles
thres = [];
% Compute (xs,ys) and score (area under the curve) for every exp/alg
[nGt,nDt]=size(res); xs=cell(nGt,nDt); ys=xs; scores=zeros(nGt,nDt);
for g=1:nGt
for d=1:nDt
[xs{g,d},ys{g,d},~, score] = ...
bbGt('compRoc',res(g,d).gtr,res(g,d).dtr,plotRoc,samples);
if(plotRoc), ys{g,d}=1-ys{g,d}; score=1-score; end
%thres = [samples' thres' score'];
if(plotRoc), score=exp(mean(log(score))); else score=mean(score); end
scores(g,d)=[score];
end
end
return;
% Generate plots
if( plotRoc ), fName=[plotName 'Roc']; else fName=[plotName 'Pr']; end
stra={res(1,:).stra}; stre={res(:,1).stre}; scores1=round(scores*100);
if( plotAlg ), nPlots=nDt; else nPlots=nGt; end; plotNum=min(plotNum,nDt);
for p=1:nPlots
% prepare xs1,ys1,lgd1,colors1,styles1,fName1 according to plot type
if( plotAlg )
xs1=xs(:,p); ys1=ys(:,p); fName1=[fName stra{p}]; lgd1=stre;
for g=1:nGt, lgd1{g}=sprintf('%2i%% %s',scores1(g,p),stre{g}); end
colors1=uniqueColors(1,max(10,nGt)); styles1=repmat({'-','--'},1,nGt);
else
xs1=xs(p,:); ys1=ys(p,:); fName1=[fName stre{p}]; lgd1=stra;
for d=1:nDt, lgd1{d}=sprintf('%2i%% %s',scores1(p,d),stra{d}); end
kp=[find(strcmp(stra,'VJ')) find(strcmp(stra,'HOG')) 1 1];
[~,ord]=sort(scores(p,:)); kp=ord==kp(1)|ord==kp(2);
j=find(cumsum(~kp)>=plotNum-2); kp(1:j(1))=1; ord=fliplr(ord(kp));
xs1=xs1(ord); ys1=ys1(ord); lgd1=lgd1(ord); colors1=colors(ord,:);
styles1=styles(ord);
%f=fopen([fName1 '.txt'],'w');
%for d=1:nDt, fprintf(f,'%s %f\n',stra{d},scores(p,d)); end; fclose(f);
end
% plot curves and finalize display
figure(1); clf; grid on; hold on; n=length(xs1); h=zeros(1,n);
for i=1:n, h(i)=plot(xs1{i},ys1{i},'Color',colors1(i,:),...
'LineStyle',styles1{i},'LineWidth',2); end
if( plotRoc )
yt=[.05 .1:.1:.5 .64 .8]; ytStr=int2str2(yt*100,2);
for i=1:length(yt), ytStr{i}=['.' ytStr{i}]; end
set(gca,'XScale','log','YScale','log',...
'YTick',[yt 1],'YTickLabel',[ytStr '1'],...
'XMinorGrid','off','XMinorTic','off',...
'YMinorGrid','off','YMinorTic','off');
xlabel('false positives per image','FontSize',14);
ylabel('miss rate','FontSize',14); axis(lims);
else
x=1; for i=1:n, x=max(x,max(xs1{i})); end, x=min(x-mod(x,.1),1.0);
y=.8; for i=1:n, y=min(y,min(ys1{i})); end, y=max(y-mod(y,.1),.01);
xlim([0, x]); ylim([y, 1]); set(gca,'xtick',0:.1:1);
xlabel('Recall','FontSize',14); ylabel('Precision','FontSize',14);
end
if(~isempty(lgd1)), legend(h,lgd1,'Location','sw','FontSize',11); end
% save figure to disk (uncomment pdfcrop commands to automatically crop)
%savefig(fName1,1,'pdf','-r300','-fonts'); %close(1);
if(0), setenv('PATH',[getenv('PATH') ':/Library/TeX/texbin/']); end
if(0), system(['pdfcrop -margins ''-30 -20 -50 -10 '' ' ...
fName1 '.pdf ' fName1 '.pdf']); end
end
end
function plotBbs( res, plotName, pPage, type )
% This function plots sample fp/tp/fn bbs for given algs/exps
if(pPage==0), return; end; [nGt,nDt]=size(res);
% construct set/vid/frame index for each image
[~,setIds,vidIds,skip]=dbInfo;
k=length(res(1).gtr); is=zeros(k,3); k=0;
for s=1:length(setIds)
for v=1:length(vidIds{s})
A=loadVbb(s,v); s1=setIds(s); v1=vidIds{s}(v);
for f=skip-1:skip:A.nFrame-1, k=k+1; is(k,:)=[s1 v1 f]; end
end
end
for g=1:nGt
for d=1:nDt
% augment each bb with set/video/frame index and flatten
dtr=res(g,d).dtr; gtr=res(g,d).gtr;
for i=1:k
dtr{i}(:,7)=is(i,1); dtr{i}(:,8)=is(i,2); dtr{i}(:,9)=is(i,3);
gtr{i}(:,6)=is(i,1); gtr{i}(:,7)=is(i,2); gtr{i}(:,8)=is(i,3);
dtr{i}=dtr{i}'; gtr{i}=gtr{i}';
end
dtr=[dtr{:}]'; dtr=dtr(dtr(:,6)~=-1,:);
gtr=[gtr{:}]'; gtr=gtr(gtr(:,5)~=-1,:);
% get bb, ind, bbo, and indo according to type
if( strcmp(type,'fn') )
keep=gtr(:,5)==0; ord=randperm(sum(keep));
bbCol='r'; bboCol='y'; bbLst='-'; bboLst='--';
bb=gtr(:,1:4); ind=gtr(:,6:8); bbo=dtr(:,1:6); indo=dtr(:,7:9);
else
switch type
case 'dt', bbCol='y'; keep=dtr(:,6)>=0;
case 'fp', bbCol='r'; keep=dtr(:,6)==0;
case 'tp', bbCol='y'; keep=dtr(:,6)==1;
end
[~,ord]=sort(dtr(keep,5),'descend');
bboCol='g'; bbLst='--'; bboLst='-';
bb=dtr(:,1:6); ind=dtr(:,7:9); bbo=gtr(:,1:4); indo=gtr(:,6:8);
end
% prepare and display
n=sum(keep); bbo1=cell(1,n); O=ones(1,size(indo,1));
ind=ind(keep,:); bb=bb(keep,:); ind=ind(ord,:); bb=bb(ord,:);
for f=1:n, bbo1{f}=bbo(all(indo==ind(O*f,:),2),:); end
f=[plotName res(g,d).stre res(g,d).stra '-' type];
plotBbSheet( bb, ind, bbo1,'fName',f,'pPage',pPage,'bbCol',bbCol,...
'bbLst',bbLst,'bboCol',bboCol,'bboLst',bboLst );
end
end
end
function plotBbSheet( bb, ind, bbo, varargin )
% Draw sheet of bbs.
%
% USAGE
% plotBbSheet( R, varargin )
%
% INPUTS
% bb - [nx4] bbs to display
% ind - [nx3] the set/video/image number for each bb
% bbo - {nx1} cell of other bbs for each image (optional)
% varargin - prm struct or name/value list w following fields:
% .fName - ['REQ'] base file to save to
% .pPage - [1] num pages
% .mRows - [5] num rows / page
% .nCols - [9] num cols / page
% .scale - [2] size of image region to crop relative to bb
% .siz0 - [100 50] target size of each bb
% .pad - [4] amount of space between cells
% .bbCol - ['g'] bb color
% .bbLst - ['-'] bb LineStyle
% .bboCol - ['r'] bbo color
% .bboLst - ['--'] bbo LineStyle
dfs={'fName','REQ', 'pPage',1, 'mRows',5, 'nCols',9, 'scale',1.5, ...
'siz0',[100 50], 'pad',8, 'bbCol','g', 'bbLst','-', ...
'bboCol','r', 'bboLst','--' };
[fName,pPage,mRows,nCols,scale,siz0,pad,bbCol,bbLst, ...
bboCol,bboLst] = getPrmDflt(varargin,dfs);
n=size(ind,1); indAll=ind; bbAll=bb; bboAll=bbo;
for page=1:min(pPage,ceil(n/mRows/nCols))
Is = zeros(siz0(1)*scale,siz0(2)*scale,3,mRows*nCols,'uint8');
bbN=[]; bboN=[]; labels=repmat({''},1,mRows*nCols);
images = dir('/home/gbmsu/Desktop/cityscapes/data-val/rgb_images/*.png');
for f=1:mRows*nCols
% get fp bb (bb), double size (bb2), and other bbs (bbo)
f0=f+(page-1)*mRows*nCols; if(f0>n), break, end
[col,row]=ind2sub([nCols mRows],f);
ind=indAll(f0,:); bb=bbAll(f0,:); bbo=bboAll{f0};
hr=siz0(1)/bb(4); wr=siz0(2)/bb(3); mr=min(hr,wr);
bb2 = round(bbApply('resize',bb,scale*hr/mr,scale*wr/mr));
bbo=bbApply('intersect',bbo,bb2); bbo=bbo(bbApply('area',bbo)>0,:);
labels{f}=sprintf('%i/%i/%i',ind(1),ind(2),ind(3));
% normalize bb and bbo for siz0*scale region, then shift
bb=bbApply('shift',bb,bb2(1),bb2(2)); bb(:,1:4)=bb(:,1:4)*mr;
bbo=bbApply('shift',bbo,bb2(1),bb2(2)); bbo(:,1:4)=bbo(:,1:4)*mr;
xdel=-pad*scale-(siz0(2)+pad*2)*scale*(col-1);
ydel=-pad*scale-(siz0(1)+pad*2)*scale*(row-1);
bb=bbApply('shift',bb,xdel,ydel); bbN=[bbN; bb]; %#ok<AGROW>
bbo=bbApply('shift',bbo,xdel,ydel); bboN=[bboN; bbo]; %#ok<AGROW>
% load and crop image region
sr=seqIo(sprintf('%s/videos/set%02i/V%03i',dbInfo,ind(1),ind(2)),'r');
sr.seek(ind(3)); I=sr.getframe(); sr.close();
%I = imread(['/home/gbmsu/Desktop/cityscapes/data-val/rgb_images/' images(ind(3)).name]);
I=bbApply('crop',I,bb2,'replicate');
I=uint8(imResample(double(I{1}),siz0*scale));
Is(:,:,:,f)=I;
end
% now plot all and save
prm=struct('hasChn',1,'padAmt',pad*2*scale,'padEl',0,'mm',mRows,...
'showLines',0,'labels',{labels});
h=figureResized(.9,1); clf; montage2(Is,prm); hold on;
bbApply('draw',bbN,bbCol,2,bbLst); bbApply('draw',bboN,bboCol,2,bboLst);
savefig([fName int2str2(page-1,2)],h,'png','-r200','-fonts'); close(h);
if(0), save([fName int2str2(page-1,2) '.mat'],'Is'); end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A = loadVbb( s, v )
% Load given annotation (caches AS for speed).
persistent AS pth sIds vIds; [pth1,sIds1,vIds1]=dbInfo;
if(~strcmp(pth,pth1) || ~isequal(sIds,sIds1) || ~isequal(vIds,vIds1))
[pth,sIds,vIds]=dbInfo; AS=cell(length(sIds),1e3); end
A=AS{s,v}; %if(~isempty(A)), return; end
fName=@(s,v) sprintf('%s/annotations/set%02i/V%03i',pth,s,v);
A=vbb('vbbLoad',fName(sIds(s),vIds{s}(v))); AS{s,v}=A;
end
function [gts, occls, ols] = loadGt( exps, plotName, aspectRatio, bnds )
% Load ground truth of all experiments for all frames.
%fprintf('Loading ground truth: %s\n',plotName);
nExp=length(exps); gts=cell(1,nExp); occls=cell(1,nExp); ols=cell(1,nExp);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nExp
gName = [plotName '/gt-' exps(i).name '.mat'];
if(exist(gName,'file')), gt=load(gName); gts{i}=gt.gt; continue; end
%fprintf('\tExperiment #%d: %s\n', i, exps(i).name);
gt=cell(1,100000); k=0; lbls={'person','person?','people','ignore'};
occl=cell(1,100000);
ol=cell(1,100000);
filterGt = @(lbl,bb,bbv) filterGtFun(lbl,bb,bbv,...
exps(i).hr,exps(i).vr,exps(i).ar,bnds,aspectRatio);
for s=1:length(setIds)
for v=1:length(vidIds{s})
A = loadVbb(s,v);
for f=skip-1:skip:A.nFrame-1
[bb, bbv, ~] = vbb('frameAnn',A,f+1,lbls,filterGt); ids=bb(:,5)~=1;
oltmp = [];
occtmp = logical([]);
for bbind=1:size(bb,1)
hasocc = ~all(bbv(bbind,:) == 0);
occtmp = [occtmp hasocc];
boxtest1 = bb(bbind,:);
boxtest2 = bbv(bbind,:);
boxtest1(3:4) = boxtest1(1:2) + boxtest1(3:4);
boxtest2(3:4) = boxtest2(1:2) + boxtest2(3:4);
overlap = boxoverlap(boxtest1,boxtest2);
if hasocc
oltmp = [oltmp overlap];
else
oltmp = [oltmp -1];
end
end
bb(ids,:)=bbApply('resize',bb(ids,:),1,0,aspectRatio);
k=k+1; gt{k}=bb; ol{k} = oltmp'; occl{k} = occtmp';
end
end
end
gt=gt(1:k); gts{i}=gt; %save(gName,'gt','-v6');
ol=ol(1:k); occl=occl(1:k); ols{i}=ol; occls{i}=occl;
end
function p = filterGtFun( lbl, bb, bbv, hr, vr, ar, bnds, aspectRatio )
p=strcmp(lbl,'person'); h=bb(4); p=p & (h>=hr(1) & h<hr(2));
if(all(bbv==0)), vf=inf; else vf=bbv(3).*bbv(4)./(bb(3)*bb(4)); end
p=p & vf>=vr(1) & vf<=vr(2);
if(ar~=0), p=p & sign(ar)*abs(bb(3)./bb(4)-aspectRatio)<ar; end
p = p & bb(1)>=bnds(1) & (bb(1)+bb(3)<=bnds(3));
p = p & bb(2)>=bnds(2) & (bb(2)+bb(4)<=bnds(4));
end
end
function dts = loadDt( algs, plotName, aspectRatio, aDirs )
% Load detections of all algorithm for all frames.
nAlg=length(algs); dts=cell(1,nAlg);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nAlg
%fprintf('\tAlgorithm #%d: %s\n', i, algs{i});
dt=cell(1,100000); k=0; aDir=aDirs{i}; %[dbInfo '/res/' algs(i).name];
resize=1;
for s=1:length(setIds), s1=setIds(s);
for v=1:length(vidIds{s}), v1=vidIds{s}(v);
A=loadVbb(s,v); frames=skip-1:skip:A.nFrame-1;
vName=sprintf('%s/set%02d/V%03d',aDir,s1,v1);
if(~exist([vName '.txt'],'file'))
% consolidate bbs for video into single text file
bbs=cell(length(frames),1);
for f=1:length(frames)
fName = sprintf('%s/I%05d.txt',vName,frames(f));
if(~exist(fName,'file'))
error(['file not found:' fName]);
%bb=zeros(0,5);
else
bb=load(fName,'-ascii'); if(isempty(bb)), bb=zeros(0,5); end
end
if(size(bb,2)~=5), error('incorrect dimensions'); end
bbs{f}=[ones(size(bb,1),1)*(frames(f)+1) bb];
end
%for f=frames, delete(sprintf('%s/I%05d.txt',vName,f)); end
bbs=cell2mat(bbs); dlmwrite([vName '.txt'],bbs);
%rmdir(vName,'s');
end
bbs=load([vName '.txt'],'-ascii');
%disp([num2str(s1) ' ' num2str(v1) ' length is ' num2str(length(bbs))]);
%if length(bbs) > 0
for f=frames
if (length(bbs) > 0)
bb=bbs(bbs(:,1)==f+1,2:6);
%bb = bb((bb(:,5) > .9), :);
bb=bbApply('resize',bb,resize,0,aspectRatio);
else
bb=zeros(1,5);
end
k=k+1; dt{k}=bb;
%disp(size(bb));
end
%end
end
end
dt=dt(1:k); dts{i}=dt; %save(aName,'dt','-v6');
end
end
|
github | garrickbrazil/SDS-RCNN-master | fast_rcnn_generate_sliding_windows.m | .m | SDS-RCNN-master/functions/utils/fast_rcnn_generate_sliding_windows.m | 1,729 | utf_8 | a788da565d8e7d1810407473c3135094 | function roidb = fast_rcnn_generate_sliding_windows(conf, imdb, roidb, roipool_in_size)
% [pred_boxes, scores] = fast_rcnn_conv_feat_detect(conf, im, conv_feat, boxes, max_rois_num_in_gpu, net_idx)
% --------------------------------------------------------
% Fast R-CNN
% Reimplementation based on Python Fast R-CNN (https://github.com/rbgirshick/fast-rcnn)
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
regions.images = imdb.image_ids;
im_sizes = imdb.sizes;
regions.boxes = cellfun(@(x) generate_sliding_windows_one_image(conf, x, roipool_in_size), num2cell(im_sizes, 2), 'UniformOutput', false);
roidb = roidb_from_proposal(imdb, roidb, regions);
end
function boxes = generate_sliding_windows_one_image(conf, im_size, roipool_in_size)
im_scale = prep_im_for_blob_size(im_size, conf.scales, conf.max_size);
im_size = round(im_size * im_scale);
x1 = 1:conf.feat_stride:im_size(2);
y1 = 1:conf.feat_stride:im_size(1);
[x1, y1] = meshgrid(x1, y1);
x1 = x1(:);
y1 = y1(:);
x2 = x1 + roipool_in_size * conf.feat_stride - 1;
y2 = y1 + roipool_in_size * conf.feat_stride - 1;
boxes = [x1, y1, x2, y2];
boxes = filter_boxes(im_size, boxes);
boxes = bsxfun(@times, boxes-1, 1/im_scale) + 1;
end
function boxes = filter_boxes(im_size, boxes)
valid_ind = boxes(:, 1) >= 1 & boxes(:, 1) <= im_size(2) & ...
boxes(:, 2) >= 1 & boxes(:, 2) <= im_size(1) & ...
boxes(:, 3) >= 1 & boxes(:, 3) <= im_size(2) & ...
boxes(:, 4) >= 1 & boxes(:, 4) <= im_size(1);
boxes = boxes(valid_ind, :);
end |
github | garrickbrazil/SDS-RCNN-master | proposal_generate_anchors.m | .m | SDS-RCNN-master/functions/rpn/proposal_generate_anchors.m | 1,760 | utf_8 | a7edd291c6d30be7bd615061b1d5e8be | function anchors = proposal_generate_anchors(conf)
% anchors = proposal_generate_anchors(conf)
% --------------------------------------------------------
% RPN_BF
% Copyright (c) 2015, Liliang Zhang
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
anchor_cache_file = [conf.output_dir '/anchors'];
try
ld = load(anchor_cache_file);
anchors = ld.anchors;
catch
base_anchor = [1, 1, conf.base_anchor_size, conf.base_anchor_size];
ratio_anchors = ratio_jitter(base_anchor, 1/conf.anchor_ratios);
anchors = cellfun(@(x) scale_jitter(x, conf.anchor_scales), num2cell(ratio_anchors, 2), 'UniformOutput', false);
anchors = cat(1, anchors{:});
save(anchor_cache_file, 'anchors');
end
end
function anchors = ratio_jitter(anchor, ratios)
ratios = ratios(:);
w = anchor(3) - anchor(1) + 1;
h = anchor(4) - anchor(2) + 1;
x_ctr = anchor(1) + (w - 1) / 2;
y_ctr = anchor(2) + (h - 1) / 2;
size = w * h;
size_ratios = size ./ ratios;
ws = round(sqrt(size_ratios));
hs = round(ws .* ratios);
anchors = [x_ctr - (ws - 1) / 2, y_ctr - (hs - 1) / 2, x_ctr + (ws - 1) / 2, y_ctr + (hs - 1) / 2];
end
function anchors = scale_jitter(anchor, scales)
scales = scales(:);
w = anchor(3) - anchor(1) + 1;
h = anchor(4) - anchor(2) + 1;
x_ctr = anchor(1) + (w - 1) / 2;
y_ctr = anchor(2) + (h - 1) / 2;
ws = w * scales;
hs = h * scales;
anchors = [x_ctr - (ws - 1) / 2, y_ctr - (hs - 1) / 2, x_ctr + (ws - 1) / 2, y_ctr + (hs - 1) / 2];
end
|
github | garrickbrazil/SDS-RCNN-master | proposal_compute_targets.m | .m | SDS-RCNN-master/functions/rpn/proposal_compute_targets.m | 4,252 | utf_8 | cd447531a971eac63c9f754dbbd27dd4 | function [bbox_targets, overlaps, targets ] = proposal_compute_targets(conf, gt_rois, gt_ignores, gt_labels, ex_rois, image_roidb, im_scale)
% output: bbox_targets
% positive: [class_label, regression_label]
% ingore: [0, zero(regression_label)]
% negative: [-1, zero(regression_label)]
gt_rois_full = gt_rois;
gt_rois = gt_rois(gt_ignores~=1, :);
if isempty(gt_rois_full)
overlaps = zeros(size(ex_rois, 1), 1, 'double');
overlaps = sparse(overlaps);
targets = uint8(zeros(size(ex_rois, 1), 1));
else
ex_gt_full_overlaps = boxoverlap(ex_rois, gt_rois_full);
[overlaps, targets] = max(ex_gt_full_overlaps, [], 2);
overlaps = sparse(double(overlaps));
end
if isempty(gt_rois)
bbox_targets = zeros(size(ex_rois, 1), 5, 'double');
bbox_targets(:, 1) = -1;
bbox_targets = sparse(bbox_targets);
return;
end
% ensure gt_labels is in single
gt_labels = single(gt_labels);
assert(all(gt_labels > 0));
ex_gt_overlaps = boxoverlap(ex_rois, gt_rois); % for fg
ex_gt_full_overlaps = boxoverlap(ex_rois, gt_rois_full); % for bg
% drop anchors which run out off image boundaries, if necessary
contained_in_image = is_contain_in_image(ex_rois, round(image_roidb.im_size * im_scale));
% for each ex_rois(anchors), get its max overlap with all gt_rois
[ex_max_overlaps, ex_assignment] = max(ex_gt_overlaps, [], 2); % for fg
[ex_full_max_overlaps, ex_full_assignment] = max(ex_gt_full_overlaps, [], 2); % for bg
% for each gt_rois, get its max overlap with all ex_rois(anchors), the
% ex_rois(anchors) are recorded in gt_assignment
% gt_assignment will be assigned as positive
% (assign a rois for each gt at least)
[gt_max_overlaps, gt_assignment] = max(ex_gt_overlaps, [], 1);
% ex_rois(anchors) with gt_max_overlaps maybe more than one, find them
% as (gt_best_matches)
[gt_best_matches, gt_ind] = find(bsxfun(@eq, ex_gt_overlaps, [gt_max_overlaps]));
% Indices of examples for which we try to make predictions
% both (ex_max_overlaps >= conf.fg_thresh) and gt_best_matches are
% assigned as positive examples
fg_inds = unique([find(ex_max_overlaps >= conf.fg_thresh); gt_best_matches]);
% Indices of examples for which we try to used as negtive samples
% the logic for assigning labels to anchors can be satisfied by both the positive label and the negative label
% When this happens, the code gives the positive label precedence to
% pursue high recall
bg_inds = setdiff(find(ex_full_max_overlaps < conf.bg_thresh_hi & ex_full_max_overlaps >= conf.bg_thresh_lo), fg_inds);
contained_in_image_ind = find(contained_in_image);
fg_inds = intersect(fg_inds, contained_in_image_ind);
% Find which gt ROI each ex ROI has max overlap with:
% this will be the ex ROI's gt target
target_rois = gt_rois(ex_assignment(fg_inds), :);
src_rois = ex_rois(fg_inds, :);
% we predict regression_label which is generated by an un-linear
% transformation from src_rois and target_rois
[regression_label] = fast_rcnn_bbox_transform(src_rois, target_rois);
bbox_targets = zeros(size(ex_rois, 1), 5, 'double');
bbox_targets(fg_inds, :) = [gt_labels(ex_assignment(fg_inds)), regression_label];
bbox_targets(bg_inds, 1) = -1;
if 0 % debug
%%%%%%%%%%%%%%
im = imread(image_roidb.image_path);
[im, im_scale] = prep_im_for_blob(im, conf.image_means, conf.scales, conf.max_size);
imshow(mat2gray(im));
hold on;
cellfun(@(x) rectangle('Position', RectLTRB2LTWH(x), 'EdgeColor', 'r'), ...
num2cell(src_rois, 2));
cellfun(@(x) rectangle('Position', RectLTRB2LTWH(x), 'EdgeColor', 'g'), ...
num2cell(target_rois, 2));
hold off;
%%%%%%%%%%%%%%
end
bbox_targets = sparse(bbox_targets);
end
function contained = is_contain_in_image(boxes, im_size)
contained = boxes >= 1 & bsxfun(@le, boxes, [im_size(2), im_size(1), im_size(2), im_size(1)]);
contained = all(contained, 2);
end
|
github | garrickbrazil/SDS-RCNN-master | proposal_locate_anchors.m | .m | SDS-RCNN-master/functions/rpn/proposal_locate_anchors.m | 2,065 | utf_8 | 92ae934220e4d73044787702a7ee66b5 | function [anchors, im_scales] = proposal_locate_anchors(conf, im_size, target_scale, feature_map_size)
% [anchors, im_scales] = proposal_locate_anchors(conf, im_size, target_scale, feature_map_size)
% --------------------------------------------------------
% Faster R-CNN
% Copyright (c) 2015, Shaoqing Ren
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
% generate anchors for each scale
% only for fcn
if ~exist('feature_map_size', 'var')
feature_map_size = [];
end
func = @proposal_locate_anchors_single_scale;
if exist('target_scale', 'var')
[anchors, im_scales] = func(im_size, conf, target_scale, feature_map_size);
else
[anchors, im_scales] = arrayfun(@(x) func(im_size, conf, x, feature_map_size), ...
conf.scales, 'UniformOutput', false);
end
end
function [anchors, im_scale] = proposal_locate_anchors_single_scale(im_size, conf, target_scale, feature_map_size)
if isempty(feature_map_size)
im_scale = prep_im_for_blob_size(im_size, target_scale, conf.max_size);
img_size = round(im_size * im_scale);
output_size = [calc_output_size(img_size(1), conf), calc_output_size(img_size(2), conf)];
else
im_scale = prep_im_for_blob_size(im_size, target_scale, conf.max_size);
output_size = feature_map_size;
end
shift_x = [0:(output_size(2)-1)] * conf.feat_stride;
shift_y = [0:(output_size(1)-1)] * conf.feat_stride;
[shift_x, shift_y] = meshgrid(shift_x, shift_y);
% concat anchors as [channel, height, width], where channel is the fastest dimension.
anchors = reshape(bsxfun(@plus, permute(conf.anchors, [1, 3, 2]), ...
permute([shift_x(:), shift_y(:), shift_x(:), shift_y(:)], [3, 1, 2])), [], 4);
% equals to
% anchors = arrayfun(@(x, y) single(bsxfun(@plus, conf.anchors, [x, y, x, y])), shift_x, shift_y, 'UniformOutput', false);
% anchors = reshape(anchors, [], 1);
% anchors = cat(1, anchors{:});
end |
github | garrickbrazil/SDS-RCNN-master | proposal_prepare_image_roidb.m | .m | SDS-RCNN-master/functions/rpn/proposal_prepare_image_roidb.m | 3,295 | utf_8 | 3dc89509d3e21ef9b4675e9c54593241 | function [image_roidb, bbox_means, bbox_stds] = proposal_prepare_image_roidb_caltech(conf, imdbs, roidbs)
% --------------------------------------------------------
% RPN_BF
% Copyright (c) 2016, Liliang Zhang
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
if ~iscell(imdbs)
imdbs = {imdbs};
roidbs = {roidbs};
end
imdbs = imdbs(:);
roidbs = roidbs(:);
image_roidb = ...
cellfun(@(x, y) ... // @(imdbs, roidbs)
arrayfun(@(z) ... //@([1:length(x.image_ids)])
struct('image_path', x.image_at(z), 'image_id', x.image_ids{z}, 'im_size', x.sizes(z, :), 'imdb_name', x.name, 'num_classes', x.num_classes, ...
'boxes', y.rois(z).boxes(y.rois(z).gt, :), 'gt_ignores', y.rois(z).ignores,'class', y.rois(z).class(y.rois(z).gt, :), 'image', [], 'bbox_targets', []), ...
[1:length(x.image_ids)]', 'UniformOutput', true),...
imdbs, roidbs, 'UniformOutput', false);
image_roidb = cat(1, image_roidb{:});
% enhance roidb to contain bounding-box regression targets
[image_roidb, bbox_means, bbox_stds] = append_bbox_regression_targets(conf, image_roidb);
end
function [image_roidb, means, stds] = append_bbox_regression_targets(conf, image_roidb)
num_images = length(image_roidb);
image_roidb_cell = num2cell(image_roidb, 2);
% Compute values needed for means and stds
% var(x) = E(x^2) - E(x)^2
class_counts = zeros(1, 1) + eps;
sums = zeros(1, 4);
squared_sums = zeros(1, 4);
for i = 1:num_images
% for fcn, anchors are concated as [channel, height, width], where channel is the fastest dimension.
[anchors, im_scales] = proposal_locate_anchors(conf, image_roidb_cell{i}.im_size);
gt_ignores = image_roidb_cell{i}.gt_ignores;
% add by zhangll, whether the gt_rois empty?
if isempty(image_roidb_cell{i}.boxes)
[bbox_targets, ~] = ...
proposal_compute_targets(conf, image_roidb_cell{i}.boxes, gt_ignores, image_roidb_cell{i}.class, anchors{1}, image_roidb_cell{i}, im_scales{1});
else
[bbox_targets, ~] = ...
proposal_compute_targets(conf, scale_rois(image_roidb_cell{i}.boxes, image_roidb_cell{i}.im_size, im_scales{1}), gt_ignores, image_roidb_cell{i}.class, anchors{1}, image_roidb_cell{i}, im_scales{1});
end
targets = bbox_targets;
gt_inds = find(targets(:, 1) > 0);
image_roidb(i).has_bbox_target = ~isempty(gt_inds);
if image_roidb(i).has_bbox_target
class_counts = class_counts + length(gt_inds);
sums = sums + sum(targets(gt_inds, 2:end), 1);
squared_sums = squared_sums + sum(targets(gt_inds, 2:end).^2, 1);
end
end
means = bsxfun(@rdivide, sums, class_counts);
stds = (bsxfun(@minus, bsxfun(@rdivide, squared_sums, class_counts), means.^2)).^0.5;
end
function scaled_rois = scale_rois(rois, im_size, im_scale)
im_size_scaled = round(im_size * im_scale);
scale = (im_size_scaled - 1) ./ (im_size - 1);
scaled_rois = bsxfun(@times, rois-1, [scale(2), scale(1), scale(2), scale(1)]) + 1;
end
|
github | garrickbrazil/SDS-RCNN-master | proposal_im_detect.m | .m | SDS-RCNN-master/functions/rpn/proposal_im_detect.m | 4,354 | utf_8 | bddedd391689c4b62b1982733ab32434 | function [pred_boxes, scores, feat_scores_bg, feat_scores_fg] = proposal_im_detect(conf, caffe_net, im)
% [pred_boxes, scores, feat_scores_bg, feat_scores_fg] = proposal_im_detect(conf, caffe_net, im)
% --------------------------------------------------------
% RPN_BF
% Copyright (c) 2016, Liliang Zhang
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
im = single(im);
[im_blob, im_scales] = prep_im_for_blob(im, conf.image_means, conf.scales, conf.max_size);
im_size = size(im);
scaled_im_size = round(im_size * im_scales);
% permute data into caffe c++ memory, thus [num, channels, height, width]
im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
im_blob = permute(im_blob, [2, 1, 3, 4]);
im_blob = single(im_blob);
net_inputs = {im_blob};
% Reshape net's input blobs
caffe_net = reshape_input_data(caffe_net, net_inputs);
caffe_net.forward(net_inputs);
% Apply bounding-box regression deltas
box_deltas = caffe_net.blobs('proposal_bbox_pred').get_data();
featuremap_size = [size(box_deltas, 2), size(box_deltas, 1)];
% permute from [width, height, channel] to [channel, height, width], where channel is the fastest dimension
box_deltas = permute(box_deltas, [3, 2, 1]);
box_deltas = reshape(box_deltas, 4, [])';
anchors = proposal_locate_anchors(conf, size(im), conf.scales, featuremap_size);
pred_boxes = fast_rcnn_bbox_transform_inv(anchors, box_deltas);
% scale back
pred_boxes = bsxfun(@times, pred_boxes - 1, ...
([im_size(2), im_size(1), im_size(2), im_size(1)] - 1) ./ ([scaled_im_size(2), scaled_im_size(1), scaled_im_size(2), scaled_im_size(1)] - 1)) + 1;
pred_boxes = clip_boxes(pred_boxes, size(im, 2), size(im, 1));
% use softmax estimated probabilities
scores = caffe_net.blobs('proposal_cls_prob').get_data();
scores = scores(:, :, end);
scores = reshape(scores, size(caffe_net.blobs('proposal_bbox_pred').get_data(), 1), size(caffe_net.blobs('proposal_bbox_pred').get_data(), 2), []);
% store features
feat_scores = caffe_net.blobs('proposal_cls_score_reshape').get_data();
feat_scores_bg = feat_scores(:, :, 1);
feat_scores_fg = feat_scores(:, :, 2);
feat_scores_fg = reshape(feat_scores_fg, size(caffe_net.blobs('proposal_bbox_pred').get_data(), 1), size(caffe_net.blobs('proposal_bbox_pred').get_data(), 2), []);
feat_scores_fg = permute(feat_scores_fg, [3, 2, 1]);
feat_scores_fg = feat_scores_fg(:);
feat_scores_bg = reshape(feat_scores_bg, size(caffe_net.blobs('proposal_bbox_pred').get_data(), 1), size(caffe_net.blobs('proposal_bbox_pred').get_data(), 2), []);
feat_scores_bg = permute(feat_scores_bg, [3, 2, 1]);
feat_scores_bg = feat_scores_bg(:);
% permute from [width, height, channel] to [channel, height, width], where channel is the
% fastest dimension
scores = permute(scores, [3, 2, 1]);
scores = scores(:);
% drop too small boxes
[pred_boxes, scores, valid_ind] = filter_boxes(conf.test_min_box_size, conf.test_min_box_height, pred_boxes, scores);
% sort
[scores, scores_ind] = sort(scores, 'descend');
pred_boxes = pred_boxes(scores_ind, :);
feat_scores_fg = feat_scores_fg(valid_ind, :);
feat_scores_fg = feat_scores_fg(scores_ind, :);
feat_scores_bg = feat_scores_bg(valid_ind, :);
feat_scores_bg = feat_scores_bg(scores_ind, :);
end
function [boxes, scores, valid_ind] = filter_boxes(min_box_size, min_box_height, boxes, scores)
widths = boxes(:, 3) - boxes(:, 1) + 1;
heights = boxes(:, 4) - boxes(:, 2) + 1;
valid_ind = widths >= min_box_size & heights >= min_box_size & heights >= min_box_height;
boxes = boxes(valid_ind, :);
scores = scores(valid_ind, :);
end
function boxes = clip_boxes(boxes, im_width, im_height)
% x1 >= 1 & <= im_width
boxes(:, 1:4:end) = max(min(boxes(:, 1:4:end), im_width), 1);
% y1 >= 1 & <= im_height
boxes(:, 2:4:end) = max(min(boxes(:, 2:4:end), im_height), 1);
% x2 >= 1 & <= im_width
boxes(:, 3:4:end) = max(min(boxes(:, 3:4:end), im_width), 1);
% y2 >= 1 & <= im_height
boxes(:, 4:4:end) = max(min(boxes(:, 4:4:end), im_height), 1);
end
|
github | garrickbrazil/SDS-RCNN-master | proposal_generate_minibatch.m | .m | SDS-RCNN-master/functions/rpn/proposal_generate_minibatch.m | 8,106 | utf_8 | 60b7b8f202ab7fb43a0f00bf441f87cf | function [input_blobs, random_scale_inds, im_rgb] = proposal_generate_minibatch(conf, image_roidb)
% [input_blobs, random_scale_inds, im_rgb] = proposal_generate_minibatch(conf, image_roidb)
% --------------------------------------------------------
% RPN_BF
% Copyright (c) 2016, Liliang Zhang
% Licensed under The MIT License [see LICENSE for details]
% --------------------------------------------------------
num_images = length(image_roidb);
assert(num_images == 1, 'only support num_images == 1');
% Sample random scales to use for each image in this batch
random_scale_inds = randi(length(conf.scales), num_images, 1);
rois_per_image = conf.batch_size / num_images;
fg_rois_per_image = round(conf.batch_size * conf.fg_fraction);
% Get the input image blob
[im_blob, im_scales, im_rgb] = get_image_blob(conf, image_roidb, random_scale_inds);
rois = image_roidb(1);
% weak segmentation
if conf.has_weak
ped_mask_weights = single(ones(size(im_blob,1), size(im_blob,2)));
ped_mask = uint8(zeros(size(im_blob,1), size(im_blob,2)));
for gtind=1:size(rois.boxes,1)
ignore = rois.gt_ignores(gtind);
gt = rois.boxes(gtind,:);
x1 = min(max(round(gt(1)*im_scales(1)),1),size(ped_mask,2));
y1 = min(max(round(gt(2)*im_scales(1)),1),size(ped_mask,1));
x2 = min(max(round(gt(3)*im_scales(1)),1),size(ped_mask,2));
y2 = min(max(round(gt(4)*im_scales(1)),1),size(ped_mask,1));
w = x2 - x1;
h = y2 - y1;
% assign fg label
ped_mask(y1:y2,x1:x2) = 1;
% cost sensitive
if conf.cost_sensitive, ped_mask_weights(y1:y2,x1:x2) = single(1 + h/(conf.cost_mean_height*im_scales(1))); end
end
ped_mask = imresize(single(ped_mask), 1/conf.feat_stride, 'nearest');
ped_mask_weights = imresize(single(ped_mask_weights), 1/conf.feat_stride, 'nearest');
ped_mask = permute(ped_mask, [2, 1, 3, 4]);
ped_mask_weights = permute(ped_mask_weights, [2, 1, 3, 4]);
end
% get fcn output size
img_size = round(image_roidb(1).im_size * im_scales(1));
output_size = [calc_output_size(img_size(1), conf), calc_output_size(img_size(2), conf)];
% init blobs
labels_blob = zeros(output_size(2), output_size(1), size(conf.anchors, 1), length(image_roidb));
label_weights_blob = zeros(output_size(2), output_size(1), size(conf.anchors, 1), length(image_roidb));
bbox_targets_blob = zeros(output_size(2), output_size(1), size(conf.anchors, 1)*4, length(image_roidb));
bbox_loss_blob = zeros(output_size(2), output_size(1), size(conf.anchors, 1)*4, length(image_roidb));
[labels, label_weights, bbox_targets, bbox_loss] = ...
sample_rois(conf, image_roidb(1), fg_rois_per_image, rois_per_image, im_scales(1));
assert(img_size(1) == size(im_blob, 1) && img_size(2) == size(im_blob, 2));
cur_labels_blob = reshape(labels, size(conf.anchors, 1), output_size(1), output_size(2));
cur_label_weights_blob = reshape(label_weights, size(conf.anchors, 1), output_size(1), output_size(2));
cur_bbox_targets_blob = reshape(bbox_targets', size(conf.anchors, 1)*4, output_size(1), output_size(2));
cur_bbox_loss_blob = reshape(bbox_loss', size(conf.anchors, 1)*4, output_size(1), output_size(2));
% permute from [channel, height, width], where channel is the
% fastest dimension to [width, height, channel]
cur_labels_blob = permute(cur_labels_blob, [3, 2, 1]);
cur_label_weights_blob = permute(cur_label_weights_blob, [3, 2, 1]);
cur_bbox_targets_blob = permute(cur_bbox_targets_blob, [3, 2, 1]);
cur_bbox_loss_blob = permute(cur_bbox_loss_blob, [3, 2, 1]);
labels_blob(:, :, :, 1) = cur_labels_blob;
label_weights_blob(:, :, :, 1) = cur_label_weights_blob;
bbox_targets_blob(:, :, :, 1) = cur_bbox_targets_blob;
bbox_loss_blob(:, :, :, 1) = cur_bbox_loss_blob;
% permute data into caffe c++ memory, thus [num, channels, height, width]
im_blob = im_blob(:, :, [3, 2, 1], :); % from rgb to brg
im_blob = single(permute(im_blob, [2, 1, 3, 4]));
labels_blob = single(labels_blob);
labels_blob(labels_blob > 0) = 1;
label_weights_blob = single(label_weights_blob);
bbox_targets_blob = single(bbox_targets_blob);
bbox_loss_blob = single(bbox_loss_blob);
assert(~isempty(im_blob));
assert(~isempty(labels_blob));
assert(~isempty(label_weights_blob));
assert(~isempty(bbox_targets_blob));
assert(~isempty(bbox_loss_blob));
input_blobs = {im_blob, labels_blob, label_weights_blob, bbox_targets_blob, bbox_loss_blob};
if conf.has_weak
input_blobs{length(input_blobs) + 1} = ped_mask;
input_blobs{length(input_blobs) + 1} = ped_mask_weights;
end
end
%% Build an input blob from the images in the roidb at the specified scales.
function [im_blob, im_scales, im_] = get_image_blob(conf, images, random_scale_inds)
num_images = length(images);
processed_ims = cell(num_images, 1);
im_scales = nan(num_images, 1);
for i = 1:num_images
im = imread(images(i).image_path);
im_ = im;
target_size = conf.scales(random_scale_inds(i));
[im, im_scale] = prep_im_for_blob(im, conf.image_means, target_size, conf.max_size);
im_scales(i) = im_scale;
processed_ims{i} = im;
end
im_blob = im_list_to_blob(processed_ims);
end
%% Generate a random sample of ROIs comprising foreground and background examples.
function [labels, label_weights, bbox_targets, bbox_loss_weights] = sample_rois(conf, image_roidb, fg_rois_per_image, rois_per_image, im_scale)
[anchors, ~] = proposal_locate_anchors(conf, image_roidb.im_size);
gt_ignores = image_roidb.gt_ignores;
% add by zhangll, whether the gt_rois empty?
if isempty(image_roidb.boxes)
[bbox_targets, ~] = ...
proposal_compute_targets(conf, image_roidb.boxes, gt_ignores, image_roidb.class, anchors{1}, image_roidb, im_scale);
else
[bbox_targets, ~] = ...
proposal_compute_targets(conf, scale_rois(image_roidb.boxes, image_roidb.im_size, im_scale), gt_ignores, image_roidb.class, anchors{1}, image_roidb, im_scale);
end
gt_inds = find(bbox_targets(:, 1) > 0);
if ~isempty(gt_inds)
bbox_targets(gt_inds, 2:end) = ...
bsxfun(@minus, bbox_targets(gt_inds, 2:end), conf.bbox_means);
bbox_targets(gt_inds, 2:end) = ...
bsxfun(@rdivide, bbox_targets(gt_inds, 2:end), conf.bbox_stds);
end
ex_asign_labels = bbox_targets(:, 1);
% Select foreground ROIs as those with >= FG_THRESH overlap
fg_inds = find(bbox_targets(:, 1) > 0);
% Select background ROIs as those within [BG_THRESH_LO, BG_THRESH_HI)
bg_inds = find(bbox_targets(:, 1) < 0);
% select foreground
fg_num = min(fg_rois_per_image, length(fg_inds));
fg_inds = fg_inds(randperm(length(fg_inds), fg_num));
bg_num = min(rois_per_image - fg_rois_per_image, length(bg_inds));
bg_inds = bg_inds(randperm(length(bg_inds), bg_num));
labels = zeros(size(bbox_targets, 1), 1);
% set foreground labels
labels(fg_inds) = ex_asign_labels(fg_inds);
assert(all(ex_asign_labels(fg_inds) > 0));
bg_weight = 1;
label_weights = zeros(size(bbox_targets, 1), 1);
label_weights(fg_inds) = fg_rois_per_image/fg_num;
label_weights(bg_inds) = bg_weight;
bbox_targets = single(full(bbox_targets(:, 2:end)));
bbox_loss_weights = bbox_targets * 0;
bbox_loss_weights(fg_inds, :) = fg_rois_per_image / fg_num;
end
function scaled_rois = scale_rois(rois, im_size, im_scale)
im_size_scaled = round(im_size * im_scale);
scale = (im_size_scaled - 1) ./ (im_size - 1);
scaled_rois = bsxfun(@times, rois-1, [scale(2), scale(1), scale(2), scale(1)]) + 1;
end
|
github | garrickbrazil/SDS-RCNN-master | classification_demo.m | .m | SDS-RCNN-master/external/caffe/matlab/demo/classification_demo.m | 5,466 | utf_8 | 45745fb7cfe37ef723c307dfa06f1b97 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | garrickbrazil/SDS-RCNN-master | vbb.m | .m | SDS-RCNN-master/external/caltech_toolbox/vbb.m | 26,999 | utf_8 | 49eea1941e375a3293a6f9aa9ee21726 | function varargout = vbb( action, varargin )
% Data structure for video bounding box (vbb) annotations.
%
% A video bounding box (vbb) annotation stores bounding boxes (bbs) for
% objects of interest. The primary difference from a static annotation is
% that each object can exist for multiple frames, ie, a vbb annotation not
% only provides the locations of objects but also tracking information. A
% vbb annotation A is simply a Matlab struct. It contains data per object
% (such as a string label) and data per object per frame (such as a bb).
% Each object is identified with a unique integer id.
%
% Data per object (indexed by integer id) includes the following fields:
% init - 0/1 value indicating whether object w given id exists
% lbl - a string label describing object type (eg: 'pedestrian')
% str - the first frame in which object appears (1 indexed)
% end - the last frame in which object appears (1 indexed)
% hide - 0/1 value indicating object is 'hidden' (used during labeling)
%
% Data per object per frame (indexed by frame and id) includes:
% pos - [l t w h]: bb indicating predicted object extent
% posv - [l t w h]: bb indicating visible region (may be [0 0 0 0])
% occl - 0/1 value indicating if bb is occluded
% lock - 0/1 value indicating bb is 'locked' (used during labeling)
%
% vbb contains a number of utility functions for working with an
% annotation A, making it generally unnecessary to access the fields of A
% directly. The format for accessing the various utility functions is:
% outputs = vbb( 'action', inputs );
% Below is a list of utility functions, broken up into 3 categories.
% Occasionally more help is available via a call to help "vbb>action".
%
% %%% init and save/load annotation to/from disk
% Create new annotation for given length video
% A = vbb( 'init', nFrame, maxObj )
% Generate annotation filename (add .vbb and optionally time stamp)
% [fName,ext] = vbb( 'vbbName', fName, [timeStmp], [ext] )
% Save annotation A to fName with optional time stamp (F by default)
% vbb('vbbSave', A, fName, [timeStmp] )
% Load annotation from disk:
% A = vbb('vbbLoad', fName )
% Save annotation A to fName (in .txt format):
% vbb('vbbSaveTxt', A, fName, timeStmp )
% Load annotation from disk (in .txt format):
% A = vbb('vbbLoadTxt', fName )
% Export single frame annotations to tarDir/*.txt
% vbb( 'vbbToFiles', A, tarDir, [fs], [skip], [f0], [f1] )
% Combine single frame annotations from srcDir/*.txt
% [A,fs] = vbb( 'vbbFrFiles', srcDir, [fs] )
%
% %%% inspect / alter annotation
% Get number of unique objects in annotation
% n = vbb( 'numObj', A )
% Get an unused object id (for adding a new object)
% [A,id] = vbb( 'newId', A )
% Create a new, empty object (not added to A)
% [A,obj] = vbb( 'emptyObj', A, [frame] )
% Get struct with all data from frames s-e for given object
% obj = vbb( 'get', A, id, [s], [e] )
% Add object to annotation
% A = vbb( 'add', A, obj )
% Remove object from annotation
% A = vbb( 'del', A, id )
% Crop or extend object temporally
% A = vbb( 'setRng', A, id, s, e )
% Get object information, see above for valid properties
% v = vbb( 'getVal', A, id, name, [frmS], [frmE] )
% Set object information, see above for valid properties
% A = vbb( 'setVal', A, id, name, v, [frmS], [frmE] )
%
% %%% other functions
% Visulatization: draw annotation on top of current image
% hs = vbb( 'drawToFrame', A, frame )
% Uses seqPlayer to display seq file with overlayed annotations.
% vbb( 'vbbPlayer', A, srcName )
% Visulatization: create seq file w annotation superimposed.
% vbb( 'drawToVideo', A, srcName, tarName )
% Shift entire annotation by del frames. (useful for synchronizing w video)
% A = vbb( 'timeShift', A, del )
% Ensure posv is fully contained in pos
% A = vbb( 'swapPosv', A, validate, swap, hide )
% Stats: get stats about annotation
% [stats,stats1,logDur] = vbb( 'getStats', A );
% Returns the ground truth bbs for a single frame.
% [gt,posv,lbls] = vbb( 'frameAnn', A, frame, lbls, test )
%
% USAGE
% varargout = vbb( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also BBAPPLY
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,nargout);
[varargout{:}] = eval([action '(varargin{:});']);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% init / save / load
function A = init( nFrame, maxObj )
if( nargin<2 || isempty(maxObj) ), maxObj=16; end
A.nFrame = nFrame;
A.objLists = cell(1,nFrame);
A.maxObj = maxObj;
A.objInit = zeros(1,A.maxObj);
A.objLbl = cell(1,A.maxObj);
A.objStr = -ones(1,A.maxObj);
A.objEnd = -ones(1,A.maxObj);
A.objHide = zeros(1,A.maxObj);
A.altered = false;
A.log = 0;
A.logLen = 0;
end
function [fName,ext] = vbbName( fName, timeStmp, ext )
if(nargin<2), timeStmp=false; end; if(nargin<3), ext=''; end
[d,f,ext1]=fileparts(fName); if(isempty(ext)), ext=ext1; end
if(isempty(ext)), ext='.vbb'; end
if(timeStmp), f=[f '-' regexprep(datestr(now), ':| ', '-')]; end
if(isempty(d)), d='.'; end; fName=[d '/' f ext];
end
function vbbSave( A, fName, timeStmp )
if(nargin<3), timeStmp=false; end; vers=1.4; %#ok<NASGU>
[fName,ext]=vbbName(fName,timeStmp);
if(strcmp(ext,'.txt')), vbbSaveTxt(A,fName,timeStmp); return; end
A=cleanup(A); save(fName,'A','vers','-v6'); %#ok<NASGU>
end
function A = vbbLoad( fName )
[fName,ext]=vbbName(fName); vers=1.4;
if(strcmp(ext,'.txt')), A=vbbLoadTxt(fName); return; end
L = load( '-mat', fName );
if( ~isfield(L,'A') || ~isfield(L,'vers') );
error('Not a valid video annoation file.');
end;
A = L.A;
% .06 -> 1.0 conversion (add log/logLen)
if( L.vers==.06 )
L.vers=1.0; A.log=0; A.logLen=0;
end
% 1.0 -> 1.1 conversion (add trnc field)
if( L.vers==1.0 )
L.vers=1.1;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; end
for j=1:length(A.objLists{f}); A.objLists{f}(j).trnc=0; end
end
end
% 1.1 -> 1.2 conversion (add hide/posv fields)
if( L.vers==1.1 )
L.vers=1.2;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; end
for j=1:length(A.objLists{f}); A.objLists{f}(j).posv=[0 0 0 0]; end
end
A.objHide = zeros(1,A.maxObj);
end
% 1.2 -> 1.3 conversion (remove trnc field)
if( L.vers==1.2 )
L.vers=1.3;
for f=1:A.nFrame
if(isempty(A.objLists{f})); A.objLists{f}=[]; else
A.objLists{f} = rmfield(A.objLists{f},'trnc');
end
end
end
% 1.3 -> 1.4 conversion (remove objAr field)
if( L.vers==1.3 )
L.vers=1.4; A = rmfield(A,'objAr');
end
% check version
if( L.vers~=vers )
er = [num2str(L.vers) ' (current: ' num2str(vers) ')'];
error(['Incompatible versions: ' er]);
end
% order fields
order={'nFrame','objLists','maxObj','objInit','objLbl','objStr',...
'objEnd','objHide','altered','log','logLen'};
A = orderfields(A,order);
A.altered = false;
end
function vbbSaveTxt( A, fName, timeStmp )
if(nargin<3), timeStmp=false; end; vers=1.4;
fName=vbbName(fName,timeStmp,'.txt');
A=cleanup(A,0); n=numObj(A); nFrame=A.nFrame;
fid=fopen(fName,'w'); assert(fid>0);
% write header info to text
fp=@(varargin) fprintf(fid,varargin{:});
fp('%% vbb version=%f\n',vers); fp('nFrame=%i n=%i\n',nFrame,n);
fp('log=['); fp('%f ',A.log); fp(']\n');
% write each object to text
for id=1:n, o=get(A,id);
fp('\n-----------------------------------\n');
fp('lbl=''%s'' str=%i end=%i hide=%i\n',o.lbl,o.str,o.end,o.hide);
fp('pos =['); fp('%f %f %f %f; ',o.pos'); fp(']\n');
fp('posv=['); fp('%f %f %f %f; ',o.posv'); fp(']\n');
fp('occl=['); fp('%i ',o.occl); fp(']\n');
fp('lock=['); fp('%i ',o.lock); fp(']\n');
end
fclose(fid);
end
function A = vbbLoadTxt( fName )
fName=vbbName(fName,0,'.txt'); vers=1.4;
if(~exist(fName,'file')), error([fName ' not found']); end
try
% read in header and create A
f=fopen(fName,'r'); s=fgetl(f); v=sscanf(s,'%% vbb version=%f');
if(v~=vers), error('Incompatible versions: %f (current=%f)',v,vers); end
s=fgetl(f); r=sscanf(s,'nFrame=%d n=%d'); nFrame=r(1); n=r(2);
s=fgetl(f); assert(strcmp(s(1:5),'log=[')); assert(s(end)==']');
log=sscanf(s(6:end-1),'%f ')'; A=init(nFrame,n);
% read in each object in turn
for id=1:n
s=fgetl(f); assert(isempty(s));
s=fgetl(f); assert(strcmp(s,'-----------------------------------'));
s=fgetl(f); r=textscan(s,'lbl=%s str=%d end=%d hide=%d');
[A,o]=emptyObj(A,0); o.lbl=r{1}{1}(2:end-1);
o.str=r{2}; o.end=r{3}; o.hide=r{4};
s=fgetl(f); assert(strcmp(s(1:6),'pos =[')); assert(s(end)==']');
pos=sscanf(s(7:end-1),'%f %f %f %f;'); o.pos=reshape(pos,4,[])';
s=fgetl(f); assert(strcmp(s(1:6),'posv=[')); assert(s(end)==']');
posv=sscanf(s(7:end-1),'%f %f %f %f;'); o.posv=reshape(posv,4,[])';
s=fgetl(f); assert(strcmp(s(1:6),'occl=[')); assert(s(end)==']');
o.occl=sscanf(s(7:end-1),'%d ');
s=fgetl(f); assert(strcmp(s(1:6),'lock=[')); assert(s(end)==']');
o.lock=sscanf(s(7:end-1),'%d ');
A=add(A,o);
end
if(isempty(log)), A.log=0; A.logLen=0; else
A.log=log; A.logLen=length(log); end
A.altered=false; fclose(f);
catch e, fclose(f); throw(e);
end
end
function vbbToFiles( A, tarDir, fs, skip, f0, f1 )
% export single frame annotations to tarDir/*.txt
nFrm=A.nFrame; fName=@(f) ['I' int2str2(f-1,5) '.txt'];
if(nargin<3 || isempty(fs)), for f=1:nFrm, fs{f}=fName(f); end; end
if(nargin<4 || isempty(skip)), skip=1; end
if(nargin<5 || isempty(f0)), f0=1; end
if(nargin<6 || isempty(f1)), f1=nFrm; end
if(~exist(tarDir,'dir')), mkdir(tarDir); end
for f=f0:skip:f1
nObj=length(A.objLists{f}); objs=bbGt('create',nObj);
for j=1:nObj
o=A.objLists{f}(j); objs(j).lbl=A.objLbl{o.id}; objs(j).occ=o.occl;
objs(j).bb=round(o.pos); objs(j).bbv=round(o.posv);
end
bbGt('bbSave',objs,[tarDir '/' fs{f}]);
end
end
function [A,fs] = vbbFrFiles( srcDir, fs )
% combine single frame annotations from srcDir/*.txt
if(nargin<2 || isempty(fs)), fs=dir([srcDir '/*.txt']); fs={fs.name}; end
nFrm=length(fs); A=init(nFrm);
for f=1:nFrm
objs = bbGt('bbLoad',[srcDir '/' fs{f}]);
for j=1:length(objs)
[A,obj]=emptyObj(A,f); o=objs(j); obj.lbl=o.lbl;
obj.pos=o.bb; obj.occl=o.occ; obj.posv=o.bbv; A=add(A,obj);
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% inspect / alter annotation
function n = numObj( A )
n = sum( A.objInit );
end
function [A,id] = newId( A )
[val,id] = min( A.objInit );
if( isempty(val) || val~=0 );
A = doubleLen( A );
[val,id] = min( A.objInit );
end
assert(val==0);
end
function [A,obj] = emptyObj( A, frame )
[A,id] = newId( A );
obj.id = id;
obj.lbl = '';
obj.hide = 0;
if(nargin<2)
obj.str = -1;
obj.end = -1;
len = 0;
else
obj.str = frame;
obj.end = frame;
len = 1;
end
obj.pos = zeros(len,4);
obj.posv = zeros(len,4);
obj.occl = zeros(len,1);
obj.lock = ones(len,1);
end
function obj = get( A, id, s, e )
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==1 );
if(nargin<3); s=A.objStr(id); else assert(s>=A.objStr(id)); end;
if(nargin<4); e=A.objEnd(id); else assert(e<=A.objEnd(id)); end;
% get general object info
obj.id = id;
obj.lbl = A.objLbl{id};
obj.str = s;
obj.end = e;
obj.hide = A.objHide(id);
% get per-frame object info
len = obj.end-obj.str+1;
obj.pos = zeros(len,4);
obj.posv = zeros(len,4);
obj.occl = zeros(len,1);
obj.lock = zeros(len,1);
for i=1:len
f = obj.str+i-1;
objList = A.objLists{f};
obj1 = objList([objList.id]==id);
obj.pos(i,:) = obj1.pos;
obj.posv(i,:) = obj1.posv;
obj.occl(i) = obj1.occl;
obj.lock(i) = obj1.lock;
end
end
function A = add( A, obj )
% check id or get new id
id = obj.id;
if( id==-1 )
[A,id] = newId( A );
else
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==0 );
end
% save general object info
A.objInit(id) = 1;
A.objLbl{id} = obj.lbl;
A.objStr(id) = obj.str;
A.objEnd(id) = obj.end;
A.objHide(id) = obj.hide;
% save per-frame object info
len = obj.end - obj.str + 1;
assert( size(obj.pos,1)==len );
assert( size(obj.posv,1)==len );
assert( size(obj.occl,1)==len );
assert( size(obj.lock,1)==len );
for i = 1:len
obj1.id = id;
obj1.pos = obj.pos(i,:);
obj1.posv = obj.posv(i,:);
obj1.occl = obj.occl(i);
obj1.lock = obj.lock(i);
f = obj.str+i-1;
A.objLists{f}=[A.objLists{f} obj1];
end
A = altered( A );
end
function A = del( A, id )
assert( 0<id && id<=A.maxObj );
assert( A.objInit(id)==1 );
% delete per-frame object info
objStr = A.objStr(id);
objEnd = A.objEnd(id);
len = objEnd-objStr+1;
for i=1:len
f = objStr+i-1;
objList = A.objLists{f};
objList([objList.id]==id) = [];
A.objLists{f} = objList;
end
% delete general object info
A.objInit(id) = 0;
A.objLbl{id} = [];
A.objStr(id) = -1;
A.objEnd(id) = -1;
A.objHide(id) = 0;
A = altered( A );
end
function A = setRng( A, id, s, e )
assert( s>=1 && e<=A.nFrame && s<=e && A.objInit(id)==1 );
s0=A.objStr(id); e0=A.objEnd(id); assert( e>=s0 && e0>=s );
if(s==s0 && e==e0), return; end; A.objStr(id)=s; A.objEnd(id)=e;
if( s0>s )
objs=A.objLists{s0}; obj=objs([objs.id]==id); obj.occl=0; obj.lock=0;
for f=s:s0-1, A.objLists{f}=[A.objLists{f} obj]; end
elseif( s0<s )
for f=s0:s-1, os=A.objLists{f}; os([os.id]==id)=[]; A.objLists{f}=os; end
end
if( e>e0 )
objs=A.objLists{e0}; obj=objs([objs.id]==id); obj.occl=0; obj.lock=0;
for f=e0+1:e, A.objLists{f}=[A.objLists{f} obj]; end
elseif( e<e0 )
for f=e+1:e0, os=A.objLists{f}; os([os.id]==id)=[]; A.objLists{f}=os; end
end
A = altered( A );
end
function v = getVal( A, id, name, frmS, frmE )
if(nargin<4); frmS=[]; end;
if(nargin<5); frmE=frmS; end;
assert(strcmp(name,'init') || A.objInit(id)==1);
switch name
case 'lbl'
assert( isempty(frmS) );
v = A.objLbl{id};
case {'init','str','end','hide'}
assert( isempty(frmS) );
name = ['obj' upper(name(1)) name(2:end)];
v = A.(name)(id);
case {'pos','posv','occl','lock'}
assert( ~isempty(frmS) );
assert( A.objStr(id)<=frmS && frmE<=A.objEnd(id) );
frms = frmS:frmE; len=length(frms);
for f=1:len
objList = A.objLists{frms(f)};
v1 = objList([objList.id]==id).(name);
if( f==1 ); v=repmat(v1,[len 1]); else v(f,:) = v1; end
end
otherwise
error( ['invalid field: ' name] );
end
end
function A = setVal( A, id, name, v, frmS, frmE )
if(nargin<5); frmS=[]; end;
if(nargin<6); frmE=frmS; end;
assert( A.objInit(id)==1 );
switch name
case 'lbl'
assert( isempty(frmS) );
A.objLbl{id} = v;
case {'hide'}
assert( isempty(frmS) );
name = ['obj' upper(name(1)) name(2:end)];
A.(name)(id) = v;
case {'pos','posv','occl','lock'}
assert( ~isempty(frmS) );
assert( A.objStr(id)<=frmS && frmE<=A.objEnd(id) );
frms = frmS:frmE; len=length(frms);
for f=1:len
objList = A.objLists{frms(f)};
objList([objList.id]==id).(name) = v(f,:);
A.objLists{frms(f)} = objList;
end
otherwise
error( ['invalid/unalterable field: ' name] );
end
A = altered( A );
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% other functions
function hs = drawToFrame( A, frame )
hs=[];
for o=A.objLists{frame}
hr = bbApply('draw', o.pos, 'g', 2, '-' );
if(all(o.posv)==0), hrv=[]; else
hrv = bbApply('draw', o.posv, 'y', 2, '--' );
end
label = [A.objLbl{o.id} ' [' int2str(o.id) ']'];
ht = text( o.pos(1), o.pos(2)-10, label );
set( ht, 'color', 'w', 'FontSize', 10, 'FontWeight', 'bold' );
hs = [hs hr ht hrv]; %#ok<AGROW>
end
end
function vbbPlayer( A, srcName )
dispFunc=@(f) vbb('drawToFrame',A,f+1);
seqPlayer(srcName,dispFunc);
end
function drawToVideo( A, srcName, tarName )
% open video to read and make video to write
assert( ~strcmp(srcName,tarName) );
sr=seqIo(srcName,'r'); info=sr.getinfo();
nFrame=info.numFrames; w=info.width; h=info.height;
assert(A.nFrame==nFrame); sw=seqIo(tarName,'w',info);
% display and write each frame
ticId=ticStatus; hf=figure; hAx=axes('parent',hf);
hIm=imshow(zeros(h,w,3,'uint8'),'parent',hAx); truesize;
for i=1:nFrame
I=sr.getnext(); set(hIm,'CData',I); hs=drawToFrame(A,i);
I=getframe; I=I.cdata; I=I(1:h,1:w,:);
sw.addframe(I); delete(hs); tocStatus( ticId, i/nFrame );
end
sr.close(); sw.close(); close(hf);
end
function A = timeShift( A, del )
% shift entire annotation by del frames
nFrame=A.nFrame; locs=logical(A.objInit);
if(del>0), is=locs & A.objStr==1; A.objStr(is)=A.objStr(is)-del; end
A.objStr(locs)=min(max(A.objStr(locs)+del,1),nFrame);
A.objEnd(locs)=min(max(A.objEnd(locs)+del,1),nFrame);
if( del>0 ) % replicate annotation for first frame del times
A.objLists=[A.objLists(ones(1,del)) A.objLists(1:end-del)];
else % no annotations for last del frames
A.objLists=[A.objLists(1-del:end) cell(1,-del)];
end
end
function A = swapPosv( A, validate, swap, hide )
% Swap pos/posv and ensure pos/posv consistent.
%
% The visible region of an object (posv) should be a subset of the
% predicted region (pos). If the object is not occluded, then posv is the
% same as pos (posv=[0 0 0 0] by default and indicates posv not set).
% Swapping is used to swap pos and posv, and validating is used to ensure
% pos contains posv. In two cases no swapping/validating occurs. If occl==0
% for a given bb, posv is set to [0 0 0 0]. If occl==1 and posv=[0 0 0 0],
% posv is set to pos. In either case there is no need to swap or validate.
%
% The validate flag:
% validate==-1: posv = intersect(pos,posv)
% validate== 0: no validation
% validate==+1: pos = union(pos,posv)
% If posv is shrunk to 0, it is set to a small bb inside pos.
%
% The swap flag:
% swap==-1: pos and posv are swapped before validating
% swap== 0: no swapping
% swap==+1: pos and posv are swapped after validating
%
% The hide flag:
% hide==0: set hide attribute to 0 for all objects
% hide==1: set hide attribute to 1 iff object is at some point occluded
%
% Suppose a user has labeled pos in a given video using some annotation
% tool. At this point can swap pos and posv and use the same tool in the
% same manner to label posv (which is stored in pos). Afterwards, can swap
% pos/posv again, and ensure they are consistent, and both end up labeled.
% Additionally, in the second labeling phase, we may want to hide any
% object that is never occluded. The command to setup labeling of posv is:
% A=vbb('swapPosv',A,-1,1,1); % validate (trust pos) THEN swap
% Afterwards, to swap back, would use:
% A=vbb('swapPosv',A,1,-1,0); % swap THEN validate (trust posv)
% While labeling posv only frames where occl is already set should be
% altered (the occl flag itself shouldn't be altered).
%
% USAGE
% A = vbb( 'swapPosv', A, validate, swap, hide )
%
% INPUTS
% A - annotation structure
% validate - see above
% swap - see above
% hide - see above
%
% OUTPUTS
% A - updated annotation
%
% EXAMPLE
%
% see also vbb
for f=1:A.nFrame
for i=1:length(A.objLists{f})
o=A.objLists{f}(i); p=o.pos; v=o.posv; vt=[];
% v is trivial - either [0 0 0 0] or same as p, continue
if(o.occl==0), vt=[0 0 0 0]; elseif(all(v)==0), vt=p; end
if(~isempty(vt)), A.objLists{f}(i).posv=vt; continue; end
% optionally swap before validating
if(swap==-1), t=p; p=v; v=t; end
% validate
if( validate==-1 )
v = bbApply('intersect',v,p);
if(all(v==0)), v=[p(1:2)+p(3:4)/2 1 1]; end
elseif( validate==1 )
p = bbApply('union',v,p);
end
% optionally swap after validating
if(swap==1), t=p; p=v; v=t; end
% store results
o.pos=p; o.posv=v; A.objLists{f}(i)=o;
end
end
if(~hide), A.objHide(:)=0; else
for id=find( A.objInit )
occl=vbb('getVal',A,id,'occl',A.objStr(id),A.objEnd(id));
A.objHide(id) = all(occl==0);
end
end
end
function [stats,stats1,logDur] = getStats( A )
% get stats of many annotations simultaneously by first merging
if(length(A)>1), A=merge(A); end
% log activity (allows up to .25h of inactivity)
nObj0=numObj(A); if(nObj0==0), stats=struct(); return; end
log = A.log / 1.1574e-005 / 60 / 60;
locs = find( (log(2:end)-log(1:end-1)) > .25 );
logS=log([1 locs+1]); logE=log([locs A.logLen]);
logDur = sum(logE-logS);
% getStats1 on entire annotation
stats = getStats1( A );
% getStats1 separately for each label
lbl0=unique(A.objLbl); nLbl0=length(lbl0);
stats1=repmat(getStats1(subset(A,lbl0(1))),1,nLbl0);
for i0=2:nLbl0, stats1(i0)=getStats1(subset(A,lbl0(i0))); end
function stats = getStats1( A )
% unique labels and label counts
lbl=unique(A.objLbl); nLbl=length(lbl); lblCnts=zeros(1,nLbl);
for i=1:nLbl, lblCnts(i)=sum(strcmp(A.objLbl,lbl{i})); end
stats.labels=lbl; stats.labelCnts=lblCnts;
% get object lengths
nObj=numObj(A); stats.nObj=nObj;
len=A.objEnd-A.objStr+1; stats.len=len;
% get all per frame info in one flat array ordered by object id
nPerFrm=cellfun(@length,A.objLists); stats.nPerFrm=nPerFrm;
ols=A.objLists(nPerFrm>0); ols=[ols{:}];
ids=[ols.id]; [ids,order]=sort(ids); ols=ols(order); stats.ids=ids;
inds=[0 cumsum(len)]; stats.inds=inds;
% get all pos/posv and centers, also first/last frame for each obj
pos=reshape([ols.pos],4,[])'; posv=reshape([ols.posv],4,[])';
posS=pos(inds(1:end-1)+1,:); posE=pos(inds(2:end),:);
stats.pos=pos; stats.posv=posv; stats.posS=posS; stats.posE=posE;
% get object centers and per frame deltas
cen=bbApply('getCenter',pos); stats.cen=cen;
del=cen(2:end,:)-cen(1:end-1,:); del(inds(2:end),:)=-1; stats.del=del;
% get occlusion information
occl=(sum(posv,2)>0)'; %occl=[ols.occl]; <--slow
occFrac=1-posv(:,3).*posv(:,4)./pos(:,3)./pos(:,4); occFrac(occl==0)=0;
occTime=zeros(1,nObj); for i=1:nObj, occTime(i)=mean(occl(ids==i)); end
stats.occl=occl; stats.occFrac=occFrac'; stats.occTime=occTime;
end
function A = subset( A, lbls )
% find elements to keep
nObj=numObj(A); keep=false(1,nObj);
for i=1:length(lbls), keep=keep | strcmp(A.objLbl,lbls{i}); end
% clean up objLists by dropping elements
frms=find(cellfun('isempty',A.objLists)==0); ols=A.objLists;
for f=frms, ols{f}=ols{f}(keep([ols{f}.id])); end, A.objLists=ols;
% run cleanup to reorder/drop elements
A.objInit=keep; A=cleanup(A,0);
end
function A = merge( AS )
nFrm=0; nObj=0;
for i=1:numel(AS)
Ai=cleanup(AS(i),0);
for f=1:Ai.nFrame
for j=1:length(Ai.objLists{f}),
Ai.objLists{f}(j).id=Ai.objLists{f}(j).id+nObj;
end
end
Ai.objStr=Ai.objStr+nFrm; Ai.objEnd=Ai.objEnd+nFrm;
nFrm=Ai.nFrame+nFrm; Ai.nFrame=nFrm;
nObj=nObj+numObj(Ai); AS(i)=Ai;
end
A.nFrame = nFrm;
A.objLists = [AS.objLists];
A.maxObj = sum([AS.maxObj]);
A.objInit = [AS.objInit];
A.objLbl = [AS.objLbl];
A.objStr = [AS.objStr];
A.objEnd = [AS.objEnd];
A.objHide = [AS.objHide];
A.altered = false;
A.log = sort([AS.log]);
A.logLen = sum([AS.logLen]);
end
end
function [gt,posv,lbls1] = frameAnn( A, frame, lbls, test )
% Returns the ground truth bbs for a single frame.
%
% Returns bbs for all object with lbl in lbls. The result is an [nx5] array
% where each row is of the form [x y w h ignore]. [x y w h] is the bb and
% ignore is a 0/1 flag that indicates regions to be ignored. For each
% returned object, the ignore flag is set to 0 if test(lbl,pos,posv)=1 for
% the given object. For example, using lbls={'person','people'}, and
% test=@(lbl,bb,bbv) bb(4)>100, returns bbs for all 'person' and 'people'
% in given frame, and for any objects under 100 pixels tall ignore=1.
%
% USAGE
% [gt,posv,lbls] = vbb( 'frameAnn', A, frame, lbls, [test] )
%
% INPUTS
% A - annotation structure
% frame - the frame index
% lbls - cell array of string labels
% test - [] ignore = ~test(lbl,pos,posv)
%
% OUTPUTS
% gt - [n x 5] array containg ground truth for frame
% posv - [n x 4] bbs of visible regions
% lbls - [n x 1] list of object labels
%
% EXAMPLE
% lbls={'person','people'}; test=@(lbl,bb,bbv) bb(4)>100;
% [gt,lbls] = vbb( 'frameAnn', A, 200, lbls, test )
if( nargin<4 ), test=[]; end; assert(frame<=A.nFrame);
ng=length(A.objLists{frame}); ignore=0;
gt=zeros(ng,5); posv=zeros(ng,4); lbls1=cell(1,ng); keep=true(1,ng);
for g=1:ng
o=A.objLists{frame}(g); lbl=A.objLbl{o.id};
if(~any(strcmp(lbl,lbls))), keep(g)=0; continue; end
if(~isempty(test)), ignore=~test(lbl,o.pos,o.posv); end
gt(g,:)=[o.pos ignore]; lbls1{g}=lbl; posv(g,:)=o.posv;
end
gt=gt(keep,:); lbls1=lbls1(keep); posv=posv(keep,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper functions
function A = doubleLen( A )
maxObj = max(1,A.maxObj);
A.objInit = [A.objInit zeros(1,maxObj)];
A.objLbl = [A.objLbl cell(1,maxObj)];
A.objStr = [A.objStr -ones(1,maxObj)];
A.objEnd = [A.objEnd -ones(1,maxObj)];
A.objHide = [A.objHide zeros(1,maxObj)];
A.maxObj = max(1,A.maxObj * 2);
A = altered( A );
end
function A = altered( A )
A.altered = true;
if( length(A.log)==A.logLen )
A.log = [A.log zeros(1,A.logLen)];
end
T = now; sec=1.1574e-005;
if( A.logLen>0 && (T-A.log(A.logLen))/sec<1 )
A.log(A.logLen) = T;
else
A.logLen = A.logLen+1;
A.log(A.logLen) = T;
end
end
function A = cleanup( A, minn )
% cleanup() Removes placeholder entries from A
if( A.maxObj==0 ), return; end
if( nargin<2 || isempty(minn) ), minn=1; end
% reorder so all initialized objects are first
while( 1 )
% find first 0 entry in objInit
[val,id0] = min(A.objInit);
if( val==1 || id0==A.maxObj ), break; end
% find last 1 entry past 0 entry
[val,id1]=max(fliplr(A.objInit(id0+1:end))); id1=A.maxObj-id1+1;
if(val==0), break; end
% swap these two locations
A = swap( A, id0, id1 );
end
% now discard all uninitialized objects (keep at least minn though)
[val,n] = min(A.objInit); n=max(minn,n-1);
if( val==0 )
A.maxObj = n;
A.objInit = A.objInit(1:n);
A.objLbl = A.objLbl(1:n);
A.objStr = A.objStr(1:n);
A.objEnd = A.objEnd(1:n);
A.objHide = A.objHide(1:n);
end
% discard useless elements in log
A.log = A.log(1:A.logLen);
end
function A = swap( A, id1, id2 )
A0=A;
if(A0.objInit(id1)), fs=A0.objStr(id1):A0.objEnd(id1); else fs=[]; end
for f=fs, ol=A0.objLists{f}; ol([ol.id]==id1).id=id2; A.objLists{f}=ol; end
if(A0.objInit(id2)), fs=A0.objStr(id2):A0.objEnd(id2); else fs=[]; end
for f=fs, ol=A0.objLists{f}; ol([ol.id]==id2).id=id1; A.objLists{f}=ol; end
A.objInit(id1) = A0.objInit(id2); A.objInit(id2) = A0.objInit(id1);
A.objLbl(id1) = A0.objLbl(id2); A.objLbl(id2) = A0.objLbl(id1);
A.objStr(id1) = A0.objStr(id2); A.objStr(id2) = A0.objStr(id1);
A.objEnd(id1) = A0.objEnd(id2); A.objEnd(id2) = A0.objEnd(id1);
A.objHide(id1) = A0.objHide(id2); A.objHide(id2) = A0.objHide(id1);
end
|
github | garrickbrazil/SDS-RCNN-master | vbbLabeler.m | .m | SDS-RCNN-master/external/caltech_toolbox/vbbLabeler.m | 38,968 | utf_8 | 03ea75bed8df14e50d44027476666f52 | function vbbLabeler( objTypes, vidNm, annNm )
% Video bound box (vbb) Labeler.
%
% Used to annotated a video (seq file) with (tracked) bounding boxes. An
% online demo describing usage is available. The code below is fairly
% complex and poorly documented. Please do not email me with question about
% how it works (unless you discover a bug).
%
% USAGE
% vbbLabeler( [objTypes], [vidNm], [annNm] )
%
% INPUTS
% objTypes - [{'object'}] list of object types to annotate
% imgDir - [] initial video to load
% resDir - [] initial annotation to load
%
% OUTPUTS
%
% EXAMPLE
% vbbLabeler
%
% See also vbb, vbbPlayer
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% defaults
if(nargin<1 || isempty(objTypes)), objTypes={'object'}; end
if(nargin<2 || isempty(vidNm)), vidNm=''; end
if(nargin<3 || isempty(annNm)), annNm=''; end
% settable constants
maxSkip = 250; % max value for skip
nStep = 16; % number of objects to display in lower panel
repLen = 1; % number of seconds to replay on left replay
maxCache = 500; % max cache length (set as high as memory allows)
fps = 150; % initial fps for playback (if 0 uses actual fps)
skip0 = 20; % initial skip (zoom)
seqPad = 4; % amount of padding around object in seq view
siz0 = 20; % minimum rect width/height
sizLk = 0; % if true rects cannot be resized
colType=0; rectCols=uniqueColors(3,8); % color rects according to id
%colType=1; rectCols=uniqueColors(3,3); % color rects according to type
% handles to gui objects / other globals
enStr = {'off','on'};
[hFig, pLf, pRt, pMenu, pObj, pSeq ] = deal([]);
[A,skip,offset,curInd,seqH,objApi,dispApi,filesApi] = deal([]);
% initialize all
makeLayout();
filesApi = filesMakeApi();
objApi = objMakeApi();
dispApi = dispMakeApi();
filesApi.closeVid();
set(hFig,'Visible','on');
drawnow;
% optionally load default data
if(~isempty(vidNm)), filesApi.openVid(vidNm); end
if(~isempty(annNm)), filesApi.openAnn(annNm); end
function makeLayout()
% properties for gui objects
bg='BackgroundColor'; fg='ForegroundColor'; ha='HorizontalAlignment';
units={'Units','pixels'}; st='String'; ps='Position'; fs='FontSize';
axsPr=[units {'Parent'}]; o4=[1 1 1 1]; clr=[.1 .1 .1];
pnlPr=[units {bg,clr,'BorderType','none','Parent'}];
btnPr={bg,[.7 .7 .7],fs,10,ps};
chbPr={'Style','checkbox',fs,8,'Interruptible','off',bg,clr,fg,'w',ps};
txtPr={'Style','text',fs,8,bg,clr,fg,'w',ps};
edtPr={'Style','edit',fs,8,bg,clr,fg,'w',ps};
uic = @(varargin) uicontrol(varargin{:});
icn=load('vbbIcons'); icn=icn.icons;
% hFig: main figure
set(0,units{:}); ss=get(0,'ScreenSize');
if( ss(3)<800 || ss(4)<600 ), error('screen too small'); end
pos = [(ss(3)-780)/2 (ss(4)-580)/2 780 580];
hFig = figure( 'Name','VBB Labeler', 'NumberTitle','off', ...
'Toolbar','auto', 'MenuBar','none', 'ResizeFcn',@figResized, ...
'Color','k', 'Visible','off', 'DeleteFcn',@exitLb, ps,pos, ...
'keyPressFcn',@keyPress );
% pMenu: video/annotation menus
pMenu.hVid = uimenu(hFig,'Label','Video');
pMenu.hVidOpn = uimenu(pMenu.hVid,'Label','Open');
pMenu.hVidCls = uimenu(pMenu.hVid,'Label','Close');
pMenu.hAnn = uimenu(hFig,'Label','Annotation');
pMenu.hAnnNew = uimenu(pMenu.hAnn,'Label','New');
pMenu.hAnnOpn = uimenu(pMenu.hAnn,'Label','Open');
pMenu.hAnnSav = uimenu(pMenu.hAnn,'Label','Save');
pMenu.hAnnCls = uimenu(pMenu.hAnn,'Label','Close');
pMenu.hCn = [pMenu.hVid pMenu.hAnn];
% pObj: top panel containing object controls
pObj.h=uipanel(pnlPr{:},hFig);
pObj.hObjTp = uic( pObj.h,'Style','popupmenu',fs,8,units{:},...
ps,[31 2 100 25],st,objTypes,'Value',1);
pObj.hBtPrv = uic(pObj.h,btnPr{:},[5 3 25 25],'CData',icn.rNext{1});
pObj.hBtNxt = uic(pObj.h,btnPr{:},[132 3 25 25],'CData',icn.rNext{2});
pObj.hBtNew = uic(pObj.h,btnPr{:},[169 3 25 25],'CData',icn.rNew);
pObj.hBtDel = uic(pObj.h,btnPr{:},[196 3 25 25],'CData',icn.rDel);
pObj.hCbFix = uic(pObj.h,chbPr{:},[230 9 50 13],st,'Lock');
pObj.hStSiz = uic(pObj.h,txtPr{:},[280 9 80 13],ha,'Center');
pObj.hCn = [pObj.hObjTp pObj.hBtNew pObj.hBtDel ...
pObj.hBtPrv pObj.hBtNxt pObj.hCbFix];
% pSeq: bottom panel containing object sequence
pSeq.h=uipanel(pnlPr{:},hFig);
pSeq.hAx = axes(axsPr{:},pSeq.h,ps,o4);
pSeq.apiRng = selectorRange(pSeq.h,o4,nStep,[],[.1 .5 1]);
pSeq.apiOcc = selectorRange(pSeq.h,o4,nStep,[],[.9 .9 .7]);
pSeq.apiLck = selectorRange(pSeq.h,o4,nStep,[],[.5 1 .5]);
pSeq.lblRng = uic(pSeq.h,txtPr{:},o4,st,'vs',fs,7,ha,'Center');
pSeq.lblOcc = uic(pSeq.h,txtPr{:},o4,st,'oc',fs,7,ha,'Center');
pSeq.lblLck = uic(pSeq.h,txtPr{:},o4,st,'lk',fs,7,ha,'Center');
% pLf: left main panel
pLf.h=uipanel(pnlPr{:},hFig); pLf.hAx=axes(axsPr{:},hFig);
icn5={icn.pPlay{1},icn.pStep{1},icn.pPause,icn.pStep{2},icn.pPlay{2}};
for i=1:5, pLf.btn(i)=uic(pLf.h,btnPr{:},o4,'CData',icn5{i}); end
pLf.btnRep = uic(pLf.h,btnPr{:},[10 5 25 20],'CData',icn.pRepeat);
pLf.fpsLbl = uic(pLf.h,txtPr{:},o4,ha,'Left',st,'fps:');
pLf.fpsInd = uic(pLf.h,edtPr{:},o4,ha,'Center');
pLf.hFrInd = uic(pLf.h,edtPr{:},o4,ha,'Right');
pLf.hFrNum = uic(pLf.h,txtPr{:},o4,ha,'Left');
pLf.hCn = [pLf.btn pLf.btnRep];
% pRt: right main panel
pRt.h=uipanel(pnlPr{:},hFig); pRt.hAx=axes(axsPr{:},hFig);
pRt.btnRep = uic(pRt.h,btnPr{:},[10 5 25 20],'CData',icn.pRepeat);
pRt.btnGo = uic(pRt.h,btnPr{:},[350 5 25 20],'CData',icn.fJump);
pRt.hFrInd = uic(pRt.h,txtPr{:},o4,ha,'Right');
pRt.hFrNum = uic(pRt.h,txtPr{:},o4,ha,'Left');
pRt.stSkip = uic(pRt.h,txtPr{:},[55 8 45 14],ha,'Right');
pRt.edSkip = uic(pRt.h,edtPr{:},[100 7 28 16],ha,'Center');
pRt.stOffst = uic(pRt.h,txtPr{:},[140 7 30 14],ha,'Center');
pRt.slOffst = uic(pRt.h,'Style','slider',bg,clr,ps,[175 5 70 20]);
setIntSlider( pRt.slOffst, [1 nStep-1] );
pRt.hCn = [pRt.btnRep pRt.btnGo pRt.slOffst];
function figResized( h, e ) %#ok<INUSD>
% overall size of drawable area (fWxfH)
pos = get(hFig,ps); pad=8; pTopH=30;
fW=pos(3)-2*pad; fH=pos(4)-2*pad-pTopH-75;
fW0=1290; fH0=(480+fW0/nStep);
fW=max(fW,700); fH=max(fH,700*fH0/fW0);
fW=min(fW,fH*fW0/fH0); fH=min(fH,fW*fH0/fW0);
% where to draw
r = fW/fW0; fW=round(fW); fH=round(fH);
seqH=floor((fW0-pad)/nStep*r); seqW=seqH*nStep; seqH=seqH+29;
x = max(pad,(pos(3)-fW)/2);
y = max(pad,(pos(4)-fH-pTopH-70)/2);
% set panel positions (resized from canonical positions)
set( pObj.h, ps, [x y+fH+70 640*r pTopH] );
set( pLf.hAx, ps, [x y+seqH+32 640*r 480*r] );
set( pRt.hAx, ps, [x+650*r y+seqH+32 640*r 480*r] );
set( pLf.h, ps, [x y+seqH+2 640*r 30] );
set( pRt.h, ps, [x+650*r y+seqH+2 640*r 30] );
set( pSeq.h, ps, [x+(fW-seqW)/2+2 y seqW seqH] );
% postion pSeq contents
set(pSeq.hAx,ps,[0 11 seqW seqH-29]); y=1;
pSeq.apiLck.setPos([0 y seqW 10]);
set(pSeq.lblLck,ps,[-13 y 12 10]); y=seqH-18;
pSeq.apiOcc.setPos([0 y seqW 10]);
set(pSeq.lblOcc,ps,[-13 y 12 10]); y=seqH-9;
pSeq.apiRng.setPos([0 y seqW 10]);
set(pSeq.lblRng,ps,[-13 y 12 10]);
% postion pLf and pRt contents
x=640*r-90; set(pRt.btnGo,ps,[x+60 5 25 20]); x1=640/3*r-75;
set(pLf.hFrInd,ps,[x 7 40 16]); set(pLf.hFrNum,ps,[x+40 8 40 14]);
set(pRt.hFrInd,ps,[x-30 8 40 14]); set(pRt.hFrNum,ps,[x+10 8 40 14]);
for i2=1:5, set(pLf.btn(i2),ps,[640/2*r+(i2-3.5)*26+10 5 25 20]); end
set(pLf.fpsLbl,ps,[x1 8 23 14]); set(pLf.fpsInd,ps,[x1+23 7 38 16]);
% request display update
if(~isempty(dispApi)); dispApi.requestUpdate(true); end;
end
function exitLb( h, e ) %#ok<INUSD>
filesApi.closeVid();
end
function keyPress( h, evnt ) %#ok<INUSL>
char=int8(evnt.Character); if(isempty(char)), char=0; end;
if( char==28 ), dispApi.setPlay(-inf); end
if( char==29 ), dispApi.setPlay(+inf); end
if( char==31 ), dispApi.setPlay(0); end
end
function setIntSlider( hSlider, rng )
set(hSlider,'Min',rng(1),'Value',rng(1),'Max',rng(2));
minSt=1/(rng(2)-rng(1)); maxSt=ceil(.25/minSt)*minSt;
set(hSlider,'SliderStep',[minSt maxSt]);
end
end
function api = objMakeApi()
% variables
[objId,objS,objE,objInd,seqObjs,lims] = deal([]);
apiRng=pSeq.apiRng; apiOcc=pSeq.apiOcc; apiLck=pSeq.apiLck;
% callbacks
set(pObj.hBtNew, 'callback', @(h,e) objNew());
set(pObj.hBtDel, 'callback', @(h,e) objDel());
set(pObj.hBtPrv, 'callback', @(h,e) objToggle(-1));
set(pObj.hBtNxt, 'callback', @(h,e) objToggle(+1));
set(pObj.hObjTp, 'callback', @(h,e) objSetType());
set(pObj.hCbFix, 'callback', @(h,e) objSetFixed());
apiRng.setRngChnCb(@objSetRng); apiRng.setLockCen(1);
apiOcc.setRngChnCb(@objSetOcc); apiLck.setRngChnCb(@objSetLck);
% create api
api=struct( 'init',@init, 'drawRects',@drawRects, ...
'prepSeq',@prepSeq, 'prepPlay',@prepPlay, ...
'annForSave',@annForSave, 'annSaved',@annSaved );
function init()
[objId,objS,objE,objInd,seqObjs,lims] = deal([]);
objId=-1; objSelect(-1); isAnn=~isempty(A); prepPlay();
if( ~isAnn ), return; end
lims=[0 0 dispApi.width() dispApi.height()]+.5;
objTypes = unique([A.objLbl(A.objInit==1) objTypes]);
t='*new-type*'; objTypes=[setdiff(objTypes,t) t];
set( pObj.hObjTp, 'String', objTypes, 'Value',1 );
end
function prepPlay()
if(objId>0), A=vbb('setRng',A,objId,objS+1,objE+1); end
set(pObj.hStSiz,'String',''); set(pObj.hCn,'Enable','off');
apiRng.enable(0); apiOcc.enable(0); apiLck.enable(0);
end
function seqI = prepSeq()
seqI=100*ones(seqH,seqH*nStep,3,'uint8'); seqObjs=[];
if(isempty(A)), return; end; n=nStepVis();
% see if objId still visible, adjust controls accordingly
lstInd = curInd + min(dispApi.nFrameRt(),skip*n-1);
isVis = objId>0 && objS<=lstInd && objE>=curInd;
set(pObj.hStSiz,'String',''); set(pObj.hCn,'Enable','on');
apiRng.enable(isVis); apiOcc.enable(isVis); apiLck.enable(isVis);
if(~isVis), objSelect(-1); return; end
% extrapolate obj to current range for display only
objSe=min(objS,curInd); objEe=max(objE,lstInd);
A = vbb( 'setRng', A, objId, objSe+1, objEe+1 );
% bound objInd to be in a visible axes
s=max(objSe,curInd); e=min(objEe,lstInd);
objInd = min(max(objInd,s),e);
objInd = curInd + skip*floor((objInd-curInd)/skip);
% update apiRng/apiOcc/apiLck
s = max(floor((objS-curInd)/skip)+1,1);
e = min(floor((objE-curInd)/skip)+1,n);
rng=zeros(1,nStep); occ=rng; lck=rng; rng(s:e)=1;
for i=1:n
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,1);
occ(i) = max(vbb('getVal',A,objId,'occl',ind0+1,ind1+1));
lck(i) = max(vbb('getVal',A,objId,'lock',ind0+1,ind1+1));
end;
apiRng.setRng(rng); apiOcc.setRng(occ); apiLck.setRng(lck);
apiRng.enable([1 n]); apiOcc.enable([s e]); apiLck.enable([s e]);
if(objS<curInd), lk=0; else lk=[]; end; apiRng.setLockLf(lk);
if(objE>lstInd), lk=0; else lk=[]; end; apiRng.setLockRt(lk);
% update other gui controls
objType=vbb('getVal',A,objId,'lbl');
set(pObj.hObjTp,'Value',find(strcmp(objType,objTypes)));
p=ceil(vbb('getVal',A,objId,'pos',objInd+1));
set(pObj.hStSiz,'String',[num2str(p(3)) ' x ' num2str(p(4))]);
% create seqObjs and seqI for display
seqObjs = repmat(struct(),1,n);
for i=0:n-1, ind=curInd+i*skip;
% absolute object location
pos0 = vbb('getVal', A, objId, 'pos', ind+1 );
posv = vbb('getVal', A, objId, 'posv', ind+1 );
% crop / resize sequence image
posSq = bbApply( 'resize', pos0, seqPad, seqPad );
posSq = bbApply( 'squarify', posSq, 0 );
[Ii,posSq] = bbApply('crop',dispApi.getImg(ind),posSq); Ii=Ii{1};
rows = round(linspace(1,size(Ii,1),seqH-2));
cols = round(linspace(1,size(Ii,2),seqH-2));
seqI(2:seqH-1,(2:seqH-1)+i*seqH,:) = Ii(rows,cols,:);
% oLim~=intersect(posSq,lims); pos~=centered(pos0*res)
res = (seqH-2)/size(Ii,1);
xDel=-i*seqH-1+posSq(1)*res; yDel=-1+posSq(2)*res;
oLim = bbApply('intersect',lims-.5,posSq);
oLim = bbApply('shift',oLim*res,xDel,yDel);
pos = bbApply('shift',pos0*res,xDel,yDel);
if(any(posv)), posv=bbApply('shift',posv*res,xDel,yDel); end
% seqObjs info
lks=vbb('getVal',A,objId,'lock',ind+1,objGrpInd(ind,1)+1);
seqObjs(i+1).pos0=pos0; seqObjs(i+1).pos=pos;
seqObjs(i+1).posv=posv; seqObjs(i+1).res=res;
seqObjs(i+1).lims=oLim; seqObjs(i+1).lock=max(lks);
end
end
function hs = drawRects( flag, ind )
hs=[]; if(isempty(A)), return; end
switch flag
case {'panelLf','panelRt'}
os=A.objLists{ind+1}; n=length(os);
if(n>0), [~,ord]=sort([os.id]==objId); os=os(ord); end
lockSet = get(pObj.hCbFix,'Value');
playMode = strcmp(get(pObj.hObjTp,'enable'),'off');
for i=1:n, o=os(i); id=o.id; lbl=A.objLbl(id);
if(A.objHide(id)), continue; end
if(lockSet && id~=objId && ~playMode), continue; end
static=(lockSet && id~=objId) || playMode;
hs1=drawRect(o.pos,o.posv,lims,lbl,static,id,ind,-1);
hs=[hs hs1]; %#ok<AGROW>
end
case 'objSeq'
if(objInd==-1), return; end
n=nStepVis(); id=objId; lbl=A.objLbl(id);
for i=1:n, o=seqObjs(i); ind=curInd+skip*(i-1);
hs1=drawRect(o.pos,o.posv,o.lims,lbl,0,id,ind,i-1);
hs=[hs hs1]; %#ok<AGROW>
end
end
function hs = drawRect(pos,posv,lims,lbl,static,id,ind,sid)
if(colType), t=find(strcmp(lbl,objTypes)); else t=id; end
col=rectCols(mod(t-1,size(rectCols,1))+1,:);
if(id~=objId), ls='-'; else
if(ind==objInd), ls='--'; else ls=':'; end; end
rp = {'lw',2,'color',col,'ls',ls,'rotate',0,'ellipse',0};
[hs,api]=imRectRot('pos',pos,'lims',lims,rp{:});
api.setSizLock( sizLk );
if( static )
api.setPosLock(1);
ht=text(pos(1),pos(2)-10, lbl); hs=[hs ht];
set(ht,'color','w','FontSize',10,'FontWeight','bold');
else
api.setPosSetCb( @(pos) objSetPos(pos(1:4),id,ind,sid) );
end
if( any(posv) )
rp={'LineWidth',2,'EdgeColor','y','LineStyle',':'};
hs = [hs rectangle('Position',posv,rp{:})];
end
end
function objSetPos( pos, id, ind, sid )
if(sid>=0), o=seqObjs(sid+1); pos=o.pos0-(o.pos-pos)/o.res; end
if(sid>0), dispApi.setOffset(sid); end
pos=constrainPos(pos); A=vbb('setVal',A,id,'pos',pos,ind+1);
if(objId==id), objS=min(objS,ind); objE=max(objE,ind); end
objSelect(id,ind); ind0=curInd+floor((ind-curInd)/skip)*skip;
ind1=objGrpInd(ind0,0); lks=zeros(ind1-ind0+1,1);
A = vbb('setVal',A,id,'lock',lks,ind0+1,ind1+1);
dispApi.requestUpdate();
end
end
function objNew()
[A,o]=vbb('emptyObj',A,curInd+1); t=get(pObj.hObjTp,'Value');
o.lbl=objTypes{t}; if(colType==0), t=o.id; end
col=rectCols(mod(t-1,size(rectCols,1))+1,:);
rp={'lw',2,'color',col,'ls','--','rotate',0,'ellipse',0};
pos=dispApi.newRect(lims,rp); o.pos=constrainPos(pos);
A=vbb('add',A,o); objSelect(o.id,curInd); dispApi.requestUpdate();
end
function objDel()
if(objId<=0), return; end; A=vbb('del',A,objId);
objId=-1; objSelect(-1); dispApi.requestUpdate();
end
function objSetLck( rng0, rng1 )
assert(objId>0); [lf,rt]=apiRng.getBnds(rng0~=rng1);
% set object locks accordingly
for i=lf:rt
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,0);
lks = [rng1(i); zeros(ind1-ind0,1)];
A=vbb('setVal',A,objId,'lock',lks,ind0+1,ind1+1);
end
s=max(objS,curInd); e=min(objE,curInd+skip*(nStepVis()-1));
if(~rng1(lf) || s==e), dispApi.requestUpdate(); return; end
% interpolate intermediate positions
o=vbb('get',A,objId,s+1,e+1); pos=[o.pos]; [n,k]=size(pos);
lks=[o.lock]; lks([1 end])=1; lks=find(lks);
for i=1:k, pos(:,i)=interp1(lks,pos(lks,i),1:n,'cubic'); end
pos=constrainPos(pos); A=vbb('setVal',A,objId,'pos',pos,s+1,e+1);
dispApi.requestUpdate();
end
function objSetRng( rng0, rng1 )
[lf0,rt0]=apiRng.getBnds( rng0 );
[lf1,rt1]=apiRng.getBnds( rng1 );
rt1=min(rt1,nStepVis()); assert(objId>0);
if(lf1~=lf0), objS=curInd+(lf1-1)*skip; end
if(rt1~=rt0), objE=curInd+(rt1-1)*skip; end
if(lf1~=lf0 || rt1~=rt0), objSelect(objId,objInd); end
dispApi.requestUpdate();
end
function objSetOcc( rng0, rng1 )
assert(objId>0); [lf,rt]=apiRng.getBnds(rng0~=rng1); assert(lf>0);
if(lf>1 && rng0(lf-1)==1), lf=lf-1; rng1(lf)=1; end %extend lf
if(rt<nStep && rng0(rt+1)==1), rt=rt+1; rng1(rt)=1; end %extend rt
for i=lf:rt
ind0=curInd+(i-1)*skip; ind1=objGrpInd(ind0,0);
occl = ones(ind1-ind0+1,1)*rng1(i);
A=vbb('setVal',A,objId,'occl',occl,ind0+1,ind1+1);
end; dispApi.requestUpdate();
end
function objSetFixed(), dispApi.requestUpdate(); end
function objSetType()
type = get(pObj.hObjTp,'Value');
if( strcmp(objTypes{type},'*new-type*') )
typeStr = inputdlg('Define new object type:');
if(isempty(typeStr) || any(strcmp(typeStr,objTypes)))
set(pObj.hObjTp,'Value',1); return; end
objTypes = [objTypes(1:end-1) typeStr objTypes(end)];
set(pObj.hObjTp,'String',objTypes,'Value',length(objTypes)-1);
end
if( objId>0 )
A = vbb('setVal',A,objId,'lbl',objTypes{type});
dispApi.requestUpdate();
end
end
function objToggle( d )
li=curInd; ri=curInd+skip*offset;
os=A.objLists{li+1}; if(isempty(os)), L=[]; else L=[os.id]; end
os=A.objLists{ri+1}; if(isempty(os)), R=[]; else R=[os.id]; end
[ids,R,L]=union(R,L); inds=[ones(1,numel(L))*li ones(1,numel(R))*ri];
keep=A.objHide(ids)==0; ids=ids(keep); inds=inds(keep);
n=length(ids); if(n==0), return; end
if(objId==-1), if(d==1), j=1; else j=n; end; else
j=find(ids==objId)+d; end
if(j<1 || j>n), objSelect(-1); else objSelect(ids(j),inds(j)); end
dispApi.requestUpdate();
end
function objSelect( id, ind )
if(objId>0), A=vbb('setRng',A,objId,objS+1,objE+1); end
if(id==-1), [objId,objS,objE,objInd]=deal(-1); return; end
objS=vbb('getVal',A,id,'str')-1; objE=vbb('getVal',A,id,'end')-1;
objId=id; objInd=ind;
end
function ind1 = objGrpInd( ind0, useExtended )
ind1 = min(ind0+skip-1,curInd+dispApi.nFrameRt());
if(~useExtended); ind1=min(ind1,objE); end
end
function n = nStepVis()
n = min(nStep,floor(dispApi.nFrameRt()/skip+1));
end
function pos = constrainPos( pos )
p=pos; p(:,3:4)=max(1,p(:,3:4)); r=max(1,siz0./p(:,3:4));
dy=(r(:,2)-1).*p(:,4); p(:,2)=p(:,2)-dy/2; p(:,4)=p(:,4)+dy;
dx=(r(:,1)-1).*p(:,3); p(:,1)=p(:,1)-dx/2; p(:,3)=p(:,3)+dx;
s=p(:,1:2); e=s+p(:,3:4);
for j=1:2, s(:,j)=min(max(s(:,j),lims(j)),lims(j+2)-siz0); end
for j=1:2, e(:,j)=max(min(e(:,j),lims(j+2)),s(:,j)+siz0); end
pos = [s e-s];
end
function A1 = annForSave()
if(objId==-1), A1=A; else A1=vbb('setRng',A,objId,objS+1,objE+1); end
end
function annSaved(), assert(~isempty(A)); A.altered=false; end
end
function api = dispMakeApi()
% variables
[sr, info, looping, nPlay, replay, needUpdate, dispMode, ...
timeDisp, hImLf, hImRt, hImSeq, hObjCur] = deal([]);
% callbacks
set( pRt.slOffst, 'Callback', @(h,e) setOffset() );
set( pRt.edSkip, 'Callback', @(h,e) setSkip() );
set( pLf.fpsInd, 'Callback', @(h,e) setFps() );
set( pLf.btnRep, 'Callback', @(h,e) setPlay('replayLf') );
set( pRt.btnRep, 'Callback', @(h,e) setPlay('replayRt') );
set( pRt.btnGo, 'Callback', @(h,e) setFrame('go') );
set( pLf.hFrInd, 'Callback', @(h,e) setFrame() );
set( pLf.btn(1), 'Callback', @(h,e) setPlay(-inf) );
set( pLf.btn(2), 'Callback', @(h,e) setFrame('-') );
set( pLf.btn(3), 'Callback', @(h,e) setPlay(0) );
set( pLf.btn(4), 'Callback', @(h,e) setFrame('+') );
set( pLf.btn(5), 'Callback', @(h,e) setPlay(+inf) );
% create api
api = struct( 'requestUpdate',@requestUpdate, 'init',@init, ...
'newRect',@newRect, 'setOffset',@setOffset, ...
'nFrame',@nFrame, 'nFrameRt', @nFrameRt, 'getImg',@getImg, ...
'width',@width, 'height',@height, 'setPlay', @setPlay );
function init( sr1 )
if(isstruct(sr)), sr=sr.close(); end; delete(hObjCur);
[sr, info, looping, nPlay, replay, needUpdate, dispMode, ...
timeDisp, hImLf, hImRt, hImSeq, hObjCur] = deal([]);
nPlay=0; replay=0; dispMode=0; looping=1; curInd=0;
needUpdate=1; sr=sr1; skip=1;
if(isstruct(sr)), info=sr.getinfo(); else
info=struct('numFrames',0,'width',0,'height',0,'fps',25); end
if(fps), info.fps=fps; end
setOffset(nStep-1); setSkip(skip0); setFps(info.fps);
hs = [pLf.hAx pRt.hAx pSeq.hAx];
for h=hs; cla(h); set(h,'XTick',[],'YTick',[]); end
set([pLf.hCn pRt.hCn],'Enable',enStr{(nFrame>0)+1});
set([pLf.hFrInd pRt.hFrInd],'String','0');
set([pLf.hFrNum pRt.hFrNum],'String',[' / ' int2str(nFrame)]);
looping=0; requestUpdate();
end
function dispLoop()
if( looping ), return; end; looping=1; k=0;
while( 1 )
% if vid not loaded nothing to display
if( nFrame==0 ), looping=0; return; end
% increment/decrement curInd/nPlay appropriately
if( nPlay~=0 )
needUpdate=1; fps=info.fps; t=clock(); t=t(6)+60*t(5);
del=round(fps*(t-timeDisp)); timeDisp=timeDisp+del/fps;
if(nPlay>0), del=min(del,nPlay); else del=max(-del,nPlay); end
nPlay=nPlay-del; if(~replay), curInd=curInd+del; end
if(del==0), drawnow(); continue; end
end
% update display if necessary
k=k+1; if(0 && ~needUpdate), fprintf('%i draw events.\n',k); end
if( ~needUpdate ), looping=0; return; end
updateDisp(); filesApi.backupAnn(); drawnow();
end
end
function updateDisp()
% delete old objects
delete(hObjCur); hObjCur=[];
% possibly switch display modes
if( dispMode~=0 && nPlay==0 )
needUpdate=1; dispMode=0; replay=0;
elseif( abs(dispMode)==1 )
needUpdate=1; dispMode=dispMode*2;
if(dispMode<0), hImMsk=hImRt; else hImMsk=hImLf; end
I=get(hImMsk,'CData'); I(:)=100; set(hImMsk,'CData',I);
I=get(hImSeq,'CData'); I(:)=100; set(hImSeq,'CData',I);
objApi.prepPlay();
else
needUpdate=0;
end
if(dispMode==0), seqI = objApi.prepSeq(); end
% display left panel
if( dispMode<=0 )
set( hFig, 'CurrentAxes', pLf.hAx );
ind=curInd; if(replay), ind=ind-nPlay; end
hImLf = imageFast( hImLf, getImg(ind) );
set( pLf.hFrInd, 'String', int2str(ind+1) );
hObjCur=[hObjCur objApi.drawRects('panelLf',ind)];
end
% display right panel
if( dispMode>=0 )
set( hFig, 'CurrentAxes', pRt.hAx );
ind=curInd+offset*skip; if(replay), ind=ind-nPlay; end
hImRt = imageFast( hImRt, getImg(ind) );
set( pRt.hFrInd, 'String', int2str(ind+1) );
hObjCur=[hObjCur objApi.drawRects('panelRt',ind)];
end
% display seq panel
if( dispMode==0 )
set( hFig, 'CurrentAxes', pSeq.hAx );
hImSeq = imageFast( hImSeq, seqI );
hObjCur=[hObjCur objApi.drawRects('objSeq',[])];
end
% adjust play controls
set( pLf.btnRep, 'Enable', enStr{(curInd>0)+1} );
set( pLf.btn(1:2), 'Enable', enStr{(curInd>0)+1} );
set( pLf.btn(4:5), 'Enable', enStr{(offset*skip<nFrameRt())+1});
function hImg = imageFast( hImg, I )
if(isempty(hImg)), hImg=image(I); axis off; else
set(hImg,'CData',I); end
end
end
function pos = newRect( lims, rp )
% get new rectangle, extract pos (disable controls temporarily)
hs=[pObj.hCn pLf.hCn pRt.hCn pMenu.hCn];
en=get(hs,'Enable'); set(hs,'Enable','off');
[hR,api]=imRectRot('hParent',pLf.hAx,'lims',lims,rp{:});
hObjCur=[hObjCur hR]; pos=api.getPos(); pos=pos(1:4);
for i=1:length(hs); set(hs(i),'Enable',en{i}); end
requestUpdate();
end
function requestUpdate( clearHs )
if(nargin==0 || isempty(clearHs)), clearHs=0; end
if(clearHs), [hImLf, hImRt, hImSeq]=deal([]); end
needUpdate=true; dispLoop();
end
function setSkip( skip1 )
if(nargin==0), skip1=round(str2double(get(pRt.edSkip,'String'))); end
if(~isnan(skip1)), skip=max(1,min(skip1,maxSkip)); end
if(nFrame>0), skip=min(skip,floor(nFrameRt()/offset)); end
set( pRt.stSkip, 'String', 'zoom: 1 / ');
set( pRt.edSkip, 'String', int2str(skip) );
set( pRt.stOffst,'String', ['+' int2str(offset*skip)] );
setPlay(0);
end
function setOffset( offset1 )
if( nargin==1 ), offset=offset1; else
offset=round(get(pRt.slOffst,'Value')); end
if(nFrame>0), offset=min(offset,floor(nFrameRt()/skip)); end
set( pRt.slOffst, 'Value', offset );
set( pRt.stOffst, 'String', ['+' int2str(offset*skip)] );
setPlay(0);
end
function setFrame( f )
if(nargin==0), f=round(str2double(get(pLf.hFrInd,'String'))); end
if(strcmp(f,'-')), f=curInd-skip+1; end
if(strcmp(f,'+')), f=curInd+skip+1; end
if(strcmp(f,'go')), f=curInd+skip*offset+1; end
if(~isnan(f)), curInd=max(0,min(f-1,nFrame-skip*offset-1)); end
set(pLf.hFrInd,'String',int2str(curInd+1)); setPlay(0);
end
function setPlay( type )
switch type
case 'replayLf'
nPlay=min(curInd,repLen*info.fps);
dispMode=-1; replay=1;
case 'replayRt'
nPlay=min(skip*offset,nFrameRt());
dispMode=1; replay=1;
otherwise
nPlay=type; dispMode=-1; replay=0;
if(nPlay<0), nPlay=max(nPlay,-curInd); end
if(nPlay>0), nPlay=min(nPlay,nFrameRt-offset*skip); end
end
t=clock(); t=t(6)+60*t(5); timeDisp=t; requestUpdate();
end
function setFps( fps )
if(nargin==0), fps=round(str2double(get(pLf.fpsInd,'String'))); end
if(isnan(fps)), fps=info.fps; else fps=max(1,min(fps,99999)); end
set(pLf.fpsInd,'String',int2str(fps)); info.fps=fps; setPlay(0);
end
function I=getImg(f)
sr.seek(f); I=sr.getframe(); if(ismatrix(I)), I=I(:,:,[1 1 1]); end
end
function w=width(), w=info.width; end
function h=height(), h=info.height; end
function n=nFrame(), n=info.numFrames; end
function n=nFrameRt(), n=nFrame-1-curInd; end
end
function api = filesMakeApi()
% variables
[fVid, fAnn, tSave, tSave1] = deal([]);
% callbacks
set( pMenu.hVidOpn, 'Callback', @(h,e) openVid() );
set( pMenu.hVidCls, 'Callback', @(h,e) closeVid() );
set( pMenu.hAnnNew, 'Callback', @(h,e) newAnn() );
set( pMenu.hAnnOpn, 'Callback', @(h,e) openAnn() );
set( pMenu.hAnnSav, 'Callback', @(h,e) saveAnn() );
set( pMenu.hAnnCls, 'Callback', @(h,e) closeAnn() );
% create api
api = struct('closeVid',@closeVid, 'backupAnn',@backupAnn, ...
'openVid',@openVid, 'openAnn',@openAnn );
function updateMenus()
m=pMenu; en=enStr{~isempty(fVid)+1}; nm='VBB Labeler';
set([m.hVidCls m.hAnnNew m.hAnnOpn],'Enable',en);
en=enStr{~isempty(fAnn)+1}; set([m.hAnnSav m.hAnnCls],'Enable',en);
if(~isempty(fVid)), [~,nm1]=fileparts(fVid); nm=[nm ' - ' nm1]; end
set(hFig,'Name',nm); objApi.init(); dispApi.requestUpdate();
end
function closeVid()
fVid=[]; if(~isempty(fAnn)), closeAnn(); end
dispApi.init([]); updateMenus();
end
function openVid( f )
if( nargin>0 )
[d,f]=fileparts(f); if(isempty(d)), d='.'; end;
d=[d '/']; f=[f '.seq'];
else
if(isempty(fVid)), d='.'; else d=fileparts(fVid); end
[f,d]=uigetfile('*.seq','Select video',[d '/*.seq']);
end
if( f==0 ), return; end; closeVid(); fVid=[d f];
try
s=0; sr=seqIo(fVid,'r',maxCache); s=1;
dispApi.init(sr); updateMenus();
catch er
errordlg(['Failed to load: ' fVid '. ' er.message],'Error');
if(s); closeVid(); end; return;
end
end
function closeAnn()
assert(~isempty(fAnn)); A1=objApi.annForSave();
if( ~isempty(A1) && A1.altered )
qstr = 'Save Current Annotation?';
button = questdlg(qstr,'Exiting','yes','no','yes');
if(strcmp(button,'yes')); saveAnn(); end
end
A=[]; [fAnn,tSave,tSave1]=deal([]); updateMenus();
end
function openAnn( f )
assert(~isempty(fVid)); if(~isempty(fAnn)), closeAnn(); end
if( nargin>0 )
[d,f,e]=fileparts(f); if(isempty(d)), d='.'; end; d=[d '/'];
if(isempty(e) && exist([d f '.txt'],'file')), e='.txt'; end
if(isempty(e) && exist([d f '.vbb'],'file')), e='.vbb'; end
f=[f e];
else
[f,d]=uigetfile('*.vbb;*.txt','Select Annotation',fVid(1:end-4));
end
if( f==0 ), return; end; fAnn=[d f];
try
if(~exist(fAnn,'file'))
A=vbb('init',dispApi.nFrame()); vbb('vbbSave',A,fAnn);
else
A=vbb( 'vbbLoad', fAnn ); eMsg='Annotation/video mismatch.';
if(A.nFrame~=dispApi.nFrame()), error(eMsg); end
end
catch er
errordlg(['Failed to load: ' fAnn '. ' er.message],'Error');
A=[]; fAnn=[]; return;
end
tSave=clock(); tSave1=tSave; updateMenus();
end
function saveAnn()
A1=objApi.annForSave(); if(isempty(A1)), return; end
[f,d]=uiputfile('*.vbb;*.txt','Select Annotation',fAnn);
if( f==0 ), return; end; fAnn=[d f]; tSave=clock; tSave1=tSave;
if(exist(fAnn,'file')), copyfile(fAnn,vbb('vbbName',fAnn,1)); end
vbb('vbbSave',A1,fAnn); objApi.annSaved();
end
function newAnn()
if(~isempty(fAnn)), closeAnn(); end; fAnn=[fVid(1:end-3) 'vbb'];
assert(~isempty(fVid)); A=vbb('init',dispApi.nFrame());
updateMenus();
end
function backupAnn()
if(isempty(tSave) || etime(clock,tSave)<30), return; end
A1=objApi.annForSave(); if(isempty(A1)), return; end
tSave=clock(); timeStmp=etime(tSave,tSave1)>60*5;
if(timeStmp), tSave1=tSave; fAnn1=fAnn; else
fAnn1=[fAnn(1:end-4) '-autobackup' fAnn(end-3:end)]; end
vbb( 'vbbSave', A1, fAnn1, timeStmp );
end
end
end
function api = selectorRange( hParent, pos, n, col0, col1 )
% Graphical way of selecting ranges from the sequence {1,2,...,n}.
%
% The result of the selection is an n element vector rng in {0,1}^n that
% indicates whether each element is selected (or in the terminology below
% ON/OFF). Particularly efficient if the ON cells in the resulting rng can
% be grouped into a few continguous blocks.
%
% Creates n individual cells, 1 per element. Each cell is either OFF/ON,
% denoted by colors col0/col1. Each cell can be clicked in three discrete
% locations: LEFT/MID/RIGHT: (1) Clicking a cell in the MID location
% toggles it ON/OFF. (2) Clicking an ON cell i turns a number of cells OFF,
% determined in the following manner. Let [lf,rt] denote the contiguous
% block of ON cells containing i. Clicking on the LEFT of cell i shrinks
% the contiguous block of ON cells to [i,rt] (ie cells [lf,i-1] are truned
% OFF). Clicking on the RIGHT of cell i shrinks the contiguous block to
% [lf,i] (ie cells [i+1,rt] are truned OFF). (3) In a similar manner
% clicking an OFF cell i turns a number of cells ON. Clicking on the LEFT
% extends the closest contiguous block to the right of i, [lf,rt], to
% [i,rt]. Clicking on the RIGHT extends the closest contiguous block the
% the left of i, [lf,rt], to [lf,i]. To better understand the interface
% simply run the example below.
%
% Locks can be set to limit how the range can change. If setLockCen(1) is
% set, the user cannot toggle individual element by clicking the MIDDLE
% location (this prevents contiguous blocks from being split). setLockLf/Rt
% can be used to ensure the overall range [lf*,rt*], where lf*=min(rng) and
% rt*=max(rng) cannot change in certain ways (see below). Also use enable()
% to enable only portion of cells for interaction.
%
% USAGE
% api = selectorRange( hParent, pos, n, [col0], [col1] )
%
% INPUTS
% hParent - object parent, either a figure or a uipanel
% pos - guis pos vector [xMin yMin width height]
% n - sequence size
% col0 - [.7 .7 .7] 1x3 array: color for OFF cells
% col1 - [.7 .9 1] 1x3 array: color for ON cells
%
% OUTPUTS
% api - interface allowing access to created gui object
% .delete() - use to delete obj, syntax is 'api.delete()'
% .enable(en) - enable given range (or 0/1 to enable/disable all)
% .setPos(pos) - set position of range selector in the figure
% .getRng() - get range: returns n elt range vector in {0,1}^n
% .setRng(rng) - set range to specified rng (n elmt vector)
% .getBnds([rng]) - get left-most/right-most (lf,rt) bounds of range
% .setRngChnCb(f) - whenever range changes, calls f(rngOld,rngNew)
% .setLockCen(v) - 0/1 enables toggling individual elements
% .setLockLf(v) - []:none; 0:locked; -1: only shrink; +1: only ext
% .setLockRt(v) - []:none; 0:locked; -1: only shrink; +1: only ext
%
% EXAMPLE
% h=figure(1); clf; pos=[10 20 500 15]; n=10;
% api = selectorRange( h, pos, n );
% rng=zeros(1,n); rng(3:7)=1; api.setRng( rng );
% f = @(rO,rN) disp(['new range= ' int2str(rN)]);
% api.setRngChnCb( f );
%
% See also imRectRot, uicontrol
narginchk(3,5);
if(nargin<4 || isempty(col0)), col0=[.7 .7 .7]; end
if(nargin<5 || isempty(col1)), col1=[.7 .9 1]; end
% globals (n, col0, col1 are implicit globals)
lockLf=-2; lockRt=-2; lockCen=0; en=1;
[Is,hAx,hImg,rangeChnCb,rng]=deal([]);
% set initial position
rng=ones(1,n); setPos( pos );
% create api
api = struct('delete',@delete1, 'enable',@enable, 'setPos',@setPos, ...
'getRng',@getRng, 'setRng',@setRng, 'getBnds',@getBnds, ...
'setRngChnCb',@setRngChnCb, 'setLockCen',@(v) setLock(v,0), ...
'setLockLf',@(v) setLock(v,-1), 'setLockRt',@(v) setLock(v,1) );
function setPos( pos )
% create images for virtual buttons (Is = h x w x rgb x enable)
w=max(3,round(pos(3)/n)); wSid=floor(w/3); wMid=w-wSid*2;
h=max(4,round(pos(4))); cols=permute([col0; col1],[1 3 2]);
IsSid=zeros(h-2,wSid,3,2); IsMid=zeros(h-2,wMid,3,2);
for i=1:2, IsSid(:,:,:,i)=repmat(cols(i,:,:),[h-2 wSid 1]); end
for i=1:2, IsMid(:,:,:,i)=repmat(cols(i,:,:),[h-2 wMid 1]); end
IsSid(:,1,:,:)=0; Is=[IsSid IsMid IsSid(:,end:-1:1,:,:)];
Is=padarray(Is,[1 0 0 0],mean(col0)*.8,'both'); pos(3)=w*n;
% create new axes and image objects
delete1(); units=get(hParent,'units'); set(hParent,'Units','pixels');
hAx=axes('Parent',hParent,'Units','pixels','Position',pos);
hImg=image(zeros(h,w*n)); axis off; set(hParent,'Units',units);
set(hImg,'ButtonDownFcn',@(h,e) btnPressed()); draw();
end
function btnPressed()
if(length(en)==1 && en==0), return; end
x=get(hAx,'CurrentPoint'); w=size(Is,2);
x=ceil(min(1,max(eps,x(1)/w/n))*3*n);
btnId=ceil(x/3); btnPos=x-btnId*3+1;
assert( btnId>=1 && btnId<=n && btnPos>=-1 && btnPos<=1 );
if(length(en)==2 && (btnId<en(1) || btnId>en(2))), return; end
% compute what contiguous block of cells to alter
if( btnPos==0 ) % toggle center
if( lockCen ), return; end
s=btnId; e=btnId; v=~rng(btnId);
elseif( btnPos==-1 && ~rng(btnId) )
rt = find(rng(btnId+1:end)) + btnId;
if(isempty(rt)), return; else rt=rt(1); end
s=btnId; e=rt-1; v=1; %extend to left
elseif( btnPos==1 && ~rng(btnId) )
lf = btnId - find(fliplr(rng(1:btnId-1)));
if(isempty(lf)), return; else lf=lf(1); end
s=lf+1; e=btnId; v=1; %extend to right
elseif( btnPos==-1 && rng(btnId) )
if(btnId==1 || ~rng(btnId-1)), return; end
lf=btnId-find([fliplr(rng(1:btnId-1)==0) 1])+1; lf=lf(1);
s=lf; e=btnId-1; v=0; %shrink to right
elseif( btnPos==1 && rng(btnId) )
if(btnId==n || ~rng(btnId+1)), return; end
rt = find([rng(btnId+1:end)==0 1]) + btnId - 1; rt=rt(1);
s=btnId+1; e=rt; v=0; %shrink to left
end
assert( all(rng(s:e)~=v) );
% apply locks preventing extension/shrinking beyond endpoints
[lf,rt] = getBnds();
if( lf==-1 && (any(lockLf==[0 -1])||any(lockRt==[0 -1]))), return; end
if( v==1 && e<lf && any(lockLf==[0 -1]) ), return; end
if( v==1 && s>rt && any(lockRt==[0 -1]) ), return; end
if( v==0 && s==lf && any(lockLf==[0 1]) ), return; end
if( v==0 && e==rt && any(lockRt==[0 1]) ), return; end
% update rng, redraw and callback
rng0=rng; rng(s:e)=v; draw();
if(~isempty(rangeChnCb)), rangeChnCb(rng0,rng); end
end
function draw()
% construct I based on hRng and set image
h=size(Is,1); w=size(Is,2); I=zeros(h,w*n,3);
if(length(en)>1 || en==1), rng1=rng; else rng1=zeros(1,n); end
for i=1:n, I(:,(1:w)+(i-1)*w,:)=Is(:,:,:,rng1(i)+1); end
if(ishandle(hImg)), set(hImg,'CData',I); end
end
function setRng( rng1 )
assert( length(rng1)==n && all(rng1==0 | rng1==1) );
if(any(rng~=rng1)), rng=rng1; draw(); end
end
function [lf,rt] = getBnds( rng1 )
if(nargin==0 || isempty(rng1)); rng1=rng; end
[~,lf]=max(rng1); [v,rt]=max(fliplr(rng1)); rt=n-rt+1;
if(v==0); lf=-1; rt=-1; end;
end
function setLock( v, flag )
if( flag==0 ), lockCen = v; else
if(isempty(v)), v=-2; end
assert( any(v==[-2 -1 0 1]) );
if(flag==1), lockRt=v; else lockLf=v; end
end
end
function delete1()
if(ishandle(hAx)), delete(hAx); end; hAx=[];
if(ishandle(hImg)), delete(hImg); end; hImg=[];
end
function enable( en1 ), en=en1; draw(); end
function setRngChnCb( f ), rangeChnCb = f; end
end
|
github | garrickbrazil/SDS-RCNN-master | dbEval.m | .m | SDS-RCNN-master/external/caltech_toolbox/dbEval.m | 20,334 | utf_8 | ed18d84be7b0e43ce99c1ccd2fb9bc08 | function dbEval
% Evaluate and plot all pedestrian detection results.
%
% Set parameters by altering this function directly.
%
% USAGE
% dbEval
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
% dbEval
%
% See also bbGt, dbInfo
%
% Caltech Pedestrian Dataset Version 3.2.1
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% List of experiment settings: { name, hr, vr, ar, overlap, filter }
% name - experiment name
% hr - height range to test
% vr - visibility range to test
% ar - aspect ratio range to test
% overlap - overlap threshold for evaluation
% filter - expanded filtering (see 3.3 in PAMI11)
exps = {
'Reasonable', [50 inf], [.65 inf], 0, .5, 1.25
'All', [20 inf], [.2 inf], 0, .5, 1.25
'Scale=large', [100 inf], [inf inf], 0, .5, 1.25
'Scale=near', [80 inf], [inf inf], 0, .5, 1.25
'Scale=medium', [30 80], [inf inf], 0, .5, 1.25
'Scale=far', [20 30], [inf inf], 0, .5, 1.25
'Occ=none', [50 inf], [inf inf], 0, .5, 1.25
'Occ=partial', [50 inf], [.65 1], 0, .5, 1.25
'Occ=heavy', [50 inf], [.2 .65], 0, .5, 1.25
'Ar=all', [50 inf], [inf inf], 0, .5, 1.25
'Ar=typical', [50 inf], [inf inf], .1, .5, 1.25
'Ar=atypical', [50 inf], [inf inf], -.1, .5, 1.25
'Overlap=25', [50 inf], [.65 inf], 0, .25, 1.25
'Overlap=50', [50 inf], [.65 inf], 0, .50, 1.25
'Overlap=75', [50 inf], [.65 inf], 0, .75, 1.25
'Expand=100', [50 inf], [.65 inf], 0, .5, 1.00
'Expand=125', [50 inf], [.65 inf], 0, .5, 1.25
'Expand=150', [50 inf], [.65 inf], 0, .5, 1.50 };
exps=cell2struct(exps',{'name','hr','vr','ar','overlap','filter'});
% List of algorithms: { name, resize, color, style }
% name - algorithm name (defines data location)
% resize - if true rescale height of each box by 100/128
% color - algorithm plot color
% style - algorithm plot linestyle
n=1000; clrs=zeros(n,3);
for i=1:n, clrs(i,:)=max(.3,mod([78 121 42]*(i+1),255)/255); end
algs = {
'VJ', 0, clrs(1,:), '-'
'HOG', 1, clrs(2,:), '--'
'FtrMine', 1, clrs(3,:), '-'
'Shapelet', 0, clrs(4,:), '--'
'PoseInv', 1, clrs(5,:), '-'
'MultiFtr', 0, clrs(6,:), '--'
'MultiFtr+CSS', 0, clrs(7,:), '-'
'MultiFtr+Motion', 0, clrs(8,:), '--'
'HikSvm', 1, clrs(9,:), '-'
'Pls', 0, clrs(10,:), '--'
'HogLbp', 0, clrs(11,:), '-'
'LatSvm-V1', 0, clrs(12,:), '--'
'LatSvm-V2', 0, clrs(13,:), '-'
'ChnFtrs', 0, clrs(14,:), '--'
'FPDW', 0, clrs(15,:), '-'
'FeatSynth', 0, clrs(16,:), '--'
'MultiResC', 0, clrs(17,:), '-'
'CrossTalk', 0, clrs(18,:), '--'
'VeryFast', 0, clrs(19,:), '-'
'ConvNet', 0, clrs(20,:), '--'
'SketchTokens', 0, clrs(21,:), '-'
'Roerei', 0, clrs(22,:), '--'
'AFS', 1, clrs(23,:), '-'
'AFS+Geo', 1, clrs(23,:), '--'
'MLS', 1, clrs(24,:), '-'
'MT-DPM', 0, clrs(25,:), '-'
'MT-DPM+Context', 0, clrs(25,:), '--'
'DBN-Isol', 0, clrs(26,:), '-'
'DBN-Mut', 0, clrs(26,:), '--'
'MF+Motion+2Ped', 0, clrs(27,:), '-'
'MultiResC+2Ped', 0, clrs(27,:), '--'
'MOCO', 0, clrs(28,:), '-'
'ACF', 0, clrs(29,:), '-'
'ACF-Caltech', 0, clrs(29,:), '--'
'ACF+SDt', 0, clrs(30,:), '-'
'FisherBoost', 0, clrs(31,:), '--'
'pAUCBoost', 0, clrs(32,:), '-'
'Franken', 0, clrs(33,:), '--'
'JointDeep', 0, clrs(34,:), '-'
'MultiSDP', 0, clrs(35,:), '--'
'SDN', 0, clrs(36,:), '-'
'RandForest', 0, clrs(37,:), '--'
'WordChannels', 0, clrs(38,:), '-'
'InformedHaar', 0, clrs(39,:), '--'
'SpatialPooling', 0, clrs(40,:), '-'
'SpatialPooling+', 0, clrs(42,:), '--'
'LDCF', 0, clrs(43,:), '-'
'ACF-Caltech+', 0, clrs(44,:), '--'
'Katamari', 0, clrs(45,:), '-'
'NAMC', 0, clrs(46,:), '--'
'FastCF', 0, clrs(47,:), '-'
'TA-CNN', 0, clrs(48,:), '--'
'SCCPriors', 0, clrs(49,:), '-'
'DeepParts', 0, clrs(50,:), '--'
'DeepCascade', 0, clrs(51,:), '-'
'DeepCascade+', 0, clrs(51,:), '--'
'LFOV', 0, clrs(52,:), '-'
'Checkerboards', 0, clrs(53,:), '--'
'Checkerboards+', 0, clrs(53,:), '-'
'CCF', 0, clrs(54,:), '--'
'CCF+CF', 0, clrs(54,:), '-'
'CompACT-Deep', 0, clrs(55,:), '--'
'SCF+AlexNet', 0, clrs(56,:), '-'
'SA-FastRCNN', 0, clrs(57,:), '--'
'RPN+BF', 0, clrs(58,:), '-'
'MS-CNN', 0, clrs(59,:), '--'
'ACF++', 0, clrs(60,:), '-'
'LDCF++', 0, clrs(61,:), '--'
'MRFC+Semantic', 0, clrs(63,:), '--'
'F-DNN', 0, clrs(64,:), '-'
'F-DNN+SS', 0, clrs(65,:), '--' };
algs=cell2struct(algs',{'name','resize','color','style'});
% List of database names
dataNames = {'UsaTest','UsaTrain','InriaTest',...
'TudBrussels','ETH','Daimler','Japan'};
% select databases, experiments and algorithms for evaluation
dataNames = dataNames(1); % select one or more databases for evaluation
exps = exps(1); % select one or more experiment for evaluation
algs = algs(:); % select one or more algorithms for evaluation
% remaining parameters and constants
aspectRatio = .41; % default aspect ratio for all bbs
bnds = [5 5 635 475]; % discard bbs outside this pixel range
plotRoc = 1; % if true plot ROC else PR curves
plotAlg = 0; % if true one plot per alg else one plot per exp
plotNum = 15; % only show best plotNum curves (and VJ and HOG)
samples = 10.^(-2:.25:0); % samples for computing area under the curve
lims = [2e-4 50 .035 1]; % axis limits for ROC plots
bbsShow = 0; % if true displays sample bbs for each alg/exp
bbsType = 'fp'; % type of bbs to display (fp/tp/fn/dt)
algs0=algs; bnds0=bnds;
for d=1:length(dataNames), dataName=dataNames{d};
% select algorithms with results for current dataset
[~,set]=dbInfo(dataName); set=['/set' int2str2(set(1),2)];
names={algs0.name}; n=length(names); keep=false(1,n);
for i=1:n, keep(i)=exist([dbInfo '/res/' names{i} set],'dir'); end
algs=algs0(keep);
% handle special database specific cases
if(any(strcmp(dataName,{'InriaTest','TudBrussels','ETH'})))
bnds=[-inf -inf inf inf]; else bnds=bnds0; end
if(strcmp(dataName,'InriaTest'))
i=find(strcmp({algs.name},'FeatSynth'));
if(~isempty(i)), algs(i).resize=1; end;
end
% name for all plots (and also temp directory for results)
plotName=[fileparts(mfilename('fullpath')) '/results/' dataName];
if(~exist(plotName,'dir')), mkdir(plotName); end
% load detections and ground truth and evaluate
dts = loadDt( algs, plotName, aspectRatio );
gts = loadGt( exps, plotName, aspectRatio, bnds );
res = evalAlgs( plotName, algs, exps, gts, dts );
% plot curves and bbs
plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, reshape([algs.color]',3,[])', {algs.style} );
plotBbs( res, plotName, bbsShow, bbsType );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = evalAlgs( plotName, algs, exps, gts, dts )
% Evaluate every algorithm on each experiment
%
% OUTPUTS
% res - nGt x nDt cell of all evaluations, each with fields
% .stra - string identifying algorithm
% .stre - string identifying experiment
% .gtr - [n x 1] gt result bbs for each frame [x y w h match]
% .dtr - [n x 1] dt result bbs for each frame [x y w h score match]
fprintf('Evaluating: %s\n',plotName); nGt=length(gts); nDt=length(dts);
res=repmat(struct('stra',[],'stre',[],'gtr',[],'dtr',[]),nGt,nDt);
for g=1:nGt
for d=1:nDt
gt=gts{g}; dt=dts{d}; n=length(gt); assert(length(dt)==n);
stra=algs(d).name; stre=exps(g).name;
fName = [plotName '/ev-' [stre '-' stra] '.mat'];
if(exist(fName,'file')), R=load(fName); res(g,d)=R.R; continue; end
fprintf('\tExp %i/%i, Alg %i/%i: %s/%s\n',g,nGt,d,nDt,stre,stra);
hr = exps(g).hr.*[1/exps(g).filter exps(g).filter];
for f=1:n, bb=dt{f}; dt{f}=bb(bb(:,4)>=hr(1) & bb(:,4)<hr(2),:); end
[gtr,dtr] = bbGt('evalRes',gt,dt,exps(g).overlap);
R=struct('stra',stra,'stre',stre,'gtr',{gtr},'dtr',{dtr});
res(g,d)=R; save(fName,'R');
end
end
end
function plotExps( res, plotRoc, plotAlg, plotNum, plotName, ...
samples, lims, colors, styles )
% Plot all ROC or PR curves.
%
% INPUTS
% res - output of evalAlgs
% plotRoc - if true plot ROC else PR curves
% plotAlg - if true one plot per alg else one plot per exp
% plotNum - only show best plotNum curves (and VJ and HOG)
% plotName - filename for saving plots
% samples - samples for computing area under the curve
% lims - axis limits for ROC plots
% colors - algorithm plot colors
% styles - algorithm plot linestyles
% Compute (xs,ys) and score (area under the curve) for every exp/alg
[nGt,nDt]=size(res); xs=cell(nGt,nDt); ys=xs; scores=zeros(nGt,nDt);
for g=1:nGt
for d=1:nDt
[xs{g,d},ys{g,d},~,score] = ...
bbGt('compRoc',res(g,d).gtr,res(g,d).dtr,plotRoc,samples);
if(plotRoc), ys{g,d}=1-ys{g,d}; score=1-score; end
if(plotRoc), score=exp(mean(log(score))); else score=mean(score); end
scores(g,d)=score;
end
end
% Generate plots
if( plotRoc ), fName=[plotName 'Roc']; else fName=[plotName 'Pr']; end
stra={res(1,:).stra}; stre={res(:,1).stre}; scores1=round(scores*100);
if( plotAlg ), nPlots=nDt; else nPlots=nGt; end; plotNum=min(plotNum,nDt);
for p=1:nPlots
% prepare xs1,ys1,lgd1,colors1,styles1,fName1 according to plot type
if( plotAlg )
xs1=xs(:,p); ys1=ys(:,p); fName1=[fName stra{p}]; lgd1=stre;
for g=1:nGt, lgd1{g}=sprintf('%2i%% %s',scores1(g,p),stre{g}); end
colors1=uniqueColors(1,max(10,nGt)); styles1=repmat({'-','--'},1,nGt);
else
xs1=xs(p,:); ys1=ys(p,:); fName1=[fName stre{p}]; lgd1=stra;
for d=1:nDt, lgd1{d}=sprintf('%2i%% %s',scores1(p,d),stra{d}); end
kp=[find(strcmp(stra,'VJ')) find(strcmp(stra,'HOG')) 1 1];
[~,ord]=sort(scores(p,:)); kp=ord==kp(1)|ord==kp(2);
j=find(cumsum(~kp)>=plotNum-2); kp(1:j(1))=1; ord=fliplr(ord(kp));
xs1=xs1(ord); ys1=ys1(ord); lgd1=lgd1(ord); colors1=colors(ord,:);
styles1=styles(ord); f=fopen([fName1 '.txt'],'w');
for d=1:nDt, fprintf(f,'%s %f\n',stra{d},scores(p,d)); end; fclose(f);
end
% plot curves and finalize display
figure(1); clf; grid on; hold on; n=length(xs1); h=zeros(1,n);
for i=1:n, h(i)=plot(xs1{i},ys1{i},'Color',colors1(i,:),...
'LineStyle',styles1{i},'LineWidth',2); end
if( plotRoc )
yt=[.05 .1:.1:.5 .64 .8]; ytStr=int2str2(yt*100,2);
for i=1:length(yt), ytStr{i}=['.' ytStr{i}]; end
set(gca,'XScale','log','YScale','log',...
'YTick',[yt 1],'YTickLabel',[ytStr '1'],...
'XMinorGrid','off','XMinorTic','off',...
'YMinorGrid','off','YMinorTic','off');
xlabel('false positives per image','FontSize',14);
ylabel('miss rate','FontSize',14); axis(lims);
else
x=1; for i=1:n, x=max(x,max(xs1{i})); end, x=min(x-mod(x,.1),1.0);
y=.8; for i=1:n, y=min(y,min(ys1{i})); end, y=max(y-mod(y,.1),.01);
xlim([0, x]); ylim([y, 1]); set(gca,'xtick',0:.1:1);
xlabel('Recall','FontSize',14); ylabel('Precision','FontSize',14);
end
if(~isempty(lgd1)), legend(h,lgd1,'Location','sw','FontSize',10); end
% save figure to disk (uncomment pdfcrop commands to automatically crop)
[o,~]=system('pdfcrop'); if(o==127), setenv('PATH',...
[getenv('PATH') ':/Library/TeX/texbin/:/usr/local/bin/']); end
savefig(fName1,1,'pdf','-r300','-fonts'); close(1); f1=[fName1 '.pdf'];
system(['pdfcrop -margins ''-30 -20 -50 -10 '' ' f1 ' ' f1]);
end
end
function plotBbs( res, plotName, pPage, type )
% This function plots sample fp/tp/fn bbs for given algs/exps
if(pPage==0), return; end; [nGt,nDt]=size(res);
% construct set/vid/frame index for each image
[~,setIds,vidIds,skip]=dbInfo;
k=length(res(1).gtr); is=zeros(k,3); k=0;
for s=1:length(setIds)
for v=1:length(vidIds{s})
A=loadVbb(s,v); s1=setIds(s); v1=vidIds{s}(v);
for f=skip-1:skip:A.nFrame-1, k=k+1; is(k,:)=[s1 v1 f]; end
end
end
for g=1:nGt
for d=1:nDt
% augment each bb with set/video/frame index and flatten
dtr=res(g,d).dtr; gtr=res(g,d).gtr;
for i=1:k
dtr{i}(:,7)=is(i,1); dtr{i}(:,8)=is(i,2); dtr{i}(:,9)=is(i,3);
gtr{i}(:,6)=is(i,1); gtr{i}(:,7)=is(i,2); gtr{i}(:,8)=is(i,3);
dtr{i}=dtr{i}'; gtr{i}=gtr{i}';
end
dtr=[dtr{:}]'; dtr=dtr(dtr(:,6)~=-1,:);
gtr=[gtr{:}]'; gtr=gtr(gtr(:,5)~=-1,:);
% get bb, ind, bbo, and indo according to type
if( strcmp(type,'fn') )
keep=gtr(:,5)==0; ord=randperm(sum(keep));
bbCol='r'; bboCol='y'; bbLst='-'; bboLst='--';
bb=gtr(:,1:4); ind=gtr(:,6:8); bbo=dtr(:,1:6); indo=dtr(:,7:9);
else
switch type
case 'dt', bbCol='y'; keep=dtr(:,6)>=0;
case 'fp', bbCol='r'; keep=dtr(:,6)==0;
case 'tp', bbCol='y'; keep=dtr(:,6)==1;
end
[~,ord]=sort(dtr(keep,5),'descend');
bboCol='g'; bbLst='--'; bboLst='-';
bb=dtr(:,1:6); ind=dtr(:,7:9); bbo=gtr(:,1:4); indo=gtr(:,6:8);
end
% prepare and display
n=sum(keep); bbo1=cell(1,n); O=ones(1,size(indo,1));
ind=ind(keep,:); bb=bb(keep,:); ind=ind(ord,:); bb=bb(ord,:);
for f=1:n, bbo1{f}=bbo(all(indo==ind(O*f,:),2),:); end
f=[plotName res(g,d).stre res(g,d).stra '-' type];
plotBbSheet( bb, ind, bbo1,'fName',f,'pPage',pPage,'bbCol',bbCol,...
'bbLst',bbLst,'bboCol',bboCol,'bboLst',bboLst );
end
end
end
function plotBbSheet( bb, ind, bbo, varargin )
% Draw sheet of bbs.
%
% USAGE
% plotBbSheet( R, varargin )
%
% INPUTS
% bb - [nx4] bbs to display
% ind - [nx3] the set/video/image number for each bb
% bbo - {nx1} cell of other bbs for each image (optional)
% varargin - prm struct or name/value list w following fields:
% .fName - ['REQ'] base file to save to
% .pPage - [1] num pages
% .mRows - [5] num rows / page
% .nCols - [9] num cols / page
% .scale - [2] size of image region to crop relative to bb
% .siz0 - [100 50] target size of each bb
% .pad - [4] amount of space between cells
% .bbCol - ['g'] bb color
% .bbLst - ['-'] bb LineStyle
% .bboCol - ['r'] bbo color
% .bboLst - ['--'] bbo LineStyle
dfs={'fName','REQ', 'pPage',1, 'mRows',5, 'nCols',9, 'scale',1.5, ...
'siz0',[100 50], 'pad',8, 'bbCol','g', 'bbLst','-', ...
'bboCol','r', 'bboLst','--' };
[fName,pPage,mRows,nCols,scale,siz0,pad,bbCol,bbLst, ...
bboCol,bboLst] = getPrmDflt(varargin,dfs);
n=size(ind,1); indAll=ind; bbAll=bb; bboAll=bbo;
for page=1:min(pPage,ceil(n/mRows/nCols))
Is = zeros(siz0(1)*scale,siz0(2)*scale,3,mRows*nCols,'uint8');
bbN=[]; bboN=[]; labels=repmat({''},1,mRows*nCols);
for f=1:mRows*nCols
% get fp bb (bb), double size (bb2), and other bbs (bbo)
f0=f+(page-1)*mRows*nCols; if(f0>n), break, end
[col,row]=ind2sub([nCols mRows],f);
ind=indAll(f0,:); bb=bbAll(f0,:); bbo=bboAll{f0};
hr=siz0(1)/bb(4); wr=siz0(2)/bb(3); mr=min(hr,wr);
bb2 = round(bbApply('resize',bb,scale*hr/mr,scale*wr/mr));
bbo=bbApply('intersect',bbo,bb2); bbo=bbo(bbApply('area',bbo)>0,:);
labels{f}=sprintf('%i/%i/%i',ind(1),ind(2),ind(3));
% normalize bb and bbo for siz0*scale region, then shift
bb=bbApply('shift',bb,bb2(1),bb2(2)); bb(:,1:4)=bb(:,1:4)*mr;
bbo=bbApply('shift',bbo,bb2(1),bb2(2)); bbo(:,1:4)=bbo(:,1:4)*mr;
xdel=-pad*scale-(siz0(2)+pad*2)*scale*(col-1);
ydel=-pad*scale-(siz0(1)+pad*2)*scale*(row-1);
bb=bbApply('shift',bb,xdel,ydel); bbN=[bbN; bb]; %#ok<AGROW>
bbo=bbApply('shift',bbo,xdel,ydel); bboN=[bboN; bbo]; %#ok<AGROW>
% load and crop image region
sr=seqIo(sprintf('%s/videos/set%02i/V%03i',dbInfo,ind(1),ind(2)),'r');
sr.seek(ind(3)); I=sr.getframe(); sr.close();
I=bbApply('crop',I,bb2,'replicate');
I=uint8(imResample(double(I{1}),siz0*scale));
Is(:,:,:,f)=I;
end
% now plot all and save
prm=struct('hasChn',1,'padAmt',pad*2*scale,'padEl',0,'mm',mRows,...
'showLines',0,'labels',{labels});
h=figureResized(.9,1); clf; montage2(Is,prm); hold on;
bbApply('draw',bbN,bbCol,2,bbLst); bbApply('draw',bboN,bboCol,2,bboLst);
savefig([fName int2str2(page-1,2)],h,'png','-r200','-fonts'); close(h);
if(0), save([fName int2str2(page-1,2) '.mat'],'Is'); end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function A = loadVbb( s, v )
% Load given annotation (caches AS for speed).
persistent AS pth sIds vIds; [pth1,sIds1,vIds1]=dbInfo;
if(~strcmp(pth,pth1) || ~isequal(sIds,sIds1) || ~isequal(vIds,vIds1))
[pth,sIds,vIds]=dbInfo; AS=cell(length(sIds),1e3); end
A=AS{s,v}; if(~isempty(A)), return; end
fName=@(s,v) sprintf('%s/annotations/set%02i/V%03i',pth,s,v);
A=vbb('vbbLoad',fName(sIds(s),vIds{s}(v))); AS{s,v}=A;
end
function gts = loadGt( exps, plotName, aspectRatio, bnds )
% Load ground truth of all experiments for all frames.
fprintf('Loading ground truth: %s\n',plotName);
nExp=length(exps); gts=cell(1,nExp);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nExp
gName = [plotName '/gt-' exps(i).name '.mat'];
if(exist(gName,'file')), gt=load(gName); gts{i}=gt.gt; continue; end
fprintf('\tExperiment #%d: %s\n', i, exps(i).name);
gt=cell(1,100000); k=0; lbls={'person','person?','people','ignore'};
filterGt = @(lbl,bb,bbv) filterGtFun(lbl,bb,bbv,...
exps(i).hr,exps(i).vr,exps(i).ar,bnds,aspectRatio);
for s=1:length(setIds)
for v=1:length(vidIds{s})
A = loadVbb(s,v);
for f=skip-1:skip:A.nFrame-1
bb = vbb('frameAnn',A,f+1,lbls,filterGt); ids=bb(:,5)~=1;
bb(ids,:)=bbApply('resize',bb(ids,:),1,0,aspectRatio);
k=k+1; gt{k}=bb;
end
end
end
gt=gt(1:k); gts{i}=gt; save(gName,'gt','-v6');
end
function p = filterGtFun( lbl, bb, bbv, hr, vr, ar, bnds, aspectRatio )
p=strcmp(lbl,'person'); h=bb(4); p=p & (h>=hr(1) & h<hr(2));
if(all(bbv==0)), vf=inf; else vf=bbv(3).*bbv(4)./(bb(3)*bb(4)); end
p=p & vf>=vr(1) & vf<=vr(2);
if(ar~=0), p=p & sign(ar)*abs(bb(3)./bb(4)-aspectRatio)<ar; end
p = p & bb(1)>=bnds(1) & (bb(1)+bb(3)<=bnds(3));
p = p & bb(2)>=bnds(2) & (bb(2)+bb(4)<=bnds(4));
end
end
function dts = loadDt( algs, plotName, aspectRatio )
% Load detections of all algorithm for all frames.
fprintf('Loading detections: %s\n',plotName);
nAlg=length(algs); dts=cell(1,nAlg);
[~,setIds,vidIds,skip] = dbInfo;
for i=1:nAlg
aName = [plotName '/dt-' algs(i).name '.mat'];
if(exist(aName,'file')), dt=load(aName); dts{i}=dt.dt; continue; end
fprintf('\tAlgorithm #%d: %s\n', i, algs(i).name);
dt=cell(1,100000); k=0; aDir=[dbInfo '/res/' algs(i).name];
if(algs(i).resize), resize=100/128; else resize=1; end
for s=1:length(setIds), s1=setIds(s);
for v=1:length(vidIds{s}), v1=vidIds{s}(v);
A=loadVbb(s,v); frames=skip-1:skip:A.nFrame-1;
vName=sprintf('%s/set%02d/V%03d',aDir,s1,v1);
if(~exist([vName '.txt'],'file'))
% consolidate bbs for video into single text file
bbs=cell(length(frames),1);
for f=1:length(frames)
fName = sprintf('%s/I%05d.txt',vName,frames(f));
if(~exist(fName,'file')), error(['file not found:' fName]); end
bb=load(fName,'-ascii'); if(isempty(bb)), bb=zeros(0,5); end
if(size(bb,2)~=5), error('incorrect dimensions'); end
bbs{f}=[ones(size(bb,1),1)*(frames(f)+1) bb];
end
for f=frames, delete(sprintf('%s/I%05d.txt',vName,f)); end
bbs=cell2mat(bbs); dlmwrite([vName '.txt'],bbs); rmdir(vName,'s');
end
bbs=load([vName '.txt'],'-ascii');
for f=frames, bb=bbs(bbs(:,1)==f+1,2:6);
bb=bbApply('resize',bb,resize,0,aspectRatio); k=k+1; dt{k}=bb;
end
end
end
dt=dt(1:k); dts{i}=dt; save(aName,'dt','-v6');
end
end
|
github | garrickbrazil/SDS-RCNN-master | imagesAlign.m | .m | SDS-RCNN-master/external/pdollar_toolbox/videos/imagesAlign.m | 8,167 | utf_8 | d125eb5beb502d940be5bd145521f34b | function [H,Ip] = imagesAlign( I, Iref, varargin )
% Fast and robust estimation of homography relating two images.
%
% The algorithm for image alignment is a simple but effective variant of
% the inverse compositional algorithm. For a thorough overview, see:
% "Lucas-kanade 20 years on A unifying framework,"
% S. Baker and I. Matthews. IJCV 2004.
% The implementation is optimized and can easily run at 20-30 fps.
%
% type may take on the following values:
% 'translation' - translation only
% 'rigid' - translation and rotation
% 'similarity' - translation, rotation and scale
% 'affine' - 6 parameter affine transform
% 'rotation' - pure rotation (about x, y and z)
% 'projective' - full 8 parameter homography
% Alternatively, type may be a vector of ids between 1 and 8, specifying
% exactly the types of transforms allowed. The ids correspond, to: 1:
% translate-x, 2: translate-y, 3: uniform scale, 4: shear, 5: non-uniform
% scale, 6: rotate-z, 7: rotate-x, 8: rotate-y. For example, to specify
% translation use type=[1,2]. If the transforms don't form a group, the
% returned homography may have more degrees of freedom than expected.
%
% Parameters (in rough order of importance): [resample] controls image
% downsampling prior to computing H. Runtime is proportional to area, so
% using resample<1 can dramatically speed up alignment, and in general not
% degrade performance much. [sig] controls image smoothing, sig=2 gives
% good performance, setting sig too low causes loss of information and too
% high will violate the linearity assumption. [epsilon] defines the
% stopping criteria, use to adjust performance versus speed tradeoff.
% [lambda] is a regularization term that causes small transforms to be
% favored, in general any small non-zero setting of lambda works well.
% [outThr] is a threshold beyond which pixels are considered outliers, be
% careful not to set too low. [minArea] determines coarsest scale beyond
% which the image is not downsampled (should not be set too low). [H0] can
% be used to specify an initial alignment. Use [show] to display results.
%
% USAGE
% [H,Ip] = imagesAlign( I, Iref, varargin )
%
% INPUTS
% I - transformed version of I
% Iref - reference grayscale double image
% varargin - additional params (struct or name/value pairs)
% .type - ['projective'] see above for options
% .resample - [1] image resampling prior to homography estimation
% .sig - [2] amount of Gaussian spatial smoothing to apply
% .epsilon - [1e-3] stopping criteria (min change in error)
% .lambda - [1e-6] regularization term favoring small transforms
% .outThr - [inf] outlier threshold
% .minArea - [4096] minimum image area in coarse to fine search
% .H0 - [eye(3)] optional initial homography estimate
% .show - [0] optionally display results in figure show
%
% OUTPUTS
% H - estimated homography to transform I into Iref
% Ip - tranformed version of I (slow to compute)
%
% EXAMPLE
% Iref = double(imread('cameraman.tif'))/255;
% H0 = [eye(2)+randn(2)*.1 randn(2,1)*10; randn(1,2)*1e-3 1];
% I = imtransform2(Iref,H0^-1,'pad','replicate');
% o=50; P=ones(o)*1; I(150:149+o,150:149+o)=P;
% prmAlign={'outThr',.1,'resample',.5,'type',1:8,'show'};
% [H,Ip]=imagesAlign(I,Iref,prmAlign{:},1);
% tic, for i=1:30, H=imagesAlign(I,Iref,prmAlign{:},0); end;
% t=toc; fprintf('average fps: %f\n',30/t)
%
% See also imTransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters
dfs={'type','projective','resample',1,'sig',2,'epsilon',1e-3,...
'lambda',1e-6,'outThr',inf,'minArea',4096,'H0',eye(3),'show',0};
[type,resample,sig,epsilon,lambda,outThr,minArea,H0,show] = ...
getPrmDflt(varargin,dfs,1);
filt = filterGauss(2*ceil(sig*2.5)+1,[],sig^2);
% determine type of transformation to recover
if(isnumeric(type)), assert(length(type)<=8); else
id=find(strcmpi(type,{'translation','rigid','similarity','affine',...
'rotation','projective'})); msgId='piotr:imagesAlign';
if(isempty(id)), error(msgId,'unknown type: %s',type); end
type={1:2,[1:2 6],[1:3 6],1:6,6:8,1:8}; type=type{id};
end; keep=zeros(1,8); keep(type)=1; keep=keep>0;
% compute image alignment (optionally resample first)
prm={keep,filt,epsilon,H0,minArea,outThr,lambda};
if( resample==1 ), H=imagesAlign1(I,Iref,prm); else
S=eye(3); S([1 5])=resample; H0=S*H0*S^-1; prm{4}=H0;
I1=imResample(I,resample); Iref1=imResample(Iref,resample);
H=imagesAlign1(I1,Iref1,prm); H=S^-1*H*S;
end
% optionally rectify I and display results (can be expensive)
if(nargout==1 && show==0), return; end
Ip = imtransform2(I,H,'pad','replicate');
if(show), figure(show); clf; s=@(i) subplot(2,3,i);
Is=[I Iref Ip]; ri=[min(Is(:)) max(Is(:))];
D0=abs(I-Iref); D1=abs(Ip-Iref); Ds=[D0 D1]; di=[min(Ds(:)) max(Ds(:))];
s(1); im(I,ri,0); s(2); im(Iref,ri,0); s(3); im(D0,di,0);
s(4); im(Ip,ri,0); s(5); im(Iref,ri,0); s(6); im(D1,di,0);
s(3); title('|I-Iref|'); s(6); title('|Ip-Iref|');
end
end
function H = imagesAlign1( I, Iref, prm )
% apply recursively if image large
[keep,filt,epsilon,H0,minArea,outThr,lambda]=deal(prm{:});
[h,w]=size(I); hc=mod(h,2); wc=mod(w,2);
if( w*h<minArea ), H=H0; else
I1=imResample(I(1:(h-hc),1:(w-wc)),.5);
Iref1=imResample(Iref(1:(h-hc),1:(w-wc)),.5);
S=eye(3); S([1 5])=2; H0=S^-1*H0*S; prm{4}=H0;
H=imagesAlign1(I1,Iref1,prm); H=S*H*S^-1;
end
% smooth images (pad first so dimensions unchanged)
O=ones(1,(length(filt)-1)/2); hs=[O 1:h h*O]; ws=[O 1:w w*O];
Iref=conv2(conv2(Iref(hs,ws),filt','valid'),filt,'valid');
I=conv2(conv2(I(hs,ws),filt','valid'),filt,'valid');
% pad images with nan so later can determine valid regions
hs=[1 1 1:h h h]; ws=[1 1 1:w w w]; I=I(hs,ws); Iref=Iref(hs,ws);
hs=[1:2 h+3:h+4]; I(hs,:)=nan; Iref(hs,:)=nan;
ws=[1:2 w+3:w+4]; I(:,ws)=nan; Iref(:,ws)=nan;
% convert weights hardcoded for 128x128 image to given image dims
wts=[1 1 1.0204 .03125 1.0313 0.0204 .00055516 .00055516];
s=sqrt(numel(Iref))/128;
wts=[wts(1:2) wts(3)^(1/s) wts(4)/s wts(5)^(1/s) wts(6)/s wts(7:8)/(s*s)];
% prepare subspace around Iref
[~,Hs]=ds2H(-ones(1,8),wts); Hs=Hs(:,:,keep); K=size(Hs,3);
[h,w]=size(Iref); Ts=zeros(h,w,K); k=0;
if(keep(1)), k=k+1; Ts(:,1:end-1,k)=Iref(:,2:end); end
if(keep(2)), k=k+1; Ts(1:end-1,:,k)=Iref(2:end,:); end
pTransf={'method','bilinear','pad','none','useCache'};
for i=k+1:K, Ts(:,:,i)=imtransform2(Iref,Hs(:,:,i),pTransf{:},1); end
Ds=Ts-Iref(:,:,ones(1,K)); Mref = ~any(isnan(Ds),3);
if(0), figure(10); montage2(Ds); end
Ds = reshape(Ds,[],size(Ds,3));
% iteratively project Ip onto subspace, storing transformation
lambda=lambda*w*h*eye(K); ds=zeros(1,8); err=inf;
for i=1:100
s=svd(H); if(s(3)<=1e-4*s(1)), H=eye(3); return; end
Ip=imtransform2(I,H,pTransf{:},0); dI=Ip-Iref; dI0=abs(dI);
M=Mref & ~isnan(Ip); M0=M; if(outThr<inf), M=M & dI0<outThr; end
M1=find(M); D=Ds(M1,:); ds1=(D'*D + lambda)^(-1)*(D'*dI(M1));
if(any(isnan(ds1))), ds1=zeros(K,1); end
ds(keep)=ds1; H1=ds2H(ds,wts); H=H*H1; H=H/H(9);
err0=err; err=dI0; err(~M0)=0; err=mean2(err); del=err0-err;
if(0), fprintf('i=%03i err=%e del=%e\n',i,err,del); end
if( del<epsilon ), break; end
end
end
function [H,Hs] = ds2H( ds, wts )
% compute homography from offsets ds
Hs=eye(3); Hs=Hs(:,:,ones(1,8));
Hs(2,3,1)=wts(1)*ds(1); % 1 x translation
Hs(1,3,2)=wts(2)*ds(2); % 2 y translation
Hs(1:2,1:2,3)=eye(2)*wts(3)^ds(3); % 3 scale
Hs(2,1,4)=wts(4)*ds(4); % 4 shear
Hs(1,1,5)=wts(5)^ds(5); % 5 scale non-uniform
ct=cos(wts(6)*ds(6)); st=sin(wts(6)*ds(6));
Hs(1:2,1:2,6)=[ct -st; st ct]; % 6 rotation about z
ct=cos(wts(7)*ds(7)); st=sin(wts(7)*ds(7));
Hs([1 3],[1 3],7)=[ct -st; st ct]; % 7 rotation about x
ct=cos(wts(8)*ds(8)); st=sin(wts(8)*ds(8));
Hs(2:3,2:3,8)=[ct -st; st ct]; % 8 rotation about y
H=eye(3); for i=1:8, H=Hs(:,:,i)*H; end
end
|
github | garrickbrazil/SDS-RCNN-master | opticalFlow.m | .m | SDS-RCNN-master/external/pdollar_toolbox/videos/opticalFlow.m | 7,386 | utf_8 | bf636ebdd9a6e87b4705c8e9f4ffda81 | function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin )
% Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck.
%
% Implemented 'type' of optical flow estimation:
% LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method
% HS: http://en.wikipedia.org/wiki/Horn-Schunck_method
% SD: Simple block-based sum of absolute differences flow
% LK is a local, fast method (the implementation is fully vectorized).
% HS is a global, slower method (an SSE implementation is provided).
% SD is a simple but potentially expensive approach.
%
% Common parameters: 'smooth' determines smoothing prior to computing flow
% and can make flow estimation more robust. 'filt' determines amount of
% median filtering of the computed flow field which improves results but is
% costly. 'minScale' and 'maxScale' control image scales in the pyramid.
% Setting 'maxScale'<1 results in faster but lower quality results, e.g.
% maxScale=.5 makes flow computation about 4x faster. Method specific
% parameters: 'radius' controls window size (and smoothness of flow) for LK
% and SD. 'nBlock' determines number of blocks tested in each direction for
% SD, computation time is O(nBlock^2). For HS, 'alpha' controls tradeoff
% between data and smoothness term (and smoothness of flow) and 'nIter'
% determines number of gradient decent steps.
%
% USAGE
% [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow )
%
% INPUTS
% I1, I2 - input images to calculate flow between
% pFlow - parameters (struct or name/value pairs)
% .type - ['LK'] may be 'LK', 'HS' or 'SD'
% .smooth - [1] smoothing radius for triangle filter (may be 0)
% .filt - [0] median filtering radius for smoothing flow field
% .minScale - [1/64] minimum pyramid scale (must be a power of 2)
% .maxScale - [1] maximum pyramid scale (must be a power of 2)
% .radius - [10] integration radius for weighted window [LK/SD only]
% .nBlock - [5] number of tested blocks [SD only]
% .alpha - [1] smoothness constraint [HS only]
% .nIter - [250] number of iterations [HS only]
%
% OUTPUTS
% Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down]
% reliab - reliability of flow in given window
%
% EXAMPLE - compute LK flow on test images
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% figure(1); im(I1); figure(2); im(I2);
% figure(3); im([Vx Vy]); colormap jet;
%
% EXAMPLE - rectify I1 to I2 using computed flow
% load opticalFlowTest;
% [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK');
% I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate');
% figure(1); im(I1); figure(2); im(I2);
%
% EXAMPLE - compare LK/HS/SD flows
% load opticalFlowTest;
% prm={'smooth',1,'radius',10,'alpha',20,'nIter',250,'type'};
% tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc
% tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc
% tic, [Vx3,Vy3]=opticalFlow(I1,I2,prm{:},'SD','minScale',1); toc
% figure(1); im([Vx1 Vy1; Vx2 Vy2; Vx3 Vy3]); colormap jet;
%
% See also convTri, imtransform2, medfilt2
%
% Piotr's Computer Vision Matlab Toolbox Version 3.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get default parameters and do error checking
dfs={ 'type','LK', 'smooth',1, 'filt',0, 'minScale',1/64, ...
'maxScale',1, 'radius',10, 'nBlock',5, 'alpha',1, 'nIter',250 };
[type,smooth,filt,minScale,maxScale,radius,nBlock,alpha,nIter] = ...
getPrmDflt(varargin,dfs,1);
assert(any(strcmp(type,{'LK','HS','SD'})));
if( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) )
error('Input images must be 2D and have same dimensions.'); end
% run optical flow in coarse to fine fashion
if(~isa(I1,'single')), I1=single(I1); I2=single(I2); end
[h,w]=size(I1); nScales=max(1,floor(log2(min([h w 1/minScale])))+1);
for s=1:max(1,nScales + round(log2(maxScale)))
% get current scale and I1s and I2s at given scale
scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale);
if( scale==1 ), I1s=I1; I2s=I2; else
I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end
% initialize Vx,Vy or upsample from previous scale
if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx));
Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end
% transform I2s according to current estimate of Vx and Vy
if(s>1), I2s=imtransform2(I2s,[],'pad','replciate','vs',Vx,'us',Vy); end
% smooth images
I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth);
% run optical flow on current scale
switch type
case 'LK', [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius);
case 'HS', [Vx1,Vy1,reliab]=opticalFlowHs(I1s,I2s,alpha,nIter);
case 'SD', [Vx1,Vy1,reliab]=opticalFlowSd(I1s,I2s,radius,nBlock,1);
end
Vx=Vx+Vx1; Vy=Vy+Vy1;
% finally median filter the resulting flow field
if(filt), Vx=medfilt2(Vx,[filt filt],'symmetric'); end
if(filt), Vy=medfilt2(Vy,[filt filt],'symmetric'); end
end
r=sqrt(h*w/numel(Vx));
if(r~=1), Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end
if(r~=1 && nargout==3), reliab=imResample(reliab,[h w]); end
end
function [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius )
% Compute elements of A'A and also of A'b
radius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1);
[Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius);
AAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius);
AAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius);
% Find determinant and trace of A'A
AAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet;
AAdeti(isinf(AAdeti))=0; AAtr=AAxx+AAyy;
% Compute components of velocity vectors (A'A)^-1 * A'b
Vx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt);
Vy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt);
% Check for ill conditioned second moment matrices
reliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet);
end
function [Vx,Vy,reliab] = opticalFlowHs( I1, I2, alpha, nIter )
% compute derivatives (averaging over 2x2 neighborhoods)
pad = @(I,p) imPad(I,p,'replicate');
crop = @(I,c) I(1+c:end-c,1+c:end-c);
Ex = I1(:,2:end)-I1(:,1:end-1) + I2(:,2:end)-I2(:,1:end-1);
Ey = I1(2:end,:)-I1(1:end-1,:) + I2(2:end,:)-I2(1:end-1,:);
Ex = Ex/4; Ey = Ey/4; Et = (I2-I1)/4;
Ex = pad(Ex,[1 1 1 2]) + pad(Ex,[0 2 1 2]);
Ey = pad(Ey,[1 2 1 1]) + pad(Ey,[1 2 0 2]);
Et=pad(Et,[0 2 1 1])+pad(Et,[1 1 1 1])+pad(Et,[1 1 0 2])+pad(Et,[0 2 0 2]);
Z=1./(alpha*alpha + Ex.*Ex + Ey.*Ey); reliab=crop(Z,1);
% iterate updating Ux and Vx in each iter
if( 1 )
[Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter);
Vx=crop(Vx,1); Vy=crop(Vy,1);
else
Ex=crop(Ex,1); Ey=crop(Ey,1); Et=crop(Et,1); Z=crop(Z,1);
Vx=zeros(size(I1),'single'); Vy=Vx;
f=single([0 1 0; 1 0 1; 0 1 0])/4;
for i = 1:nIter
Mx=conv2(Vx,f,'same'); My=conv2(Vy,f,'same');
m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m;
end
end
end
function [Vx,Vy,reliab] = opticalFlowSd( I1, I2, radius, nBlock, step )
% simple block-based sum of absolute differences flow
[h,w]=size(I1); k=2*nBlock+1; k=k*k; D=zeros(h,w,k,'single'); k=1;
rng = @(x,w) max(1+x*step,1):min(w+x*step,w);
for x=-nBlock:nBlock, xs0=rng(x,w); xs1=rng(-x,w);
for y=-nBlock:nBlock, ys0=rng(y,h); ys1=rng(-y,h);
D(ys0,xs0,k)=abs(I1(ys0,xs0)-I2(ys1,xs1)); k=k+1;
end
end
D=convTri(D,radius); [reliab,D]=min(D,[],3);
k=2*nBlock+1; Vy=mod(D-1,k)+1; Vx=(D-Vy)/k+1;
Vy=(nBlock+1-Vy)*step; Vx=(nBlock+1-Vx)*step;
end
|
github | garrickbrazil/SDS-RCNN-master | seqWriterPlugin.m | .m | SDS-RCNN-master/external/pdollar_toolbox/videos/seqWriterPlugin.m | 8,280 | utf_8 | 597792f79fff08b8bb709313267c3860 | function varargout = seqWriterPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow writing of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (swp=seqWriterPlugin):
% h=swp('open',h,fName,info) % Open a seq file for writing (h ignored).
% h=swp('close',h) % Close seq file (output h is -1).
% swp('addframe',h,I,[ts]) % Writes video frame (and timestamp).
% swp('addframeb',h,I,[ts]) % Writes video frame with no encoding.
% info = swp('getinfo',h) % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% varargout = seqWriterPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQREADERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.66
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o1=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
fName=[pth filesep name];
[infos{h},fids(h),tNms{h}]=open(fName,in{2}); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
writeHeader(fid,info);
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'addframe', chk(nIn,1,2); info=addFrame(fid,info,tNm,1,in{:});
case 'addframeb', chk(nIn,1,2); info=addFrame(fid,info,tNm,0,in{:});
case 'getinfo', chk(nIn,0); o1=info;
otherwise, error(['Unrecognized command: "' cmd '"']);
end
infos{h}=info; varargout={o1};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for writing, create space for header
t=[fName '.seq']; if(exist(t,'file')), delete(t); end
t=[fName '-seek.mat']; if(exist(t,'file')), delete(t); end
fid=fopen([fName '.seq'],'w','l'); assert(fid~=-1);
fwrite(fid,zeros(1,1024),'uint8');
% initialize info struct (w all fields necessary for writeHeader)
assert(isfield2(info,{'width','height','fps','codec'},1));
switch(info.codec)
case {'monoraw', 'imageFormat100'}, frmt=100; nCh=1; ext='raw';
case {'raw', 'imageFormat200'}, frmt=200; nCh=3; ext='raw';
case {'monojpg', 'imageFormat102'}, frmt=102; nCh=1; ext='jpg';
case {'jpg', 'imageFormat201'}, frmt=201; nCh=3; ext='jpg';
case {'monopng', 'imageFormat001'}, frmt=001; nCh=1; ext='png';
case {'png', 'imageFormat002'}, frmt=002; nCh=3; ext='png';
otherwise, error('unknown format');
end; s=1;
if(strcmp(ext,'jpg')), s=getImgFile('wjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.writeImg=@(p) png('write',p{:}); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngwritec');
if(s), info.writeImg=@(p) pngwritec(p{:}); end; end
if(~s), error('Cannot find Matlab''s source image writer'); end
info.imageFormat=frmt; info.ext=ext;
if(any(strcmp(ext,{'jpg','png'}))), info.seek=1024; info.seekNm=t; end
if(~isfield2(info,'quality')), info.quality=80; end
info.imageBitDepth=8*nCh; info.imageBitDepthReal=8;
nByte=info.width*info.height*nCh; info.imageSizeBytes=nByte;
info.numFrames=0; info.trueImageSize=nByte+6+512-mod(nByte+6,512);
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
end
function info = addFrame( fid, info, tNm, encode, I, ts )
% write frame
nCh=info.imageBitDepth/8; ext=info.ext; c=info.numFrames+1;
if( encode )
siz = [info.height info.width nCh];
assert(size(I,1)==siz(1) && size(I,2)==siz(2) && size(I,3)==siz(3));
end
switch ext
case 'raw'
% write an uncompressed image (assume imageBitDepthReal==8)
if( ~encode ), assert(numel(I)==info.imageSizeBytes); else
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(nCh==1), I=I'; else I=permute(I,[3,2,1]); end
end
fwrite(fid,I(:),'uint8'); pad=info.trueImageSize-info.imageSizeBytes-6;
case 'jpg'
if( encode )
% write/read to/from temporary .jpg (not that much overhead)
p=struct('quality',info.quality,'comment',{{}},'mode','lossy');
for t=0:99, try wjpg8c(I,tNm,p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
case 'png'
if( encode )
% write/read to/from temporary .png (not that much overhead)
p=cell(1,17); if(nCh==1), p{4}=0; else p{4}=2; end
p{1}=I; p{3}=tNm; p{5}=8; p{8}='none'; p{16}=cell(0,2);
for t=0:99, try info.writeImg(p); fr=fopen(tNm,'r'); assert(fr>0);
break; catch, pause(.01); fr=-1; end; end %#ok<CTCH>
if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr);
end
fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10;
otherwise, assert(false);
end
% store seek info
if(any(strcmp(ext,{'jpg','png'})))
if(length(info.seek)<c+1), info.seek=[info.seek; zeros(c,1)]; end
info.seek(c+1)=info.seek(c)+numel(I)+10+pad;
end
% write timestamp
if(nargin<6),ts=(c-1)/info.fps; end; s=floor(ts); ms=round(mod(ts,1)*1000);
fwrite(fid,s,'int32'); fwrite(fid,ms,'uint16'); info.numFrames=c;
% pad with zeros
if(pad>0), fwrite(fid,zeros(1,pad),'uint8'); end
end
function writeHeader( fid, info )
fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
fwrite(fid,hex2dec('FEED'),'uint32');
fwrite(fid,['Norpix seq' 0 0],'uint16');
% next 8 bytes for version (3) and header size (1024), then 512 for descr
fwrite(fid,[3 1024],'int32');
if(isfield(info,'descr')), d=info.descr(:); else d=('No Description')'; end
d=[d(1:min(256,end)); zeros(256-length(d),1)]; fwrite(fid,d,'uint16');
% write remaining info
vals=[info.width info.height info.imageBitDepth info.imageBitDepthReal ...
info.imageSizeBytes info.imageFormat info.numFrames 0 ...
info.trueImageSize];
fwrite(fid,vals,'uint32');
% store frame rate and pad with 0's
fwrite(fid,info.fps,'float64'); fwrite(fid,zeros(1,432),'uint8');
% write seek info for compressed images to disk
if(any(strcmp(info.ext,{'jpg','png'})))
seek=info.seek(1:info.numFrames); %#ok<NASGU>
try save(info.seekNm,'seek'); catch; end %#ok<CTCH>
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.