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
mribri999/MRSignalsSeqs-master
exrecsignal.m
.m
MRSignalsSeqs-master/Matlab/exrecsignal.m
525
utf_8
739a3c2f8ff99ce98b383dbb8818b20f
% %[sig] = exrecsignal(T1,T2,TE,TR,flip) % % Calculates the steady-state signal of a % simple excitation recovery sequence (or SPGR). % % T1,T2,TE,TR are tissue/sequence parameters. % flip is the flip angle in degrees. % The signal as a fraction of Mo is returned. % function [sig,M] = exrecsignal(T1,T2,TE,TR,flip); s = sin(pi*flip/180); c = cos(pi*flip/180); E = exp(-TE/T2); R = exp(-(TR)/T1); if (abs(1-R*c)<.0001) sig = 1; M=[1;0;0]; else sig = (1-R)*E*s/(1-R*c); M = [sig;0;(1-R)*E*c/(1-R*c)]; end;
github
mribri999/MRSignalsSeqs-master
displogim.m
.m
MRSignalsSeqs-master/Matlab/displogim.m
394
utf_8
15e0d58b6b15e9ee17ceac106aca806d
% displogim(im) % displays log-magnitude version of image im (complex array) % % im = 2D image array (real or complex, magnitude displayed) % % =========================================================== function displogim(im) im = squeeze((im)); lowexp = 0; % Make negative if max(im) is small. im = log(abs(im)); f = find(im(:)< (lowexp)); im(f)= lowexp; im = im - lowexp; dispim(im);
github
mribri999/MRSignalsSeqs-master
setprops.m
.m
MRSignalsSeqs-master/Matlab/setprops.m
486
utf_8
d102d65180a29160f152b96e8bf8184c
% % function setprops(handle, propertylist,debug) % % Function sets the properties of the handle and children % according to propertylist. % % propertylist is a list object of the form % { type1, prop1, val1, type2, prop2, val2, ... } % % For each child of handle, if the type matches typeN, and % there is a property matching propN, then it is set to valN. % % B.Hargreaves % function setprops(handle, propertylist,debug) % Do nothing... not working on 2016/2017 so commenting out!
github
mribri999/MRSignalsSeqs-master
showspins.m
.m
MRSignalsSeqs-master/Matlab/showspins.m
3,202
utf_8
ca809fe420d5a8550bf28da3a7bdf70c
%function showspins(M,scale,spinorig,myc) % % Show vector plot on one axis, that can then be rotated for 2D or 3D % viewing. % % M = 3xN spins to show % scale = axis scaling [-scale scale] defaults to 1. % spinorig = 3xN origin of spins % myc = colors to show spins (will default to something reasonable.) % % Get arrow3D to make these look nicer! % function showspins(M,scale,spinorig,myc) if (nargin < 1) M = [0.8,0,0.2].'; end; if (nargin < 2) scale = 1.0; end; if (nargin < 3) spinorig = 0*M; end; sz = size(M); Nspins = sz(2); myc = mycolors(Nspins); % -- Get nice colors, if not passed % -- Plot vectors. hold off; for k=1:Nspins if (exist('arrow3D')) %arrow3D(spinorig(:,k),M(:,k),myc(k,:),0.8,0.03*scale); arrow3D(spinorig(:,k),M(:,k),myc(k,:),0.8); else h = plot3([spinorig(1,k) M(1,k)],[spinorig(2,k) M(2,k)],[spinorig(3,k) M(3,k)]); set(h,'LineWidth',3); set(h,'Color',myc(k,:)); hold on; grid on; end; end; axis(scale*[-1 1 -1 1 -1 1]); % -- Label Axes, set nice effects xlabel('M_x'); ylabel('M_y'); zlabel('M_z'); axis square; lighting phong; camlight right; function c = mycolors(n) cc = [ 0 0 0.5625 0 0 0.6250 0 0 0.6875 0 0 0.7500 0 0 0.8125 0 0 0.8750 0 0 0.9375 0 0 1.0000 0 0.0625 1.0000 0 0.1250 1.0000 0 0.1875 1.0000 0 0.2500 1.0000 0 0.3125 1.0000 0 0.3750 1.0000 0 0.4375 1.0000 0 0.5000 1.0000 0 0.5625 1.0000 0 0.6250 1.0000 0 0.6875 1.0000 0 0.7500 1.0000 0 0.8125 1.0000 0 0.8750 1.0000 0 0.9375 1.0000 0 1.0000 1.0000 0.0625 1.0000 0.9375 0.1250 1.0000 0.8750 0.1875 1.0000 0.8125 0.2500 1.0000 0.7500 0.3125 1.0000 0.6875 0.3750 1.0000 0.6250 0.4375 1.0000 0.5625 0.5000 1.0000 0.5000 0.5625 1.0000 0.4375 0.6250 1.0000 0.3750 0.6875 1.0000 0.3125 0.7500 1.0000 0.2500 0.8125 1.0000 0.1875 0.8750 1.0000 0.1250 0.9375 1.0000 0.0625 1.0000 1.0000 0 1.0000 0.9375 0 1.0000 0.8750 0 1.0000 0.8125 0 1.0000 0.7500 0 1.0000 0.6875 0 1.0000 0.6250 0 1.0000 0.5625 0 1.0000 0.5000 0 1.0000 0.4375 0 1.0000 0.3750 0 1.0000 0.3125 0 1.0000 0.2500 0 1.0000 0.1875 0 1.0000 0.1250 0 1.0000 0.0625 0 1.0000 0 0 0.9375 0 0 0.8750 0 0 0.8125 0 0 0.7500 0 0 0.6875 0 0 0.6250 0 0 0.5625 0 0 0.5000 0 0]; sz = size(cc); cind = ceil(([1:n]/(n+1))*sz(1)); c = cc(cind,:);
github
mribri999/MRSignalsSeqs-master
diamond.m
.m
MRSignalsSeqs-master/Matlab/diamond.m
411
utf_8
96a7ec2f0bdf60d8d0a03262f0380a15
% function im = diamond(size,w) % % Make a diamond of given width in a given image size % % INPUT: % size = matrix size (2D) % w = width (widest point) % % OUTPUT: % image that is 1 inside diamond, 0 elsewhere. % function im = diamond(size,w) [x,y] = meshgrid([1:size]-size/2,[1:size]-size/2); im = ones(size,size); im(find(x+y>w/2))=0; im(find(x-y>w/2))=0; im(find(-x+y>w/2))=0; im(find(-x-y>w/2))=0;
github
mribri999/MRSignalsSeqs-master
gresignal.m
.m
MRSignalsSeqs-master/Matlab/gresignal.m
660
utf_8
0998ede31b51b02565f67c4bed822512
% [sig] = gresignal(T1,T2,TE,TR,flip) % % Plot the theoretical signal for a gradient-spoiled sequence. % Note that this is NOT RF-spoiled GRE, which is the same % (roughly) as excitation-recovery. % % T1,T2,TE,TR are parameters for tissue and sequence. % flip is the flip angle in degrees. % The signal as a fraction of Mo is returned. % % See Buxton 1989. function [sig] = gresignal(T1,T2,TE,TR,flip) E1 = exp(-TR/T1); E2 = exp(-TR/T2); E = exp(-TE/T2); s = sin(pi*flip/180); c = cos(pi*flip/180); B = 1 - E1*c - E2^2*(E1-c); C = E2*(1-E1)*(1+c); A = sqrt(B^2-C^2); if (abs(A*C)==0) sig = 1; else sig = s*(1-E1)*E* (C-E2*(B-A)) / (A*C); end;
github
mribri999/MRSignalsSeqs-master
lec7kimhist.m
.m
MRSignalsSeqs-master/Matlab/lectures/lec7kimhist.m
558
utf_8
5f9a53916c654698521d1556d44e09d1
% % Function plots k-space, image and histogram, and returns mean and sd. function [mn,sd] = lec7kimhist(ksp,ftitle,histpts,refsnr) [N,M] = size(ksp); im = (1/N)*ft(ksp); subplot(2,2,1); dispim(log(1+abs(ksp))); tt = sprintf('kspace - %s',ftitle); title(tt); axis off; subplot(2,2,2); dispim(im); tt = sprintf('image - %s',ftitle); title(tt); axis off; subplot(2,2,3); [mn,sd] = ghist(histpts); if (nargin < 4) refsnr = mn/sd; end; title(ftitle); tt=sprintf('%s: mean=%g, stdev=%g, ratio=%g, relative=%g',ftitle,mn,sd,mn/sd,mn/sd/refsnr); disp(tt);
github
yikouniao/MTMCT-master
distHSV1.m
.m
MTMCT-master/distHSV1.m
389
utf_8
1a407c98a3a355ba29c35a7be65d0854
%function [dist] = distHSV1(dAppr1, dAppr2, w_f) function [dist] = distHSV1(flag1, appr1, flag2, appr2, w_f) k1 = find(flag1'); k2 = find(flag2'); %n1 = size(k1,1); n2 = size(k2,1); w = zeros(8,8); dist = 0; for i = k1 for j = k2 w(i,j) = w_f(abs(dirDiff(i, j))+1); dist = dist + w(i,j) * distHSV(appr1(i,:), appr2(j,:)); end end dist = dist / sum(w(:)); end
github
yikouniao/MTMCT-master
knnsearch2.m
.m
MTMCT-master/utils/misc/knnsearch2.m
3,977
utf_8
6121bae49c29fe897da0d67a9d77ecfa
function [idx,D]=knnsearch2(varargin) % KNNSEARCH Linear k-nearest neighbor (KNN) search % IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array % representing n points in a d-dimensional space) to find the k-nearest % neighbors of each query point represented by eahc row of Q (m x d array). % The results are stored in the (m x K) index array, IDX. % % IDX = knnsearch(Q,R) takes the default value K=1. % % IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q. % % Rationality % Linear KNN search is the simplest appraoch of KNN. The search is based on % calculation of all distances. Therefore, it is normally believed only % suitable for small data sets. However, other advanced approaches, such as % kd-tree and delaunary become inefficient when d is large comparing to the % number of data points. On the other hand, the linear search in MATLAB is % relatively insensitive to d due to the vectorization. In this code, the % efficiency of linear search is further improved by using the JIT % aceeleration of MATLAB. Numerical example shows that its performance is % comparable with kd-tree algorithm in mex. % % See also, kdtree, nnsearch, delaunary, dsearch % By Yi Cao at Cranfield University on 25 March 2008 % Example 1: small data sets %{ R=randn(100,2); Q=randn(3,2); idx=knnsearch(Q,R); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx'); %} % Example 2: ten nearest points to [0 0] %{ R=rand(100,2); Q=[0 0]; K=10; idx=knnsearch(Q,R,10); r=max(sqrt(sum(R(idx,:).^2,2))); theta=0:0.01:pi/2; x=r*cos(theta); y=r*sin(theta); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2); %} % Example 3: cputime comparion with delaunay+dsearch I, a few to look up %{ R=randn(10000,4); Q=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 4: cputime comparion with delaunay+dsearch II, lots to look up %{ Q=randn(10000,4); R=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 5: cputime comparion with kd-tree by Steven Michael (mex file) % <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=7030&objectType=file">kd-tree by Steven Michael</a> %{ Q=randn(10000,10); R=randn(500,10); t0=cputime; idx=knnsearch(Q,R); t1=cputime; tree=kdtree(R); idx1=kdtree_closestpoint(tree,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Check inputs [Q,R,K,fident] = parseinputs(varargin{:}); % Check outputs error(nargoutchk(0,2,nargout)); % C2 = sum(C.*C,2)'; [N,M] = size(Q); L=size(R,1); idx = zeros(N,K); D = idx; if K==1 % Loop for each query point for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [D(k),idx(k)]=min(d); end else for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [s,t]=sort(d); idx(k,:)=t(1:K); D(k,:)=s(1:K); end end if nargout>1 D=sqrt(D); end function [Q,R,K,fident] = parseinputs(varargin) % Check input and output error(nargchk(1,3,nargin)); Q=varargin{1}; if nargin<2 R=Q; fident = true; else fident = false; R=varargin{2}; end if isempty(R) fident = true; R=Q; end if ~fident fident = isequal(Q,R); end if nargin<3 K=1; else K=varargin{3}; end
github
niravshah241/master_thesis-master
mygridnirav3.m
.m
master_thesis-master/misc/mygridnirav3.m
1,388
utf_8
9a6faaff1ebcca1720cc1ed2c6a0531b
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[3 2 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 1 0 1],'SQ1'); pdecirc(0.5,0.5,0.10000000000000001,'C1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','SQ1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
mygridnirav2.m
.m
master_thesis-master/misc/mygridnirav2.m
1,485
utf_8
0577163a9727f7bcfe0ae7bd844775ea
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[3 2 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 2.2000000000000002 0.40999999999999998 0],'R1'); pdeellip(0.20000000000000001,0.20000000000000001,0.050000000000000003,0.050000000000000003,... 0,'E1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1-E1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
ch3_fig_1.m
.m
master_thesis-master/thesis_latex/ch3_fig_1.m
1,418
utf_8
474509356b96297c891b0905e6c85308
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[1.5 1 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([-0.5039525691699609 0.29446640316205563 0.41699604743082963 -0.15217391304347805],'R1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
figsame.m
.m
master_thesis-master/figsame/figsame.m
895
utf_8
83086746f829eac6e6af849a8d84e69f
% FIGSAME Makes figures the same size % % FIGSAME Resizes all figures to be the size of gcf % FIGSAME(f1) Resizes all figures to be the size as figure f1 % FIGSAME(f1,f2) Resizes figure(s) specified by vector f2 to be the same % size as f1 function figsame(f1,f2) if ~exist('f1','var') f1 = gcf; end if ~exist('f2','var') f2 = get(0,'children'); end if ~isscalar(f1) || ~isvector(f2) error('Usage: figsamesize(f1 (scalar),f2 (vector))') end figure(f1); figsiz = get(gcf,'Position'); newfigpos = figsiz; scrn = get(0,'screensize'); n = 20; %Shift by 20 pixels for k = [f2(:)]' figure(k); newfigpos = newfigpos+[n -n 0 0]; % Make sure we don't push it off the screen... if newfigpos*[1;0;1;0] > scrn(3) newfigpos(1) = 1; end newfigpos(2) = max(newfigpos(2), 1); set(gcf,'Position',newfigpos); end
github
niravshah241/master_thesis-master
mygridnirav3.m
.m
master_thesis-master/my_grids/mygridnirav3.m
1,388
utf_8
299b51eaa73f8d5968f74152aeeabae8
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[3 2 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 1 0 1],'SQ1'); pdecirc(0.2,0.2,0.05000000000000001,'C1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','SQ1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
mygridnirav2.m
.m
master_thesis-master/my_grids/mygridnirav2.m
1,485
utf_8
0577163a9727f7bcfe0ae7bd844775ea
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[3 2 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 2.2000000000000002 0.40999999999999998 0],'R1'); pdeellip(0.20000000000000001,0.20000000000000001,0.050000000000000003,0.050000000000000003,... 0,'E1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1-E1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
pdegrid_2.m
.m
master_thesis-master/my_grids/pdegrid_2.m
1,343
utf_8
edaa38fe40d2dcff1967c1e8831b8419
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[3 2 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 1 1 0],'R1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
pdegrid_1.m
.m
master_thesis-master/my_grids/pdegrid_1.m
2,011
utf_8
410bda61cc054bf1b3dd7d184c98af49
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[1.5 1 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 1 0 1],'SQ1'); pdecirc(0.2,0.5,0.05000000000000001,'C1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','SQ1-C1') % Boundary conditions: pdetool('changemode',0) pdesetbd(8,... 'dir',... 1,... '1',... '0') pdesetbd(7,... 'dir',... 1,... '1',... '0') pdesetbd(6,... 'dir',... 1,... '1',... '0') pdesetbd(5,... 'dir',... 1,... '1',... '0') pdesetbd(4,... 'dir',... 1,... '1',... '0') pdesetbd(3,... 'neu',... 1,... '0',... '0') pdesetbd(2,... 'dir',... 1,... '1',... '0') pdesetbd(1,... 'neu',... 1,... '0',... '0') % Mesh generation: setappdata(pde_fig,'Hgrad',1.3); setappdata(pde_fig,'refinemethod','regular'); setappdata(pde_fig,'jiggle',char('on','mean','')); setappdata(pde_fig,'MesherVersion','preR2013a'); pdetool('initmesh') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
niravshah241/master_thesis-master
pdegrid_convergenece_tests.m
.m
master_thesis-master/my_grids/testgrids/pdegrid_convergenece_tests.m
1,788
utf_8
de0a42a66cffa00f56ba36b4b84a3810
% This script is written and read by pdetool and should NOT be edited. % There are two recommended alternatives: % 1) Export the required variables from pdetool and create a MATLAB script % to perform operations on these. % 2) Define the problem completely using a MATLAB script. See % http://www.mathworks.com/help/pde/examples/index.html for examples % of this approach. function pdemodel [pde_fig,ax]=pdeinit; pdetool('appl_cb',1); set(ax,'DataAspectRatio',[1 1 1]); set(ax,'PlotBoxAspectRatio',[1.5 1 1]); set(ax,'XLim',[-1.5 1.5]); set(ax,'YLim',[-1 1]); set(ax,'XTickMode','auto'); set(ax,'YTickMode','auto'); % Geometry description: pderect([0 1 1 0],'R1'); set(findobj(get(pde_fig,'Children'),'Tag','PDEEval'),'String','R1') % Boundary conditions: pdetool('changemode',0) pdesetbd(4,... 'dir',... 1,... '1',... '0') pdesetbd(3,... 'dir',... 1,... '1',... '0') pdesetbd(2,... 'dir',... 1,... '1',... '0') pdesetbd(1,... 'dir',... 1,... '1',... '0') % Mesh generation: setappdata(pde_fig,'Hgrad',1.3); setappdata(pde_fig,'refinemethod','regular'); setappdata(pde_fig,'jiggle',char('on','mean','')); setappdata(pde_fig,'MesherVersion','preR2013a'); pdetool('initmesh') % PDE coefficients: pdeseteq(1,... '1.0',... '0.0',... '10.0',... '1.0',... '0:10',... '0.0',... '0.0',... '[0 100]') setappdata(pde_fig,'currparam',... ['1.0 ';... '0.0 ';... '10.0';... '1.0 ']) % Solve parameters: setappdata(pde_fig,'solveparam',... char('0','1000','10','pdeadworst',... '0.5','longest','0','1E-4','','fixed','Inf')) % Plotflags and user data strings: setappdata(pde_fig,'plotflags',[1 1 1 1 1 1 1 1 0 0 0 1 1 0 0 0 0 1]); setappdata(pde_fig,'colstring',''); setappdata(pde_fig,'arrowstring',''); setappdata(pde_fig,'deformstring',''); setappdata(pde_fig,'heightstring','');
github
IrvingShu/XQDA-master
LOMO.m
.m
XQDA-master/code/LOMO.m
10,916
utf_8
b6e9a0ae258aa1945212a176248cde9f
function descriptors = LOMO(images, options) %% function Descriptors = LOMO(images, options) % Function for the Local Maximal Occurrence (LOMO) feature extraction % % Input: % <images>: a set of n RGB color images. Size: [h, w, 3, n] % [optioins]: optional parameters. A structure containing any of the % following fields: % numScales: number of pyramid scales in feature extraction. Default: 3 % blockSize: size of the sub-window for histogram counting. Default: 10 % blockStep: sliding step for the sub-windows. Default: 5 % hsvBins: number of bins for HSV channels. Default: [8,8,8] % tau: the tau parameter in SILTP. Default: 0.3 % R: the radius paramter in SILTP. Specify multiple values for multiscale SILTP. Default: [3, 5] % numPoints: number of neiborhood points for SILTP encoding. Default: 4 % The above default parameters are good for 128x48 and 160x60 person % images. You may need to adjust the numScales, blockSize, and R parameters % for other smaller or higher resolutions. % % Output: % descriptors: the extracted LOMO descriptors. Size: [d, n] % % Example: % I = imread('../images/000_45_a.bmp'); % descriptor = LOMO(I); % % Reference: % Shengcai Liao, Yang Hu, Xiangyu Zhu, and Stan Z. Li. Person % re-identification by local maximal occurrence representation and metric % learning. In IEEE Conference on Computer Vision and Pattern Recognition, 2015. % % Version: 1.0 % Date: 2015-04-29 % % Author: Shengcai Liao % Institute: National Laboratory of Pattern Recognition, % Institute of Automation, Chinese Academy of Sciences % Email: [email protected] %% set parameters numScales = 3; blockSize = 10; blockStep = 5; hsvBins = [8,8,8]; tau = 0.3; R = [3, 5]; numPoints = 4; if nargin >= 2 if isfield(options,'numScales') && ~isempty(options.numScales) && isscalar(options.numScales) && isnumeric(options.numScales) && options.numScales > 0 numScales = options.numScales; fprintf('numScales = %d.\n', numScales); end if isfield(options,'blockSize') && ~isempty(options.blockSize) && isscalar(options.blockSize) && isnumeric(options.blockSize) && options.blockSize > 0 blockSize = options.blockSize; fprintf('blockSize = %d.\n', blockSize); end if isfield(options,'blockStep') && ~isempty(options.blockStep) && isscalar(options.blockStep) && isnumeric(options.blockStep) && options.blockStep > 0 blockStep = options.blockStep; fprintf('blockStep = %d.\n', blockStep); end if isfield(options,'hsvBins') && ~isempty(options.hsvBins) && isvector(options.blockStep) && isnumeric(options.hsvBins) && length(options.hsvBins) == 3 && all(options.hsvBins > 0) hsvBins = options.hsvBins; fprintf('hsvBins = [%d, %d, %d].\n', hsvBins); end if isfield(options,'tau') && ~isempty(options.tau) && isscalar(options.tau) && isnumeric(options.tau) && options.tau > 0 tau = options.tau; fprintf('tau = %g.\n', tau); end if isfield(options,'R') && ~isempty(options.R) && isnumeric(options.R) && all(options.R > 0) R = options.R; fprintf('R = %d.\n', R); end if isfield(options,'numPoints') && ~isempty(options.numPoints) && isscalar(options.numPoints) && isnumeric(options.numPoints) && options.numPoints > 0 numPoints = options.numPoints; fprintf('numPoints = %d.\n', numPoints); end end t0 = tic; %% extract Joint HSV based LOMO descriptors fea1 = PyramidMaxJointHist( images, numScales, blockSize, blockStep, hsvBins ); %% extract SILTP based LOMO descriptors fea2 = []; for i = 1 : length(R) fea2 = [fea2; PyramidMaxSILTPHist( images, numScales, blockSize, blockStep, tau, R(i), numPoints )]; %#ok<AGROW> end %% finishing descriptors = [fea1; fea2]; clear Fea1 Fea2 feaTime = toc(t0); meanTime = feaTime / size(images, 4); fprintf('LOMO feature extraction finished. Running time: %.3f seconds in total, %.3f seconds per image.\n', feaTime, meanTime); end function descriptors = PyramidMaxJointHist( oriImgs, numScales, blockSize, blockStep, colorBins ) %% PyramidMaxJointHist: HSV based LOMO representation if nargin == 1 numScales = 3; blockSize = 10; blockStep = 5; colorBins = [8,8,8]; end totalBins = prod(colorBins); numImgs = size(oriImgs, 4); images = zeros(size(oriImgs)); % color transformation for i = 1 : numImgs I = oriImgs(:,:,:,i); I = Retinex(I); I = rgb2hsv(I); I(:,:,1) = min( floor( I(:,:,1) * colorBins(1) ), colorBins(1)-1 ); I(:,:,2) = min( floor( I(:,:,2) * colorBins(2) ), colorBins(2)-1 ); I(:,:,3) = min( floor( I(:,:,3) * colorBins(3) ), colorBins(3)-1 ); images(:,:,:,i) = I; % HSV end minRow = 1; minCol = 1; descriptors = []; % Scan multi-scale blocks and compute histograms for i = 1 : numScales patterns = images(:,:,3,:) * colorBins(2) * colorBins(1) + images(:,:,2,:)*colorBins(1) + images(:,:,1,:); % HSV patterns = reshape(patterns, [], numImgs); height = size(images, 1); width = size(images, 2); maxRow = height - blockSize + 1; maxCol = width - blockSize + 1; [cols,rows] = meshgrid(minCol:blockStep:maxCol, minRow:blockStep:maxRow); % top-left positions cols = cols(:); rows = rows(:); numBlocks = length(cols); numBlocksCol = length(minCol:blockStep:maxCol); if numBlocks == 0 break; end offset = bsxfun(@plus, (0 : blockSize-1)', (0 : blockSize-1) * height); % offset to the top-left positions. blockSize-by-blockSize index = sub2ind([height, width], rows, cols); index = bsxfun(@plus, offset(:), index'); % (blockSize*blockSize)-by-numBlocks patches = patterns(index(:), :); % (blockSize * blockSize * numBlocks)-by-numImgs patches = reshape(patches, [], numBlocks * numImgs); % (blockSize * blockSize)-by-(numBlocks * numChannels * numImgs) fea = hist(patches, 0 : totalBins-1); % totalBins-by-(numBlocks * numImgs) fea = reshape(fea, [totalBins, numBlocks / numBlocksCol, numBlocksCol, numImgs]); fea = max(fea, [], 3); fea = reshape(fea, [], numImgs); descriptors = [descriptors; fea]; %#ok<AGROW> if i < numScales images = ColorPooling(images, 'average'); end end descriptors = log(descriptors + 1); descriptors = normc(descriptors); end function outImages = ColorPooling(images, method) [height, width, numChannels, numImgs] = size(images); outImages = images; if mod(height, 2) == 1 outImages(end, :, :, :) = []; height = height - 1; end if mod(width, 2) == 1 outImages(:, end, :, :) = []; width = width - 1; end if height == 0 || width == 0 error('Over scaled image: height=%d, width=%d.', height, width); end height = height / 2; width = width / 2; outImages = reshape(outImages, 2, height, 2, width, numChannels, numImgs); outImages = permute(outImages, [2, 4, 5, 6, 1, 3]); outImages = reshape(outImages, height, width, numChannels, numImgs, 2*2); if strcmp(method, 'average') outImages = floor(mean(outImages, 5)); else if strcmp(method, 'max') outImages = max(outImages, [], 5); else error('Error pooling method: %s.', method); end end end function descriptors = PyramidMaxSILTPHist( oriImgs, numScales, blockSize, blockStep, tau, R, numPoints ) %% PyramidMaxSILTPHist: SILTP based LOMO representation if nargin == 1 numScales = 3; blockSize = 10; blockStep = 5; tau = 0.3; R = 5; numPoints = 4; end totalBins = 3^numPoints; [imgHeight, imgWidth, ~, numImgs] = size(oriImgs); images = zeros(imgHeight,imgWidth, numImgs); % Convert gray images for i = 1 : numImgs I = oriImgs(:,:,:,i); I = rgb2gray(I); images(:,:,i) = double(I) / 255; end minRow = 1; minCol = 1; descriptors = []; % Scan multi-scale blocks and compute histograms for i = 1 : numScales height = size(images, 1); width = size(images, 2); if width < R * 2 + 1 fprintf('Skip scale R = %d, width = %d.\n', R, width); continue; end patterns = SILTP(images, tau, R, numPoints); patterns = reshape(patterns, [], numImgs); maxRow = height - blockSize + 1; maxCol = width - blockSize + 1; [cols,rows] = meshgrid(minCol:blockStep:maxCol, minRow:blockStep:maxRow); % top-left positions cols = cols(:); rows = rows(:); numBlocks = length(cols); numBlocksCol = length(minCol:blockStep:maxCol); if numBlocks == 0 break; end offset = bsxfun(@plus, (0 : blockSize-1)', (0 : blockSize-1) * height); % offset to the top-left positions. blockSize-by-blockSize index = sub2ind([height, width], rows, cols); index = bsxfun(@plus, offset(:), index'); % (blockSize*blockSize)-by-numBlocks patches = patterns(index(:), :); % (blockSize * blockSize * numBlocks)-by-numImgs patches = reshape(patches, [], numBlocks * numImgs); % (blockSize * blockSize)-by-(numBlocks * numChannels * numImgs) fea = hist(patches, 0:totalBins-1); % totalBins-by-(numBlocks * numImgs) fea = reshape(fea, [totalBins, numBlocks / numBlocksCol, numBlocksCol, numImgs]); fea = max(fea, [], 3); fea = reshape(fea, [], numImgs); descriptors = [descriptors; fea]; %#ok<AGROW> if i < numScales images = Pooling(images, 'average'); end end descriptors = log(descriptors + 1); descriptors = normc(descriptors); end function outImages = Pooling(images, method) [height, width, numImgs] = size(images); outImages = images; if mod(height, 2) == 1 outImages(end, :, :) = []; height = height - 1; end if mod(width, 2) == 1 outImages(:, end, :) = []; width = width - 1; end if height == 0 || width == 0 error('Over scaled image: height=%d, width=%d.', height, width); end height = height / 2; width = width / 2; outImages = reshape(outImages, 2, height, 2, width, numImgs); outImages = permute(outImages, [2, 4, 5, 1, 3]); outImages = reshape(outImages, height, width, numImgs, 2*2); if strcmp(method, 'average') outImages = mean(outImages, 4); else if strcmp(method, 'max') outImages = max(outImages, [], 4); else error('Error pooling method: %s.', method); end end end
github
JamesLinus/webrtc-master
readDetection.m
.m
webrtc-master/modules/audio_processing/transient/test/readDetection.m
927
utf_8
f6af5020971d028a50a4d19a31b33bcb
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [d, t] = readDetection(file, fs, chunkSize) %[d, t] = readDetection(file, fs, chunkSize) % %Reads a detection signal from a DAT file. % %d: The detection signal. %t: The respective time vector. % %file: The DAT file where the detection signal is stored in float format. %fs: The signal sample rate in Hertz. %chunkSize: The chunk size used for the detection in seconds. fid = fopen(file); d = fread(fid, inf, 'float'); fclose(fid); t = 0:(1 / fs):(length(d) * chunkSize - 1 / fs); d = d(floor(t / chunkSize) + 1);
github
JamesLinus/webrtc-master
readPCM.m
.m
webrtc-master/modules/audio_processing/transient/test/readPCM.m
821
utf_8
76b2955e65258ada1c1e549a4fc9bf79
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [x, t] = readPCM(file, fs) %[x, t] = readPCM(file, fs) % %Reads a signal from a PCM file. % %x: The read signal after normalization. %t: The respective time vector. % %file: The PCM file where the signal is stored in int16 format. %fs: The signal sample rate in Hertz. fid = fopen(file); x = fread(fid, inf, 'int16'); fclose(fid); x = x - mean(x); x = x / max(abs(x)); t = 0:(1 / fs):((length(x) - 1) / fs);
github
JamesLinus/webrtc-master
plotDetection.m
.m
webrtc-master/modules/audio_processing/transient/test/plotDetection.m
923
utf_8
e8113bdaf5dcfe4f50200a3ca29c3846
% % Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [] = plotDetection(PCMfile, DATfile, fs, chunkSize) %[] = plotDetection(PCMfile, DATfile, fs, chunkSize) % %Plots the signal alongside the detection values. % %PCMfile: The file of the input signal in PCM format. %DATfile: The file containing the detection values in binary float format. %fs: The sample rate of the signal in Hertz. %chunkSize: The chunk size used to compute the detection values in seconds. [x, tx] = readPCM(PCMfile, fs); [d, td] = readDetection(DATfile, fs, chunkSize); plot(tx, x, td, d);
github
JamesLinus/webrtc-master
apmtest.m
.m
webrtc-master/modules/audio_processing/test/apmtest.m
9,874
utf_8
17ad6af59f6daa758d983dd419e46ff0
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function apmtest(task, testname, filepath, casenumber, legacy) %APMTEST is a tool to process APM file sets and easily display the output. % APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs: % 'test' Processes the files to produce test output. % 'list' Prints a list of cases in the test set, preceded by their % CASENUMBERs. % 'show' Uses spclab to show the test case specified by the % CASENUMBER parameter. % % using a set of test files determined by TESTNAME: % 'all' All tests. % 'apm' The standard APM test set (default). % 'apmm' The mobile APM test set. % 'aec' The AEC test set. % 'aecm' The AECM test set. % 'agc' The AGC test set. % 'ns' The NS test set. % 'vad' The VAD test set. % % FILEPATH specifies the path to the test data files. % % CASENUMBER can be used to select a single test case. Omit CASENUMBER, % or set to zero, to use all test cases. % if nargin < 5 || isempty(legacy) % Set to true to run old VQE recordings. legacy = false; end if nargin < 4 || isempty(casenumber) casenumber = 0; end if nargin < 3 || isempty(filepath) filepath = 'data/'; end if nargin < 2 || isempty(testname) testname = 'all'; end if nargin < 1 || isempty(task) task = 'test'; end if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show') error(['TASK ' task ' is not recognized']); end if casenumber == 0 && strcmp(task, 'show') error(['CASENUMBER must be specified for TASK ' task]); end inpath = [filepath 'input/']; outpath = [filepath 'output/']; refpath = [filepath 'reference/']; if strcmp(testname, 'all') tests = {'apm','apmm','aec','aecm','agc','ns','vad'}; else tests = {testname}; end if legacy progname = './test'; else progname = './process_test'; end global farFile; global nearFile; global eventFile; global delayFile; global driftFile; if legacy farFile = 'vqeFar.pcm'; nearFile = 'vqeNear.pcm'; eventFile = 'vqeEvent.dat'; delayFile = 'vqeBuf.dat'; driftFile = 'vqeDrift.dat'; else farFile = 'apm_far.pcm'; nearFile = 'apm_near.pcm'; eventFile = 'apm_event.dat'; delayFile = 'apm_delay.dat'; driftFile = 'apm_drift.dat'; end simulateMode = false; nErr = 0; nCases = 0; for i=1:length(tests) simulateMode = false; if strcmp(tests{i}, 'apm') testdir = ['apm/']; outfile = ['out']; if legacy opt = ['-ec 1 -agc 2 -nc 2 -vad 3']; else opt = ['--no_progress -hpf' ... ' -aec --drift_compensation -agc --fixed_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apm-swb') simulateMode = true; testdir = ['apm-swb/']; outfile = ['out']; if legacy opt = ['-fs 32000 -ec 1 -agc 2 -nc 2']; else opt = ['--no_progress -fs 32000 -hpf' ... ' -aec --drift_compensation -agc --adaptive_digital' ... ' -ns --ns_moderate -vad']; end elseif strcmp(tests{i}, 'apmm') testdir = ['apmm/']; outfile = ['out']; opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ... '--ns_moderate']; else error(['TESTNAME ' tests{i} ' is not recognized']); end inpathtest = [inpath testdir]; outpathtest = [outpath testdir]; refpathtest = [refpath testdir]; if ~exist(inpathtest,'dir') error(['Input directory ' inpathtest ' does not exist']); end if ~exist(refpathtest,'dir') warning(['Reference directory ' refpathtest ' does not exist']); end [status, errMsg] = mkdir(outpathtest); if (status == 0) error(errMsg); end [nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ... progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy); if strcmp(task, 'test') || strcmp(task, 'show') system(['rm ' farFile]); system(['rm ' nearFile]); if simulateMode == false system(['rm ' eventFile]); system(['rm ' delayFile]); system(['rm ' driftFile]); end end end if ~strcmp(task, 'list') if nErr == 0 fprintf(1, '\nAll files are bit-exact to reference\n', nErr); else fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr); end end function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ... outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ... legacy) global farFile; global nearFile; global eventFile; global delayFile; global driftFile; dirs = dir(inpath); nDirs = 0; nErrOut = nErr; for i=3:length(dirs) % skip . and .. nDirs = nDirs + dirs(i).isdir; end if nDirs == 0 nCases = nCases + 1; if casenumber == nCases || casenumber == 0 if strcmp(task, 'list') fprintf([num2str(nCases) '. ' outfile '\n']) else vadoutfile = ['vad_' outfile '.dat']; outfile = [outfile '.pcm']; % Check for VAD test vadTest = 0; if ~isempty(findstr(opt, '-vad')) vadTest = 1; if legacy opt = [opt ' ' outpath vadoutfile]; else opt = [opt ' --vad_out_file ' outpath vadoutfile]; end end if exist([inpath 'vqeFar.pcm']) system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]); elseif exist([inpath 'apm_far.pcm']) system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]); end if exist([inpath 'vqeNear.pcm']) system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]); elseif exist([inpath 'apm_near.pcm']) system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]); end if exist([inpath 'vqeEvent.dat']) system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]); elseif exist([inpath 'apm_event.dat']) system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]); end if exist([inpath 'vqeBuf.dat']) system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]); elseif exist([inpath 'apm_delay.dat']) system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]); end if exist([inpath 'vqeSkew.dat']) system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]); elseif exist([inpath 'vqeDrift.dat']) system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]); elseif exist([inpath 'apm_drift.dat']) system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]); end if simulateMode == false command = [progname ' -o ' outpath outfile ' ' opt]; else if legacy inputCmd = [' -in ' nearFile]; else inputCmd = [' -i ' nearFile]; end if exist([farFile]) if legacy inputCmd = [' -if ' farFile inputCmd]; else inputCmd = [' -ir ' farFile inputCmd]; end end command = [progname inputCmd ' -o ' outpath outfile ' ' opt]; end % This prevents MATLAB from using its own C libraries. shellcmd = ['bash -c "unset LD_LIBRARY_PATH;']; fprintf([command '\n']); [status, result] = system([shellcmd command '"']); fprintf(result); fprintf(['Reference file: ' refpath outfile '\n']); if vadTest == 1 equal_to_ref = are_files_equal([outpath vadoutfile], ... [refpath vadoutfile], ... 'int8'); if ~equal_to_ref nErr = nErr + 1; end end [equal_to_ref, diffvector] = are_files_equal([outpath outfile], ... [refpath outfile], ... 'int16'); if ~equal_to_ref nErr = nErr + 1; end if strcmp(task, 'show') % Assume the last init gives the sample rate of interest. str_idx = strfind(result, 'Sample rate:'); fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17)); fprintf('Using %d Hz\n', fs); if exist([farFile]) spclab(fs, farFile, nearFile, [refpath outfile], ... [outpath outfile], diffvector); %spclab(fs, diffvector); else spclab(fs, nearFile, [refpath outfile], [outpath outfile], ... diffvector); %spclab(fs, diffvector); end end end end else for i=3:length(dirs) if dirs(i).isdir [nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ... refpath,[outfile '_' dirs(i).name], progname, opt, ... simulateMode, nErr, nCases, task, casenumber, legacy); end end end nErrOut = nErr; function [are_equal, diffvector] = ... are_files_equal(newfile, reffile, precision, diffvector) are_equal = false; diffvector = 0; if ~exist(newfile,'file') warning(['Output file ' newfile ' does not exist']); return end if ~exist(reffile,'file') warning(['Reference file ' reffile ' does not exist']); return end fid = fopen(newfile,'rb'); new = fread(fid,inf,precision); fclose(fid); fid = fopen(reffile,'rb'); ref = fread(fid,inf,precision); fclose(fid); if length(new) ~= length(ref) warning('Reference is not the same length as output'); minlength = min(length(new), length(ref)); new = new(1:minlength); ref = ref(1:minlength); end diffvector = new - ref; if isequal(new, ref) fprintf([newfile ' is bit-exact to reference\n']); are_equal = true; else if isempty(new) warning([newfile ' is empty']); return end snr = snrseg(new,ref,80); fprintf('\n'); are_equal = false; end
github
JamesLinus/webrtc-master
parse_delay_file.m
.m
webrtc-master/modules/audio_coding/neteq/test/delay_tool/parse_delay_file.m
6,405
utf_8
4cc70d6f90e1ca5901104f77a7e7c0b3
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function outStruct = parse_delay_file(file) fid = fopen(file, 'rb'); if fid == -1 error('Cannot open file %s', file); end textline = fgetl(fid); if ~strncmp(textline, '#!NetEQ_Delay_Logging', 21) error('Wrong file format'); end ver = sscanf(textline, '#!NetEQ_Delay_Logging%d.%d'); if ~all(ver == [2; 0]) error('Wrong version of delay logging function') end start_pos = ftell(fid); fseek(fid, -12, 'eof'); textline = fgetl(fid); if ~strncmp(textline, 'End of file', 21) error('File ending is not correct. Seems like the simulation ended abnormally.'); end fseek(fid,-12-4, 'eof'); Npackets = fread(fid, 1, 'int32'); fseek(fid, start_pos, 'bof'); rtpts = zeros(Npackets, 1); seqno = zeros(Npackets, 1); pt = zeros(Npackets, 1); plen = zeros(Npackets, 1); recin_t = nan*ones(Npackets, 1); decode_t = nan*ones(Npackets, 1); playout_delay = zeros(Npackets, 1); optbuf = zeros(Npackets, 1); fs_ix = 1; clock = 0; ts_ix = 1; ended = 0; late_packets = 0; fs_now = 8000; last_decode_k = 0; tot_expand = 0; tot_accelerate = 0; tot_preemptive = 0; while not(ended) signal = fread(fid, 1, '*int32'); switch signal case 3 % NETEQ_DELAY_LOGGING_SIGNAL_CLOCK clock = fread(fid, 1, '*float32'); % keep on reading batches of M until the signal is no longer "3" % read int32 + float32 in one go % this is to save execution time temp = [3; 0]; M = 120; while all(temp(1,:) == 3) fp = ftell(fid); temp = fread(fid, [2 M], '*int32'); end % back up to last clock event fseek(fid, fp - ftell(fid) + ... (find(temp(1,:) ~= 3, 1 ) - 2) * 2 * 4 + 4, 'cof'); % read the last clock value clock = fread(fid, 1, '*float32'); case 1 % NETEQ_DELAY_LOGGING_SIGNAL_RECIN temp_ts = fread(fid, 1, 'uint32'); if late_packets > 0 temp_ix = ts_ix - 1; while (temp_ix >= 1) && (rtpts(temp_ix) ~= temp_ts) % TODO(hlundin): use matlab vector search instead? temp_ix = temp_ix - 1; end if temp_ix >= 1 % the ts was found in the vector late_packets = late_packets - 1; else temp_ix = ts_ix; ts_ix = ts_ix + 1; end else temp_ix = ts_ix; ts_ix = ts_ix + 1; end rtpts(temp_ix) = temp_ts; seqno(temp_ix) = fread(fid, 1, 'uint16'); pt(temp_ix) = fread(fid, 1, 'int32'); plen(temp_ix) = fread(fid, 1, 'int16'); recin_t(temp_ix) = clock; case 2 % NETEQ_DELAY_LOGGING_SIGNAL_FLUSH % do nothing case 4 % NETEQ_DELAY_LOGGING_SIGNAL_EOF ended = 1; case 5 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE last_decode_ts = fread(fid, 1, 'uint32'); temp_delay = fread(fid, 1, 'uint16'); k = find(rtpts(1:(ts_ix - 1))==last_decode_ts,1,'last'); if ~isempty(k) decode_t(k) = clock; playout_delay(k) = temp_delay + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end case 6 % NETEQ_DELAY_LOGGING_SIGNAL_CHANGE_FS fsvec(fs_ix) = fread(fid, 1, 'uint16'); fschange_ts(fs_ix) = last_decode_ts; fs_now = fsvec(fs_ix); fs_ix = fs_ix + 1; case 7 % NETEQ_DELAY_LOGGING_SIGNAL_MERGE_INFO playout_delay(last_decode_k) = playout_delay(last_decode_k) ... + fread(fid, 1, 'int32'); case 8 % NETEQ_DELAY_LOGGING_SIGNAL_EXPAND_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_expand = tot_expand + temp / (fs_now / 1000); end case 9 % NETEQ_DELAY_LOGGING_SIGNAL_ACCELERATE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_accelerate = tot_accelerate + temp / (fs_now / 1000); end case 10 % NETEQ_DELAY_LOGGING_SIGNAL_PREEMPTIVE_INFO temp = fread(fid, 1, 'int32'); if last_decode_k ~= 0 tot_preemptive = tot_preemptive + temp / (fs_now / 1000); end case 11 % NETEQ_DELAY_LOGGING_SIGNAL_OPTBUF optbuf(last_decode_k) = fread(fid, 1, 'int32'); case 12 % NETEQ_DELAY_LOGGING_SIGNAL_DECODE_ONE_DESC last_decode_ts = fread(fid, 1, 'uint32'); k = ts_ix - 1; while (k >= 1) && (rtpts(k) ~= last_decode_ts) % TODO(hlundin): use matlab vector search instead? k = k - 1; end if k < 1 % packet not received yet k = ts_ix; rtpts(ts_ix) = last_decode_ts; late_packets = late_packets + 1; end decode_t(k) = clock; playout_delay(k) = fread(fid, 1, 'uint16') + ... 5 * fs_now / 8000; % add overlap length last_decode_k = k; end end fclose(fid); outStruct = struct(... 'ts', rtpts, ... 'sn', seqno, ... 'pt', pt,... 'plen', plen,... 'arrival', recin_t,... 'decode', decode_t,... 'fs', fsvec(:),... 'fschange_ts', fschange_ts(:),... 'playout_delay', playout_delay,... 'tot_expand', tot_expand,... 'tot_accelerate', tot_accelerate,... 'tot_preemptive', tot_preemptive,... 'optbuf', optbuf);
github
JamesLinus/webrtc-master
plot_neteq_delay.m
.m
webrtc-master/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m
5,967
utf_8
cce342fed6406ef0f12d567fe3ab6eef
% % Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. % function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin) % InfoStruct = plot_neteq_delay(delayfile) % InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds) % % Henrik Lundin, 2006-11-17 % Henrik Lundin, 2011-05-17 % try s = parse_delay_file(delayfile); catch error(lasterr); end delayskip=0; noplot=0; arg_ptr=1; delaypoints=[]; s.sn=unwrap_seqno(s.sn); while arg_ptr+1 <= nargin switch lower(varargin{arg_ptr}) case {'skipdelay', 'delayskip'} % skip a number of seconds in the beginning when calculating delays delayskip = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; case 'noplot' noplot=1; arg_ptr = arg_ptr + 1; case {'get_delay', 'getdelay'} % return a vector of delay values for the points in the given vector delaypoints = varargin{arg_ptr+1}; arg_ptr = arg_ptr + 2; otherwise warning('Unknown switch %s\n', varargin{arg_ptr}); arg_ptr = arg_ptr + 1; end end % find lost frames that were covered by one-descriptor decoding one_desc_ix=find(isnan(s.arrival)); for k=1:length(one_desc_ix) ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts))); s.sn(one_desc_ix(k))=s.sn(ix)+1; s.pt(one_desc_ix(k))=s.pt(ix); s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix); end % remove duplicate received frames that were never decoded (RED codec) if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts))) ix=find(isfinite(s.decode)); s.sn=s.sn(ix); s.ts=s.ts(ix); s.arrival=s.arrival(ix); s.playout_delay=s.playout_delay(ix); s.pt=s.pt(ix); s.optbuf=s.optbuf(ix); plen=plen(ix); s.decode=s.decode(ix); end % find non-unique sequence numbers [~,un_ix]=unique(s.sn); nonun_ix=setdiff(1:length(s.sn),un_ix); if ~isempty(nonun_ix) warning('RTP sequence numbers are in error'); end % sort vectors [s.sn,sort_ix]=sort(s.sn); s.ts=s.ts(sort_ix); s.arrival=s.arrival(sort_ix); s.decode=s.decode(sort_ix); s.playout_delay=s.playout_delay(sort_ix); s.pt=s.pt(sort_ix); send_t=s.ts-s.ts(1); if length(s.fs)<1 warning('No info about sample rate found in file. Using default 8000.'); s.fs(1)=8000; s.fschange_ts(1)=min(s.ts); elseif s.fschange_ts(1)>min(s.ts) s.fschange_ts(1)=min(s.ts); end end_ix=length(send_t); for k=length(s.fs):-1:1 start_ix=find(s.ts==s.fschange_ts(k)); send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000; s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000; s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000; end_ix=start_ix-1; end tot_time=max(send_t)-min(send_t); seq_ix=s.sn-min(s.sn)+1; send_t=send_t+max(min(s.arrival-send_t),0); plot_send_t=nan*ones(max(seq_ix),1); plot_send_t(seq_ix)=send_t; plot_nw_delay=nan*ones(max(seq_ix),1); plot_nw_delay(seq_ix)=s.arrival-send_t; cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID if noplot==0 h=plot(plot_send_t/1000,plot_nw_delay); set(h,'color',0.75*[1 1 1]); hold on if any(s.optbuf~=0) peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix); h1=plot(send_t(cng_ix(peak_ix))/1000,... s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),... 'r.'); h2=plot(send_t(cng_ix(no_peak_ix))/1000,... s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),... 'g.'); set([h1, h2],'markersize',1) end %h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix)); h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix)); set(h,'linew',1.5); hold off ax1=axis; axis tight ax2=axis; axis([ax2(1:3) ax1(4)]) end % calculate delays and other parameters delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 ); use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames... intersect(find(isfinite(s.decode)),... % ... that did arrive ... (delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix)); neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix)); Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1; nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack; neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack; delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,... 'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,... 'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),... 'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,... 'filename',delayfile,'units','ms','fs',unique(s.fs)); if not(isempty(delaypoints)) delayvalues=interp1(send_t(cng_ix),... s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),... delaypoints,'nearest',NaN); else delayvalues=[]; end % SUBFUNCTIONS % function y=unwrap_seqno(x) jumps=find(abs((diff(x)-1))>65000); while ~isempty(jumps) n=jumps(1); if x(n+1)-x(n) < 0 % negative jump x(n+1:end)=x(n+1:end)+65536; else % positive jump x(n+1:end)=x(n+1:end)-65536; end jumps=find(abs((diff(x(n+1:end))-1))>65000); end y=x; return;
github
JamesLinus/webrtc-master
rtpAnalyze.m
.m
webrtc-master/tools_webrtc/matlab/rtpAnalyze.m
7,892
utf_8
46e63db0fa96270c14a0c205bbab42e4
function rtpAnalyze( input_file ) %RTP_ANALYZE Analyze RTP stream(s) from a txt file % The function takes the output from the command line tool rtp_analyze % and analyzes the stream(s) therein. First, process your rtpdump file % through rtp_analyze (from command line): % $ out/Debug/rtp_analyze my_file.rtp my_file.txt % Then load it with this function (in Matlab): % >> rtpAnalyze('my_file.txt') % Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. % % Use of this source code is governed by a BSD-style license % that can be found in the LICENSE file in the root of the source % tree. An additional intellectual property rights grant can be found % in the file PATENTS. All contributing project authors may % be found in the AUTHORS file in the root of the source tree. [SeqNo,TimeStamp,ArrTime,Size,PT,M,SSRC] = importfile(input_file); %% Filter out RTCP packets. % These appear as RTP packets having payload types 72 through 76. ix = not(ismember(PT, 72:76)); fprintf('Removing %i RTCP packets\n', length(SeqNo) - sum(ix)); SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); %% Find streams. [uSSRC, ~, uix] = unique(SSRC); % If there are multiple streams, select one and purge the other % streams from the data vectors. If there is only one stream, the % vectors are good to use as they are. if length(uSSRC) > 1 for i=1:length(uSSRC) uPT = unique(PT(uix == i)); fprintf('%i: %s (%d packets, pt: %i', i, uSSRC{i}, ... length(find(uix==i)), uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf(')\n'); end sel = input('Select stream number: '); if sel < 1 || sel > length(uSSRC) error('Out of range'); end ix = find(uix == sel); % This is where the data vectors are trimmed. SeqNo = SeqNo(ix); TimeStamp = TimeStamp(ix); ArrTime = ArrTime(ix); Size = Size(ix); PT = PT(ix); M = M(ix); SSRC = SSRC(ix); end %% Unwrap SeqNo and TimeStamp. SeqNoUW = maxUnwrap(SeqNo, 65535); TimeStampUW = maxUnwrap(TimeStamp, 4294967295); %% Generate some stats for the stream. fprintf('Statistics:\n'); fprintf('SSRC: %s\n', SSRC{1}); uPT = unique(PT); if length(uPT) > 1 warning('This tool cannot yet handle changes in codec sample rate'); end fprintf('Payload type(s): %i', uPT(1)); if length(uPT) > 1 fprintf(', %i', uPT(2:end)); end fprintf('\n'); fprintf('Packets: %i\n', length(SeqNo)); SortSeqNo = sort(SeqNoUW); fprintf('Missing sequence numbers: %i\n', ... length(find(diff(SortSeqNo) > 1))); fprintf('Duplicated packets: %i\n', length(find(diff(SortSeqNo) == 0))); reorderIx = findReorderedPackets(SeqNoUW); fprintf('Reordered packets: %i\n', length(reorderIx)); tsdiff = diff(TimeStampUW); tsdiff = tsdiff(diff(SeqNoUW) == 1); [utsdiff, ~, ixtsdiff] = unique(tsdiff); fprintf('Common packet sizes:\n'); for i = 1:length(utsdiff) fprintf(' %i samples (%i%%)\n', ... utsdiff(i), ... round(100 * length(find(ixtsdiff == i))/length(ixtsdiff))); end %% Trying to figure out sample rate. fs_est = (TimeStampUW(end) - TimeStampUW(1)) / (ArrTime(end) - ArrTime(1)); fs_vec = [8, 16, 32, 48]; fs = 0; for f = fs_vec if abs((fs_est-f)/f) < 0.05 % 5% margin fs = f; break; end end if fs == 0 fprintf('Cannot determine sample rate. I get it to %.2f kHz\n', ... fs_est); fs = input('Please, input a sample rate (in kHz): '); else fprintf('Sample rate estimated to %i kHz\n', fs); end SendTimeMs = (TimeStampUW - TimeStampUW(1)) / fs; fprintf('Stream duration at sender: %.1f seconds\n', ... (SendTimeMs(end) - SendTimeMs(1)) / 1000); fprintf('Stream duration at receiver: %.1f seconds\n', ... (ArrTime(end) - ArrTime(1)) / 1000); fprintf('Clock drift: %.2f%%\n', ... 100 * ((ArrTime(end) - ArrTime(1)) / ... (SendTimeMs(end) - SendTimeMs(1)) - 1)); fprintf('Sent average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (SendTimeMs(end)-SendTimeMs(1)))); fprintf('Received average bitrate: %i kbps\n', ... round(sum(Size) * 8 / (ArrTime(end)-ArrTime(1)))); %% Plots. delay = ArrTime - SendTimeMs; delay = delay - min(delay); delayOrdered = delay; delayOrdered(reorderIx) = nan; % Set reordered packets to NaN. delayReordered = delay(reorderIx); % Pick the reordered packets. sendTimeMsReordered = SendTimeMs(reorderIx); % Sort time arrays in packet send order. [~, sortix] = sort(SeqNoUW); SendTimeMs = SendTimeMs(sortix); Size = Size(sortix); delayOrdered = delayOrdered(sortix); figure plot(SendTimeMs / 1000, delayOrdered, ... sendTimeMsReordered / 1000, delayReordered, 'r.'); xlabel('Send time [s]'); ylabel('Relative transport delay [ms]'); title(sprintf('SSRC: %s', SSRC{1})); SendBitrateKbps = 8 * Size(1:end-1) ./ diff(SendTimeMs); figure plot(SendTimeMs(1:end-1)/1000, SendBitrateKbps); xlabel('Send time [s]'); ylabel('Send bitrate [kbps]'); end %% Subfunctions. % findReorderedPackets returns the index to all packets that are considered % old compared with the largest seen sequence number. The input seqNo must % be unwrapped for this to work. function reorderIx = findReorderedPackets(seqNo) largestSeqNo = seqNo(1); reorderIx = []; for i = 2:length(seqNo) if seqNo(i) < largestSeqNo reorderIx = [reorderIx; i]; %#ok<AGROW> else largestSeqNo = seqNo(i); end end end %% Auto-generated subfunction. function [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = ... importfile(filename, startRow, endRow) %IMPORTFILE Import numeric data from a text file as column vectors. % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME) Reads % data from text file FILENAME for the default selection. % % [SEQNO,TIMESTAMP,SENDTIME,SIZE,PT,M,SSRC] = IMPORTFILE(FILENAME, % STARTROW, ENDROW) Reads data from rows STARTROW through ENDROW of text % file FILENAME. % % Example: % [SeqNo,TimeStamp,SendTime,Size,PT,M,SSRC] = % importfile('rtpdump_recv.txt',2, 123); % % See also TEXTSCAN. % Auto-generated by MATLAB on 2015/05/28 09:55:50 %% Initialize variables. if nargin<=2 startRow = 2; endRow = inf; end %% Format string for each line of text: % column1: double (%f) % column2: double (%f) % column3: double (%f) % column4: double (%f) % column5: double (%f) % column6: double (%f) % column7: text (%s) % For more information, see the TEXTSCAN documentation. formatSpec = '%5f%11f%11f%6f%6f%3f%s%[^\n\r]'; %% Open the text file. fileID = fopen(filename,'r'); %% Read columns of data according to format string. % This call is based on the structure of the file used to generate this % code. If an error occurs for a different file, try regenerating the code % from the Import Tool. dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ... 'Delimiter', '', 'WhiteSpace', '', 'HeaderLines', startRow(1)-1, ... 'ReturnOnError', false); for block=2:length(startRow) frewind(fileID); dataArrayBlock = textscan(fileID, formatSpec, ... endRow(block)-startRow(block)+1, 'Delimiter', '', 'WhiteSpace', ... '', 'HeaderLines', startRow(block)-1, 'ReturnOnError', false); for col=1:length(dataArray) dataArray{col} = [dataArray{col};dataArrayBlock{col}]; end end %% Close the text file. fclose(fileID); %% Post processing for unimportable data. % No unimportable data rules were applied during the import, so no post % processing code is included. To generate code which works for % unimportable data, select unimportable cells in a file and regenerate the % script. %% Allocate imported array to column variable names SeqNo = dataArray{:, 1}; TimeStamp = dataArray{:, 2}; SendTime = dataArray{:, 3}; Size = dataArray{:, 4}; PT = dataArray{:, 5}; M = dataArray{:, 6}; SSRC = dataArray{:, 7}; end
github
Jiankai-Sun/Digital-Image-Processing-master
myMarrHildreth.m
.m
Digital-Image-Processing-master/Problem9/SourceCode/myMarrHildreth.m
2,895
utf_8
b16702e08457d60ca13cf2daf7537f0e
function edges = myMarrHildreth(Image, sigma) % This is a simple implementation of the LoG edge detector. % Image: Gray-level input image % sigma: try values like 1, 2, 4, 8, etc. % edges: Output edge map % Form the LoG filter nLoG = filter_LoG(sigma); % convResult = conv2(double(Image), nLoG, 'same'); % imfilter works better for border pixels (use conv2 above or imfilter below) convResult = imfilter(double(Image), nLoG, 'replicate'); slope = mean( abs(convResult(:)) ); %% Vertical edges % Shift image one pixel to the left and right convLeft = circshift(convResult, [0, -1]); convRight = circshift(convResult, [0, 1]); % The vertical edges (- +, + -, - 0 +, + 0 -) v_edge1 = convResult < 0 & convLeft > 0 & abs(convLeft - convResult) > slope; v_edge2 = convResult < 0 & convRight > 0 & abs(convRight - convResult) > slope; v_edge3 = convResult == 0 & sign(convLeft) ~= sign(convRight) & abs(convLeft - convRight) > slope; v_edge = v_edge1 | v_edge2 | v_edge3; v_edge(:, [1 end]) = 0; %% Horizontal edges % Shift image one pixel to the top and bottom convTop = circshift(convResult, [-1, 0]); convBot = circshift(convResult, [1, 0]); % The horizontal edges (- +, + -, - 0 +, + 0 -) h_edge1 = convResult < 0 & convTop > 0 & abs(convTop - convResult) > slope; h_edge2 = convResult < 0 & convBot > 0 & abs(convBot - convResult) > slope; h_edge3 = convResult == 0 & sign(convTop) ~= sign(convBot) & abs(convTop - convBot) > slope; h_edge = h_edge1 | h_edge2 | h_edge3; h_edge([1 end], :) = 0; % Combine vertical and horizontal edges edges = v_edge | h_edge; end function nLoG = filter_LoG(sigma) % This function generates Laplacian of Gaussian filter given the sigma % parameter as its input. Filter size is estimated by multiplying the % sigma with a constant. %% The function fsize = ceil(sigma) * 5; % filter size is estimated by: sigma * constant fsize = (fsize - 1) / 2; [x, y] = meshgrid(-fsize : fsize, -fsize : fsize); % The two parts of the LoG equation a = (x .^ 2 + y .^ 2 - 2 * sigma ^ 2) / sigma ^ 4; b = exp( - (x .^ 2 + y .^ 2) / (2 * sigma ^ 2) ); b = b / sum(b(:)); % The LoG filter LoG = a .* b; % The normalized LoG filter nLoG = LoG - mean2(LoG); % ** end of the function ** %% Uncomment to display LoG plot % surf(x, y , nLoG); % xlabel('x'); % ylabel('y'); % zlabel('LoG'); % name = ['Laplacian of 2D Gaussian ( \sigma = ' , num2str(sigma), ' )']; % title(name); %% Uncomment to save at output % print(num2str(sigma), '-dpng', '-r400'); return end %% Additionally you can use the following code to overlay edges on the input image % overlay = repmat(Image, 1, [1 3]); % % for i = 1 : size(edges, 1) % for j = 1 : size(edges, 2) % if edges(i, j) % overlay(i, j, :) = [0 255 255]; % end % end % end
github
Jiankai-Sun/Digital-Image-Processing-master
myMarrHildreth5.m
.m
Digital-Image-Processing-master/Problem9/SourceCode/myMarrHildreth5.m
959
utf_8
251c861c08cd746dcd5ca377334d7840
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % my_edgeMarrHildreth.m % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function edgeMagnitude = myMarrHildreth(image, sigma) % Determine filter size N = [sigma x 3] x 2 + 1 and the % size of the image. N = ceil(sigma * 3)*2 + 1; [height, width, ~] = size(image); % Use the laplacian of the gaussian. log = fspecial('log', N, sigma); convolved = double(imfilter(image, log)); % Threshold the image convolved = imbinarize(convolved, 0); padded = padarray(convolved, [1,1], 1); edgeMagnitude = zeros(height, width, 1); % Zero Crossings for i=1:height for j=1:width if (padded(i+1, j+1) == 1) if(padded(i,j+1) == 0 || padded(i+1, j+2) == 0 ||... padded(i+2, j+1) == 0 || padded(i+1, j) == 0) edgeMagnitude(i,j) = 1; end end end end end
github
Jiankai-Sun/Digital-Image-Processing-master
myCanny3.m
.m
Digital-Image-Processing-master/Problem9/SourceCode/myCanny3.m
2,757
utf_8
bced8264db9a7776e98d429eab5e6fa3
function I_temp = myCanny3( w ) % The algorithm parameters: % 1. Parameters of edge detecting filters: % X-axis direction filter: Nx1=10;Sigmax1=1;Nx2=10;Sigmax2=1;Theta1=pi/2; % Y-axis direction filter: Ny1=10;Sigmay1=1;Ny2=10;Sigmay2=1;Theta2=0; % 2. The thresholding parameter alfa: alfa=0.1; subplot(3,2,1); imagesc(w); title('Original Image'); % X-axis direction edge detection subplot(3,2,2); filterx=d2dgauss(Nx1,Sigmax1,Nx2,Sigmax2,Theta1); Ix= conv2(w,filterx,'same'); imagesc(Ix); title('Ix'); % Y-axis direction edge detection subplot(3,2,3) filtery=d2dgauss(Ny1,Sigmay1,Ny2,Sigmay2,Theta2); Iy=conv2(w,filtery,'same'); imagesc(Iy); title('Iy'); % Norm of the gradient (Combining the X and Y directional derivatives) subplot(3,2,4); NVI=sqrt(Ix.*Ix+Iy.*Iy); imagesc(NVI); title('Norm of Gradient'); % Thresholding I_max=max(max(NVI)); I_min=min(min(NVI)); level=alfa*(I_max-I_min)+I_min; subplot(3,2,5); Ibw=max(NVI,level.*ones(size(NVI))); imagesc(Ibw); title('After Thresholding'); % Thinning (Using interpolation to find the pixels where the norms of % gradient are local maximum.) subplot(3,2,6); [n,m]=size(Ibw); for i=2:n-1 for j=2:m-1 if Ibw(i,j) > level X=[-1,0,+1;-1,0,+1;-1,0,+1]; Y=[-1,-1,-1;0,0,0;+1,+1,+1]; Z=[Ibw(i-1,j-1),Ibw(i-1,j),Ibw(i-1,j+1); Ibw(i,j-1),Ibw(i,j),Ibw(i,j+1); Ibw(i+1,j-1),Ibw(i+1,j),Ibw(i+1,j+1)]; XI=[Ix(i,j)/NVI(i,j), -Ix(i,j)/NVI(i,j)]; YI=[Iy(i,j)/NVI(i,j), -Iy(i,j)/NVI(i,j)]; ZI=interp2(X,Y,Z,XI,YI); if Ibw(i,j) >= ZI(1) && Ibw(i,j) >= ZI(2) I_temp(i,j)=I_max; else I_temp(i,j)=I_min; end else I_temp(i,j)=I_min; end end end imagesc(I_temp); title('After Thinning'); colormap(gray); end %%%%%%%%%%%%%% End of the main.m file %%%%%%%%%%%%%%% %%%%%%% The functions used in the main.m file %%%%%%% % Function "d2dgauss.m": % This function returns a 2D edge detector (first order derivative % of 2D Gaussian function) with size n1*n2; theta is the angle that % the detector rotated counter clockwise; and sigma1 and sigma2 are the % standard deviation of the gaussian functions. function h = d2dgauss(n1,sigma1,n2,sigma2,theta) r=[cos(theta) -sin(theta); sin(theta) cos(theta)]; for i = 1 : n2 for j = 1 : n1 u = r * [j-(n1+1)/2 i-(n2+1)/2]'; h(i,j) = gauss(u(1),sigma1)*dgauss(u(2),sigma2); end end h = h / sqrt(sum(sum(abs(h).*abs(h)))); end % Function "gauss.m": function y = gauss(x,std) y = exp(-x^2/(2*std^2)) / (std*sqrt(2*pi)); end % Function "dgauss.m"(first order derivative of gauss function): function y = dgauss(x,std) y = -x * gauss(x,std) / std^2; end %%%%%%%%%%%%%% end of the functions %%%%%%%%%%%%%
github
Jiankai-Sun/Digital-Image-Processing-master
myCanny.m
.m
Digital-Image-Processing-master/Problem9/SourceCode/myCanny.m
2,196
utf_8
c8ead2e036dc8028e672d7cdd42b1532
function outputImg = myCanny(inputImg) [h,w] = size(inputImg); % gaussian blur sigma = round(min(h,w) * 0.005); ksize = ceil(sigma*6); if mod(ksize, 2) == 0 ksize = ksize + 1; end inputImgGaussian = convolutionDouble(inputImg,GaussianFilter(ksize,ksize,sigma)); % sobel SobelKernelX = [-1,0,1; -2,0,2; -1,0,1]; SobelKernelY = [-1,-2,-1; 0,0,0; 1,2,1]; Gx = convolutionDouble(inputImgGaussian, SobelKernelX); Gy = convolutionDouble(inputImgGaussian, SobelKernelY); inputImgSobel = sqrt(Gx.^2 + Gy.^2); alpha = atan(Gy ./ Gx); alpha = round(alpha ./ (pi / 4) + 3); alpha(alpha == 5) = 1; %nonmaxima suppression d1Mask = alpha == 1; d2Mask = alpha == 2; d3Mask = alpha == 3; d4Mask = alpha == 4; paddedMinputImgSobel = padarray(inputImgSobel, [1, 1], 'replicate'); %vertical d1Comp = and(inputImgSobel >= paddedMinputImgSobel(1:h, 2:w+1), inputImgSobel >= paddedMinputImgSobel(3:h+2,2:w+1)); %-pi/4 d2Comp = and(inputImgSobel >= paddedMinputImgSobel(3:h+2, 1:w), inputImgSobel >= paddedMinputImgSobel(1:h, 3:w+2)); %horizon d3Comp = and(inputImgSobel >= paddedMinputImgSobel(2:h+1, 1:w), inputImgSobel >= paddedMinputImgSobel(2:h+1, 3:w+2)); %pi/4 d4Comp = and(inputImgSobel >= paddedMinputImgSobel(1:h, 1:w), inputImgSobel >= paddedMinputImgSobel(3:h+2, 3:w+2)); gN = inputImgSobel .* (and(d1Mask, d1Comp) + and(d2Mask, d2Comp) + and(d3Mask, d3Comp) + and(d4Mask, d4Comp)); sortedOut = sort(reshape( gN, 1, h * w), 'descend'); threshH = sortedOut(1, ceil(h * w * 0.02)); threshL = 1 * threshH; N = 100; set(0,'RecursionLimit',N); for i=1:h for j=1:w if gN(i,j)>threshH &&gN(i,j)~=255 gN(i,j)=255; gN=connect(gN,i,j,threshL); end end end outputImg = uint8(gN); end function [nedge] = connect(nedge,y,x,low) neighbour=[-1 -1;-1 0;-1 1;0 -1;0 1;1 -1;1 0;1 1]; [m, n]=size(nedge); for k=1:8 yy=y+neighbour(k,1); xx=x+neighbour(k,2); if yy>=1 &&yy<=m &&xx>=1 && xx<=n if nedge(yy,xx)>=low && nedge(yy,xx)~=255 nedge(yy,xx)=255; nedge=connect(nedge,yy,xx,low); end end end end
github
Jiankai-Sun/Digital-Image-Processing-master
otsu.m
.m
Digital-Image-Processing-master/Problem9/SourceCode/otsu.m
5,859
utf_8
51c9aaa2aaf3a9a9554b8abe4dc30089
function [IDX,sep] = otsu(I,n) %OTSU Global image thresholding/segmentation using Otsu's method. % IDX = OTSU(I,N) segments the image I into N classes by means of Otsu's % N-thresholding method. OTSU returns an array IDX containing the cluster % indices (from 1 to N) of each point. Zero values are assigned to % non-finite (NaN or Inf) pixels. % % IDX = OTSU(I) uses two classes (N=2, default value). % % [IDX,sep] = OTSU(...) also returns the value (sep) of the separability % criterion within the range [0 1]. Zero is obtained only with data % having less than N values, whereas one (optimal value) is obtained only % with N-valued arrays. % % Notes: % ----- % It should be noticed that the thresholds generally become less credible % as the number of classes (N) to be separated increases (see Otsu's % paper for more details). % % If I is an RGB image, a Karhunen-Loeve transform is first performed on % the three R,G,B channels. The segmentation is then carried out on the % image component that contains most of the energy. % % Example: % ------- % load clown % subplot(221) % X = ind2rgb(X,map); % imshow(X) % title('Original','FontWeight','bold') % for n = 2:4 % IDX = otsu(X,n); % subplot(2,2,n) % imagesc(IDX), axis image off % title(['n = ' int2str(n)],'FontWeight','bold') % end % colormap(gray) % % Reference: % --------- % Otsu N, <a href="matlab:web('http://dx.doi.org/doi:10.1109/TSMC.1979.4310076')">A Threshold Selection Method from Gray-Level Histograms</a>, % IEEE Trans. Syst. Man Cybern. 9:62-66;1979 % % See also GRAYTHRESH, IM2BW % narginchk(1,2) % Check if is the input is an RGB image isRGB = isrgb(I); assert(isRGB | ismatrix(I),... 'The input must be a 2-D array or an RGB image.') %% Checking n (number of classes) if nargin==1 n = 2; elseif n==1 IDX = NaN(size(I)); sep = 0; return elseif n~=abs(round(n)) || n==0 error('MATLAB:otsu:WrongNValue',... 'n must be a strictly positive integer!') elseif n>255 n = 255; warning('MATLAB:otsu:TooHighN',... 'n is too high. n value has been changed to 255.') end I = single(I); %% Perform a KLT if isRGB, and keep the component of highest energy if isRGB sizI = size(I); I = reshape(I,[],3); [V,D] = eig(cov(I)); [~,c] = max(diag(D)); I = reshape(I*V(:,c),sizI(1:2)); % component with the highest energy end %% Convert to 256 levels I = I-min(I(:)); I = round(I/max(I(:))*255); %% Probability distribution unI = sort(unique(I)); nbins = min(length(unI),256); if nbins==n IDX = ones(size(I)); for i = 1:n, IDX(I==unI(i)) = i; end sep = 1; return elseif nbins<n IDX = NaN(size(I)); sep = 0; return elseif nbins<256 [histo,pixval] = hist(I(:),unI); else [histo,pixval] = hist(I(:),256); end P = histo/sum(histo); clear unI %% Zeroth- and first-order cumulative moments w = cumsum(P); mu = cumsum((1:nbins).*P); %% Maximal sigmaB^2 and Segmented image if n==2 sigma2B =... (mu(end)*w(2:end-1)-mu(2:end-1)).^2./w(2:end-1)./(1-w(2:end-1)); [maxsig,k] = max(sigma2B); % segmented image IDX = ones(size(I)); IDX(I>pixval(k+1)) = 2; % separability criterion sep = maxsig/sum(((1:nbins)-mu(end)).^2.*P); elseif n==3 w0 = w; w2 = fliplr(cumsum(fliplr(P))); [w0,w2] = ndgrid(w0,w2); mu0 = mu./w; mu2 = fliplr(cumsum(fliplr((1:nbins).*P))./cumsum(fliplr(P))); [mu0,mu2] = ndgrid(mu0,mu2); w1 = 1-w0-w2; w1(w1<=0) = NaN; sigma2B =... w0.*(mu0-mu(end)).^2 + w2.*(mu2-mu(end)).^2 +... (w0.*(mu0-mu(end)) + w2.*(mu2-mu(end))).^2./w1; sigma2B(isnan(sigma2B)) = 0; % zeroing if k1 >= k2 [maxsig,k] = max(sigma2B(:)); [k1,k2] = ind2sub([nbins nbins],k); % segmented image IDX = ones(size(I))*3; IDX(I<=pixval(k1)) = 1; IDX(I>pixval(k1) & I<=pixval(k2)) = 2; % separability criterion sep = maxsig/sum(((1:nbins)-mu(end)).^2.*P); else k0 = linspace(0,1,n+1); k0 = k0(2:n); [k,y] = fminsearch(@sig_func,k0,optimset('TolX',1)); k = round(k*(nbins-1)+1); % segmented image IDX = ones(size(I))*n; IDX(I<=pixval(k(1))) = 1; for i = 1:n-2 IDX(I>pixval(k(i)) & I<=pixval(k(i+1))) = i+1; end % separability criterion sep = 1-y; end IDX(~isfinite(I)) = 0; %% Function to be minimized if n>=4 function y = sig_func(k) muT = sum((1:nbins).*P); sigma2T = sum(((1:nbins)-muT).^2.*P); k = round(k*(nbins-1)+1); k = sort(k); if any(k<1 | k>nbins), y = 1; return, end k = [0 k nbins]; sigma2B = 0; for j = 1:n wj = sum(P(k(j)+1:k(j+1))); if wj==0, y = 1; return, end muj = sum((k(j)+1:k(j+1)).*P(k(j)+1:k(j+1)))/wj; sigma2B = sigma2B + wj*(muj-muT)^2; end y = 1-sigma2B/sigma2T; % within the range [0 1] end end function isRGB = isrgb(A) % --- Do we have an RGB image? % RGB images can be only uint8, uint16, single, or double isRGB = ndims(A)==3 && (isfloat(A) || isa(A,'uint8') || isa(A,'uint16')); % ---- Adapted from the obsolete function ISRGB ---- if isRGB && isfloat(A) % At first, just test a small chunk to get a possible quick negative mm = size(A,1); nn = size(A,2); chunk = A(1:min(mm,10),1:min(nn,10),:); isRGB = (min(chunk(:))>=0 && max(chunk(:))<=1); % If the chunk is an RGB image, test the whole image if isRGB, isRGB = (min(A(:))>=0 && max(A(:))<=1); end end end
github
Jiankai-Sun/Digital-Image-Processing-master
myReconstruction.m
.m
Digital-Image-Processing-master/Problem8/SourceCode/myReconstruction.m
1,330
utf_8
f5f1a39b90159153219ddbd6249dff36
%% Self defined function for opening by reconstruction % function recon1 = myReconstruction( marker, mask ) % % se = strel('square', 3); % se = ones(3, 3); % recon1 = marker; % recon1_old = zeros(size(recon1)); % while (sum(sum(recon1 - recon1_old)) ~= 0) % % Retain output of previous iteration % recon1_old = recon1; % % Perform dilation % % recon1 = imdilate(recon1, se); % % The following command is slow. If you want to have better % % performance, uncomment the above `recon1 = imdilate(recon1, se);` % % and use `se = strel('square', 3);` % recon1 = myDilate(recon1, se); % % Restrict the dialated values using the mask % bw = recon1 > mask; % recon1(bw) = mask(bw); % end % end function [ h ] = myReconstruction( f, g, B ) % Implementation of morphlogical operation called reconstruction narginchk(1,3); nargoutchk(1,1); if ~islogical(f) || ~islogical(g) error('f, g must be logical matrix'); end if nargin == 2 B = logical([0, 1, 0; 1, 1, 1; 0, 1, 0]); end h = f; htmp = f; flag = false; while (~flag) h = logical(myDilate(htmp, B) .* g); flag = 1-any(any(h - htmp)); htmp = h; end end
github
Jiankai-Sun/Digital-Image-Processing-master
myHoleFill3.m
.m
Digital-Image-Processing-master/Problem8/SourceCode/myHoleFill3.m
11,431
utf_8
df8610f8bc88bb1dad620088a4293cd6
%% Self defined function for hole filling function [ g ] = myHoleFill( f) narginchk(1,1); if ~islogical(f) f = imbinarize(f); end fc = logical(1 - f); [r, s] = size(f); fm = false(r, s); for i = 1:r for j= 1:s if i==1 || i==r || j==1 || j==s fm(i,j) = 1 - f(i,j); end end end g = myReconstruction(fm, fc); g = logical(1-g); g = logical((double(f)+double(g))>0); end % The following function has a better performance % function [I2,locations] = myHoleFill(varargin) % %IMFILL Fill image regions and holes. % % BW2 = IMFILL(BW1,LOCATIONS) performs a flood-fill operation on % % background pixels of the input binary image BW1, starting from the % % points specified in LOCATIONS. LOCATIONS can be a P-by-1 vector, in % % which case it contains the linear indices of the starting locations. % % LOCATIONS can also be a P-by-NDIMS(IM1) matrix, in which case each row % % contains the array indices of one of the starting locations. % % % % BW2 = IMFILL(BW1,'holes') fills holes in the input image. A hole is % % a set of background pixels that cannot be reached by filling in the % % background from the edge of the image. % % % % I2 = IMFILL(I1) fills holes in an intensity image, I1. In this % % case a hole is an area of dark pixels surrounded by lighter pixels. % % % % Interactive Use % % --------------- % % BW2 = IMFILL(BW1) displays BW1 on the screen and lets you select the % % starting locations using the mouse. Use normal button clicks to add % % points. Press <BACKSPACE> or <DELETE> to remove the previously selected % % point. A shift-click, right-click, or double-click selects a final % % point and then starts the fill; pressing <RETURN> finishes the selection % % without adding a point. Interactive use is supported only for 2-D images. % % % % The syntax [BW2,LOCATIONS] = IMFILL(BW1) can be used to get the starting % % points selected using the mouse. The output LOCATIONS is always in the % % form of a vector of linear indices into the input image. % % % % Specifying Connectivity % % ----------------------- % % By default, IMFILL uses 4-connected background neighbors for 2-D % % inputs and 6-connected background neighbors for 3-D inputs. For % % higher dimensions the default background connectivity is % % CONNDEF(NUM_DIMS,'minimal'). You can override the default % % connectivity with these syntaxes: % % % % BW2 = IMFILL(BW1,LOCATIONS,CONN) % % BW2 = IMFILL(BW1,CONN,'holes') % % I2 = IMFILL(I1,CONN) % % % % To override the default connectivity and interactively specify the % % starting locations, use this syntax: % % % % BW2 = IMFILL(BW1,0,CONN) % % % % CONN may have the following scalar values: % % % % 4 two-dimensional four-connected neighborhood % % 8 two-dimensional eight-connected neighborhood % % 6 three-dimensional six-connected neighborhood % % 18 three-dimensional 18-connected neighborhood % % 26 three-dimensional 26-connected neighborhood % % % % Connectivity may be defined in a more general way for any dimension by % % using for CONN a 3-by-3-by- ... -by-3 matrix of 0s and 1s. The 1-valued % % elements define neighborhood locations relative to the center element of % % CONN. CONN must be symmetric about its center element. % % % % Class Support % % ------------- % % The input image can be numeric or logical, and it must be real and % % nonsparse. It can have any dimension. The output image has the % % same class as the input image. % % % % Examples % % -------- % % Fill in the background of a binary image from a specified starting % % location: % % % % BW1 = logical([1 0 0 0 0 0 0 0 % % 1 1 1 1 1 0 0 0 % % 1 0 0 0 1 0 1 0 % % 1 0 0 0 1 1 1 0 % % 1 1 1 1 0 1 1 1 % % 1 0 0 1 1 0 1 0 % % 1 0 0 0 1 0 1 0 % % 1 0 0 0 1 1 1 0]); % % BW2 = imfill(BW1,[3 3],8) % % % % Fill in the holes of a binary image: % % % % BW4 = imbinarize(imread('coins.png')); % % BW5 = imfill(BW4,'holes'); % % figure, imshow(BW4), figure, imshow(BW5) % % % % Fill in the holes of an intensity image: % % % % I = imread('tire.tif'); % % I2 = imfill(I); % % figure, imshow(I), figure, imshow(I2) % % % % See also BWSELECT, GRAYCONNECTED, IMRECONSTRUCT, REGIONFILL. % % % Grandfathered syntaxes: % % IMFILL(I1,'holes') - no longer necessary to use 'holes' % % IMFILL(I1,CONN,'holes') - no longer necessary to use 'holes' % % % Testing notes % % ============= % % I - real, full, nonsparse, numeric array, any dimension % % - Infs OK % % - NaNs not allowed % % % % CONN - valid connectivity specifier % % % % LOCATIONS - the value 0 is used as a flag to indicate interactive % % selection % % - can be either a P-by-1 double vector containing % % valid linear indices into the input image, or a % % P-by-ndims(I) array. In the second case, each row % % of LOCATIONS must contain a set of valid array indices % % into the input image. % % - can be empty. % % % % 'holes' - match is case-insensitive; partial match allowed. % % % % If 'holes' argument is not provided, then the input image must be % % binary. % % [I,locations,conn,do_fillholes] = parse_inputs(varargin{:}); % % if do_fillholes % if islogical(I) % mask = uint8(I); % else % mask = I; % end % mask = padarray(mask, ones(1,ndims(mask)), -Inf, 'both'); % mask = imcomplement(mask); % marker = mask; % % idx = cell(1,ndims(I)); % for k = 1:ndims(I) % idx{k} = 2:(size(marker,k) - 1); % end % marker(idx{:}) = -Inf; % % I2 = imreconstruct(marker, mask, conn); % I2 = imcomplement(I2); % I2 = I2(idx{:}); % % if islogical(I) % I2 = logical(I2); % end % % else % mask = imcomplement(I); % marker = false(size(mask)); % marker(locations) = mask(locations); % marker = imreconstruct(marker, mask, conn); % I2 = I | marker; % end % % %%% % %%% Subfunction ParseInputs % %%% % function [IM,locations,conn,do_fillholes] = parse_inputs(varargin) % % narginchk(1,3); % % IM = varargin{1}; % validateattributes(IM, {'numeric' 'logical'}, {'nonsparse' 'real','nonnan'}, ... % mfilename, 'I1 or BW1', 1); % % do_interactive = false; % do_fillholes = false; % % conn = conndef(ndims(IM),'minimal'); % do_conn_check = false; % % locations = []; % do_location_check = false; % % switch nargin % case 1 % if islogical(IM) % % IMFILL(BW1) % do_interactive = true; % else % % IMFILL(I1) % do_fillholes = true; % end % % case 2 % if islogical(IM) % if ischar(varargin{2}) % % IMFILL(BW1, 'holes') % validatestring(varargin{2}, {'holes'}, mfilename, 'OPTION', 2); % do_fillholes = true; % % else % % IMFILL(BW1, LOCATIONS) % locations = varargin{2}; % do_location_check = true; % end % % else % if ischar(varargin{2}) % % IMFILL(I1, 'holes') % validatestring(varargin{2}, {'holes'}, mfilename, 'OPTION', 2); % do_fillholes = true; % % else % % IMFILL(I1, CONN) % conn = varargin{2}; % do_conn_check = true; % conn_position = 2; % do_fillholes = true; % end % % end % % case 3 % if islogical(IM) % if ischar(varargin{3}) % % IMFILL(BW1,CONN,'holes') % validatestring(varargin{3}, {'holes'}, mfilename, 'OPTION', 3); % do_fillholes = true; % conn = varargin{2}; % do_conn_check = true; % conn_position = 2; % % else % if isequal(varargin{2}, 0) % % IMFILL(BW1,0,CONN) % do_interactive = true; % conn = varargin{3}; % do_conn_check = true; % conn_position = 2; % % else % % IMFILL(BW1,LOCATIONS,CONN) % locations = varargin{2}; % do_location_check = true; % conn = varargin{3}; % do_conn_check = true; % conn_position = 3; % end % % end % % else % % IMFILL(I1,CONN,'holes') % validatestring(varargin{3}, {'holes'}, mfilename, 'OPTION', 3); % do_fillholes = true; % conn = varargin{2}; % do_conn_check = true; % conn_position = 2; % end % end % % if do_conn_check % iptcheckconn(conn, mfilename, 'CONN', conn_position); % end % % if do_location_check % locations = check_locations(locations, size(IM)); % elseif do_interactive % locations = get_locations_interactively(IM); % end % % % Convert to linear indices if necessary. % if ~do_fillholes && (size(locations,2) ~= 1) % idx = cell(1,ndims(IM)); % for k = 1:ndims(IM) % idx{k} = locations(:,k); % end % locations = sub2ind(size(IM), idx{:}); % end % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function locations = check_locations(locations, image_size) % % Checks validity of LOCATIONS. Converts LOCATIONS to linear index % % form. Warns if any locations are out of range. % % validateattributes(locations, {'double'}, {'real' 'positive' 'integer' '2d'}, ... % mfilename, 'LOCATIONS', 2); % % num_dims = length(image_size); % if (size(locations,2) ~= 1) && (size(locations,2) ~= num_dims) % error(message('images:imfill:badLocationSize', iptnum2ordinal( 2 ))); % end % % if size(locations,2) == 1 % bad_pix = (locations < 1) | (locations > prod(image_size)); % else % bad_pix = zeros(size(locations,1),1); % for k = 1:num_dims % bad_pix = bad_pix | ((locations(:,k) < 1) | ... % (locations(:,k) > image_size(k))); % end % end % % if any(bad_pix) % warning(message('images:imfill:outOfRange')); % locations(bad_pix,:) = []; % end % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % function locations = get_locations_interactively(BW) % % Display image and give user opportunity to select locations with the mouse. % % if ~ismatrix(BW) % error(message('images:imfill:badInteractiveDimension')) % end % % if isempty(BW) % error(message('images:imfill:emptyImage')) % end % % imshow(BW) % [xi,yi] = getpts; % c = round(axes2pix(size(BW,2), [1 size(BW,2)], xi)); % r = round(axes2pix(size(BW,1), [1 size(BW,1)], yi)); % locations = sub2ind(size(BW),r,c);
github
Jiankai-Sun/Digital-Image-Processing-master
chainCode.m
.m
Digital-Image-Processing-master/Problem10/SourceCode/chainCode.m
8,576
utf_8
3ed31c4b670992c84d111a6949064fee
function c = chainCode(b, conn, dir) % CHAINCODE Computes the Freeman chain code of a boundary. % C = FCHCODE(B) computes the 8-connected Freeman chain code of a % set of 2-D coordinate pairs contained in B, an np-by-2 array. C % is a structure with the following fields: % % c.fcc = Freeman chain code (1-by-np) % c.diff = First difference of code c.fcc (1-by-np) % c.mm = Integer of minimum magnitude from c.fcc (1-by-np) % c.diffmm = First difference of code c.mm (1-by-np) % c.x0y0 = Coordinates where the code starts (1-by-2) % % C = FCHCODE(B, CONN) produces the same outputs as above, but % with the code connectivity specified in CONN. CONN can be 8 for % an 8-connected chain code, or CONN can be 4 for a 4-connected % chain code. Specifying CONN=4 is valid only if the input % sequence, B, contains transitions with values 0, 2, 4, and 6, % exclusively. % % C = FHCODE(B, CONN, DIR) produces the same outputs as above, but, % in addition, the desired code direction is specified. Values for % DIR can be: % % 'same' Same as the order of the sequence of points in b. % This is the default. % % 'reverse' Outputs the code in the direction opposite to the % direction of the points in B. The starting point % for each DIR is the same. % % The elements of B are assumed to correspond to a 1-pixel-thick, % fully-connected, closed boundary. B cannot contain duplicate % coordinate pairs, except in the first and last positions, which % is a common feature of boundary tracing programs. % % FREEMAN CHAIN CODE REPRESENTATION % The table on the left shows the 8-connected Freeman chain codes % corresponding to allowed deltax, deltay pairs. An 8-chain is % converted to a 4-chain if (1) if conn = 4; and (2) only % transitions 0, 2, 4, and 6 occur in the 8-code. Note that % dividing 0, 2, 4, and 6 by 2 produce the 4-code. % % ----------------------- ---------------- % deltax | deltay | 8-code corresp 4-code % ----------------------- ---------------- % 0 1 0 0 % -1 1 1 % -1 0 2 1 % -1 -1 3 % 0 -1 4 2 % 1 -1 5 % 1 0 6 3 % 1 1 7 % ----------------------- ---------------- % % The formula z = 4*(deltax + 2) + (deltay + 2) gives the following % sequence corresponding to rows 1-8 in the preceding table: z = % 11,7,6,5,9,13,14,15. These values can be used as indices into the % table, improving the speed of computing the chain code. The % preceding formula is not unique, but it is based on the smallest % integers (4 and 2) that are powers of 2. % Preliminaries. if nargin == 1 dir = 'same'; conn = 8; elseif nargin == 2 dir = 'same'; elseif nargin == 3 % Nothing to do here. else error('Incorrect number of inputs.') end [np, nc] = size(b); if np < nc error('B must be of size np-by-2.'); end % Some boundary tracing programs, such as boundaries.m, output a % sequence in which the coordinates of the first and last points are % the same. If this is the case, eliminate the last point. if isequal(b(1, :), b(np, :)) np = np - 1; b = b(1:np, :); end % Build the code table using the single indices from the formula % for z given above: C(11)=0; C(7)=1; C(6)=2; C(5)=3; C(9)=4; C(13)=5; C(14)=6; C(15)=7; % End of Preliminaries. % Begin processing. x0 = b(1, 1); y0 = b(1, 2); c.x0y0 = [x0, y0]; % Make sure the coordinates are organized sequentially: % Get the deltax and deltay between successive points in b. The % last row of a is the first row of b. a = circshift(b, [-1, 0]); % DEL = a - b is an nr-by-2 matrix in which the rows contain the % deltax and deltay between successive points in b. The two % components in the kth row of matrix DEL are deltax and deltay % between point (xk, yk) and (xk+1, yk+1). The last row of DEL % contains the deltax and deltay between (xnr, ynr) and (x1, y1), % (i.e., between the last and first points in b). DEL = a - b; % If the abs value of either (or both) components of a pair % (deltax, deltay) is greater than 1, then by definition the curve % is broken (or the points are out of order), and the program % terminates. if any(abs(DEL(:, 1)) > 1) || any(abs(DEL(:, 2)) > 1) error('The input curve is broken or points are out of order.') end % Create a single index vector using the formula described above. z = 4*(DEL(:, 1) + 2) + (DEL(:, 2) + 2); % Use the index to map into the table. The following are % the Freeman 8-chain codes, organized in a 1-by-np array. fcc = C(z); % Check if direction of code sequence needs to be reversed. if strcmp(dir, 'reverse') fcc = coderev(fcc); % See below for function coderev. end % If 4-connectivity is specified, check that all components % of fcc are 0, 2, 4, or 6. if conn == 4 val = find(fcc == 1 | fcc == 3 | fcc == 5 | fcc ==7, 1 ); if isempty(val) fcc = fcc./2; else warning('The specified 4-connected code cannot be satisfied.') end end % Freeman chain code for structure output. c.fcc = fcc; % Obtain the first difference of fcc. c.diff = codediff(fcc,conn); % See below for function codediff. % Obtain code of the integer of minimum magnitude. c.mm = minmag(fcc); % See below for function minmag. % Obtain the first difference of fcc c.diffmm = codediff(c.mm, conn); %-------------------------------------------------------------------% function cr = coderev(fcc) % Traverses the sequence of 8-connected Freeman chain code fcc in % the opposite direction, changing the values of each code % segment. The starting point is not changed. fcc is a 1-by-np % array. % Flip the array left to right. This redefines the starting point % as the last point and reverses the order of "travel" through the % code. cr = fliplr(fcc); % Next, obtain the new code values by traversing the code in the % opposite direction. (0 becomes 4, 1 becomes 5, ... , 5 becomes 1, % 6 becomes 2, and 7 becomes 3). ind1 = find(0 <= cr & cr <= 3); ind2 = find(4 <= cr & cr <= 7); cr(ind1) = cr(ind1) + 4; cr(ind2) = cr(ind2) - 4; %-------------------------------------------------------------------% function z = minmag(c) %MINMAG Finds the integer of minimum magnitude in a chain code. % Z = MINMAG(C) finds the integer of minimum magnitude in a given % 4- or 8-connected Freeman chain code, C. The code is assumed to % be a 1-by-np array. % The integer of minimum magnitude starts with min(c), but there % may be more than one such value. Find them all, I = find(c == min(c)); % and shift each one left so that it starts with min(c). J = 0; A = zeros(length(I), length(c)); for k = I J = J + 1; A(J, :) = circshift(c,[0 -(k-1)]); end % Matrix A contains all the possible candidates for the integer of % minimum magnitude. Starting with the 2nd column, succesively find % the minima in each column of A. The number of candidates decreases % as the seach moves to the right on A. This is reflected in the % elements of J. When length(J)=1, one candidate remains. This is % the integer of minimum magnitude. [M, N] = size(A); J = (1:M)'; for k = 2:N D(1:M, 1) = Inf; D(J, 1) = A(J, k); amin = min(A(J, k)); J = find(D(:, 1) == amin); if length(J)==1 z = A(J, :); return end end %-------------------------------------------------------------------% function d = codediff(fcc, conn) %CODEDIFF Computes the first difference of a chain code. % D = CODEDIFF(FCC) computes the first difference of code, FCC. The % code FCC is treated as a circular sequence, so the last element % of D is the difference between the last and first elements of % FCC. The input code is a 1-by-np vector. % % The first difference is found by counting the number of direction % changes (in a counter-clockwise direction) that separate two % adjacent elements of the code. sr = circshift(fcc, [0, -1]); % Shift input left by 1 location. delta = sr - fcc; d = delta; I = find(delta < 0); type = conn; switch type case 4 % Code is 4-connected d(I) = d(I) + 4; case 8 % Code is 8-connected d(I) = d(I) + 8; end
github
Jiankai-Sun/Digital-Image-Processing-master
wavefast.m
.m
Digital-Image-Processing-master/Problem7/SourceCode/wavefast.m
5,094
utf_8
d143429208f8cb9eec34c5878f14a892
function [ c, s ] = wavefast( x, n, varargin ) %WAVEFAST Computes the FWT of a '3-D extended' 2-D array % [C, L] = WAVEFAST(X, N, LP, HP) computes 'PAGES' 2D N-level % FWTs of a 'ROWS x COLUMNS x PAGES' matrix X with respect to % decomposition filters LP and HP. % % [C, L] = WAVEFAST(X, N, WNAME) performs the same operation but % fetches filters LP and HP for wavelet WNAME using WAVEFILTER % % Scale parameter N must be less than or equal to log2 of the % maximum image dimension. Filters LP and HP must be even. To % reduce border distortion, X is symmetrically extended. That is, % if X = [c1 c2 c3 ... cn] (in 1D), then its symmetric extension % would be [... c3 c2 c1 c1 c2 c3 ... cn cn cn-1 cn-2 ...]. % % OUTPUTS: % Vector C is a coefficient decomposition vector: % % C = [a1(n) ... ak(n) h1(n) ... hk(n) v1(n) ... vk(n) % d1(n) ... dk(n) h1(n-1) ... d1(1) ... dk(1)] % % where ai, hi, vi, and di for i = 0, 1, ... k are columnwise % vectors containing approximation, horizontal, vertical, and % diagonal coefficient matrices, respectively, and k is the % number of pages in the 3-D extended array X. C has 3n + 1 % sections where n is the number of wavelet decompositions. % % Matrix S is an [(n+2) x 2] bookkeeping matrix if k = 1; % else it is [(n+2) x 3]; % % S = [ sa(n, :); sd(n, :); sd(n-1, :); ... ; sd(1, :); sx ] % % where sa and sd are approximation and detail size entries. % % See also WAVEFAST and WAVEFILTER % Check the input arguments for reasonableness. narginchk(3, 4); if nargin == 3 if ischar(varargin{1}) [lp, hp] = wavefilter(varargin{1}, 'd'); else error('Missing wavelet name.'); end else lp = varargin{1}; hp = varargin{2}; end % Get the filter length, 'lp', input array size, 'sx', and number of % pages, 'pages', in extended 2-D array x. fl = length(lp); sx = size(x); pages = size(x, 3); if ((~ismatrix(x)) && (ndims(x) ~= 3)) || (min(sx) < 2) ... || ~isreal(x) || ~isnumeric(x) error('X must be a real, numeric 2-D or 3-D matrix.'); end if (~ismatrix(lp)) || ~isreal(lp) || ~isnumeric(lp) ... || (~ismatrix(hp)) || ~isreal(hp) || ~isnumeric(hp) ... || (fl ~= length(hp)) || rem(fl, 2) ~= 0 error(['LP and HP must be even and equal length real, ' ... 'numeric filter vectors.']); end if ~isreal(n) || ~isnumeric(n) || (n < 1) || (n > log2(max(sx))) error(['N must be a real scalar between 1 and ' ... 'log2(max(size((X))).']); end % Init the starting output data structures and initial approximation. c = []; s = sx(1:2); app = cell(pages, 1); for i = 1:pages app{i} = double(x(:, :, i)); end % For each decomposition ... for i = 1:n % Extend the approximation symmetrically. [app, keep] = symextend(app, fl, pages); % Convolve rows with HP and downsample. Then convolve columns % with HP and LP to get the diagonal and vertical coefficients. rows = symconv(app, hp, 'row', fl, keep, pages); coefs = symconv(rows, hp, 'col', fl, keep, pages); c = addcoefs(c, coefs, pages); s = [size(coefs{1}); s]; coefs = symconv(rows, lp, 'col', fl, keep, pages); c = addcoefs(c, coefs, pages); % Convolve rows with LP and downsample. Then convolve columns % with HP and LP to get the horizontal and next approximation % coeffcients. rows = symconv(app, lp, 'row', fl, keep, pages); coefs = symconv(rows, hp, 'col', fl, keep, pages); c = addcoefs(c, coefs, pages); app = symconv(rows, lp, 'col', fl, keep, pages); end % Append the final approximation structures. c = addcoefs(c, app, pages); s = [size(app{1});s]; if ~ismatrix(x) s(:, 3) = size(x, 3); end end % -------------------------------------------------------------------------% function nc = addcoefs(c, x, pages) % Add 'pages' array coefficients to the wavelet decomposition vector. nc = c; for i = pages: -1 :1 nc = [x{i}(:)' nc]; end end % -------------------------------------------------------------------------% function [y, keep] = symextend(x, fl, pages) % Compute the number of coefficients to keep after convolution and % downsampling. Then extend the 'pages' arrays of x in both % dimensions. y = cell(pages, 1); for i = 1:pages keep = floor((fl + size(x{i}) - 1) / 2); y{i} = padarray(x{i}, [(fl - 1) (fl - 1)], 'symmetric', 'both'); end end % -------------------------------------------------------------------------% function y =symconv(x, h, type, fl, keep, pages) % For the 'pages' 2-D arrays in x, convolve the rows or columns with % h , downsample, and extract the center section since symmetrically % extended. y = cell(pages, 1); for i = 1:pages if strcmp(type, 'row') y{i} = conv2(x{i}, h); y{i} = y{i}(:, 1:2:end); y{i} = y{i}(:, fl / 2 + 1:fl / 2 + keep(2)); else y{i} = conv2(x{i}, h'); y{i} = y{i}(1:2:end, :); y{i} = y{i}(fl / 2 + 1 : fl / 2 + keep(1), :); end end end
github
Jiankai-Sun/Digital-Image-Processing-master
waveback.m
.m
Digital-Image-Processing-master/Problem7/SourceCode/waveback.m
4,489
utf_8
92a54874b3ac290b1071b5c812768816
function [ varargout ] = waveback( c, s, varargin ) %WAVEBACK Computes inverse FWTs for multi-level decomposition [C, S]. % [VARARGOUT] = WAVEBACK(C, S, VARARGOUT) performs a 2D N-level % partial or complete wavelet reconstruction of decomposition % structure [C, S]; % % SYNTAX: % Y = WAVEBACK(C, S, 'WNAME'); Output inverse FWT matrix Y % Y = WAVEBACK(C, S, LR, HR); using lowpass and highpass % reconstruction filters (LR and % HR) or filters obtained by % calling WAVEFILTER with 'WNAME'. % % [NC, NS] = WAVEBACK(C, S, 'WNAME', N); Output new wavelet % [NC, NS] = WAVEBACK(C, S, LR, HR, N); decomposition structure % [NC, NS] after N step % reconstruction. % % See also WAVEFAST and WAVEFILTER. % Check the input and output arguments for reasonableness. narginchk(3, 5); nargoutchk(1, 2); if(~ismatrix(c)) || (size(c, 1) ~= 1) error('C must be a row vector.'); end if(~ismatrix(s)) || ~isreal(s) || ~isnumeric(s) || ... ((size(s, 2) ~= 2) && (size(s, 2) ~= 3)) error('S must be a real, numeric two- or three-column array.'); end elements = prod(s, 2); if(length(c) < elements(end)) || ... ~(elements(1) + 3 * sum(elements(2:end - 1)) >= elements(end)) error('[C S] must be a standard wavelet decomposition structure.'); end % Maximum levels in [C, S]. nmax = size(s, 1) - 2; % Get third input parameter and init check flags. wname = varargin{1}; filterchk = 0; nchk = 0; switch nargin case 3 if ischar(wname) [lp, hp] = wavefilter(wname, 'r'); n = nmax; else error('Undefined filter.'); end if nargout ~= 1 error('Wrong number of output arguments.'); end case 4 if ischar(wname) [lp, hp] = wavefilter(wname, 'r'); n = varargin{2}; nchk = 1; else lp = varargin{1}; hp = varargin{2}; filterchk = 1; n = nmax; if nargout ~= 1 error('Wrong number of output arguments.'); end end case 5 lp = varargin{1}; hp = varargin{2}; filterchk = 1; n = varargin{3}; nchk = 1; otherwise error('Improper number of input arguments.'); end fl = length(lp); if filterchk % Check filters. if (~ismatrix(lp)) || ~isreal(lp) || ~isnumeric(lp) ... || (~ismatrix(hp)) || ~isreal(hp) || ~isnumeric(hp) ... || (fl ~= length(hp)) || rem(fl, 2) ~= 0 error('LP and HP must be even and equal length real, numeric filter vectors.'); end end if nchk && (~isnumeric(n) || ~isreal(n)) % Check scale N. error('N must be a real numeric.'); end if (n > nmax) || (n < 1) error('Invalid number (N) of reconstructions requested.'); end if (n ~= nmax) && (nargout ~= 2) error('Not enough output arguments.'); end nc = c; ns = s; nnmax = nmax; % Init decomposition. for i = 1:n % Compute a new approximation. a = symconvup(wavecopy('a', nc, ns), lp, lp, fl, ns(3, :)) + ... symconvup(wavecopy('h', nc, ns, nnmax), hp, lp, fl, ns(3, :)) + ... symconvup(wavecopy('v', nc, ns, nnmax), lp, hp, fl, ns(3, :)) + ... symconvup(wavecopy('d', nc, ns, nnmax), hp, hp, fl, ns(3, :)); % Update decomposition. nc = nc(4 * prod(ns(1, :)) + 1:end); nc = [a(:)' nc]; ns = ns(3:end, :); ns = [ns(1, :); ns]; nnmax = size(ns, 1) - 2; end % For complete reconstructions, reformat output as 2-D. if nargout == 1 a = nc; nc = zeros(ns(1, :)); nc(:) = a; end varargout{1} = nc; if nargout == 2 varargout{2} = ns; end end % ------------------------------------------------------------------------ % function w = symconvup(x, f1, f2, fln, keep) % Upsample rows and convolve columns with f1; upsample columns and % convolve rows with f2; then extract center assuming symmetrical % extension % Process each "page" (i.e., 3rd index) of an extended 2-D array % seperately; if 'x' is 2-D, size(x, 3) = 1. % Preallocate w. zi = fln - 1: fln + keep(1) - 2; zj = fln - 1: fln + keep(2) - 2; w = zeros(numel(zi), numel(zj), size(x, 3)); for i = 1:size(x, 3) y = zeros([2 1] .* size(x(:, :, i))); y(1:2:end, :) = x(:, :, i); y = conv2(y, f1'); z = zeros([1 2] .* size(y)); z(:, 1:2:end) = y; z = conv2(z,f2); z = z(zi, zj); w(:, :, i) = z; end end
github
nrodrig4/Matlab-Codes-Vapor-Droplet-Evaporation-master
optimizedPolyFit.m
.m
Matlab-Codes-Vapor-Droplet-Evaporation-master/optimizedPolyFit.m
12,255
utf_8
8ef8e3cf54c6f074bdf74b45d20da862
function [resultsOutput,new_results_Size] = optimizedPolyFit(app,z_length,z_loc,mu,compound,M,C_v,R,x_spacing,noise_IA,rootdir,SpacingOption,powers,Fitting,error_rel_rms,error_rel2_rms,RMSresults) for i = 1:z_length for j = 1:length(powers) r_max = 50; z_o = z_loc(i); power = powers(j); SavesFolder = [rootdir,'/z_',num2str(z_o)]; mkdir(SavesFolder) RMSdetails = [SavesFolder,'/RMS_details.txt']; RMS_mod_details = [SavesFolder,'/RMS_mod_details.txt']; neg_analytical_C = [SavesFolder,'/Neg_analytical_vals.txt']; data = IA_minus_Concentration_mod(noise_IA,z_o,mu,M,C_v,R,SavesFolder,x_spacing); if SpacingOption ~= 'Analytical..' C_f = 0.0166%2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... %5sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) r = 50; x_loc = 0:0.5:50; for n = 1:length(x_loc) x_o = x_loc(n); a = sqrt(r^2-x_o^2); fun = @(t) compute_C(t,C_v,x_o,z_o,R,C_f); % disp('int1') solution = integral(fun,-a,a); %line integral along the y-direction % disp('int2') %unit? if(solution==0) RampToZeroLocation = x_o; break; end %solution = solution*1000/(1*10^6*M)*mu-(2.0*rand(size(solution))-1*ones(size(solution)))*noise_IA; %unit? end data = addRamping(data,RampToZeroLocation); end results=Variable_Fitting_CT_NR_OP(data,z_o,compound,power,SavesFolder,mu,Fitting); results_tmp = find(results(:,1)<35 + 1e-5 & results(:,1)>-eps); new_results_Size = [results_tmp(1) results_tmp(end)]; %still have all the points from CT analysis resultsOutput(:,i) = results(:,2)/(1/(1*10^3*M)); t1=results(new_results_Size(1):new_results_Size(2),1); rw = r_max; %sqrt(50^2 - z_o^2); %%%assume that C(r,50) is also zero (= C(50,z)) z_oo = 0; C_f = 2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) temp = zeros(size(t1)); rel_rms = zeros(size(temp)); rel2_rms = []; count = 0; neg_ana_C = []; for k = 1:length(t1) x_o=t1(k); temp(k) = (2*C_v./pi*atan(R./(sqrt(0.5*(x_o.^2+z_o.^2-R.^2 + sqrt((x_o.^2+z_o.^2 ... -R.^2).^2 + 4*z_o.^2*R^2)))))-C_f)*1/(1*10^3*M);%units mole/cm^3 rel_rms(k) = (results(new_results_Size(1)+k-1,2)-temp(k))/temp(k); if (temp(k) > 0.0) && (x_o < r_max + 1e-5) rel2_rms = [rel2_rms;rel_rms(k)]; end end error_tmp = [t1 results(new_results_Size(1):new_results_Size(2),2) temp rel_rms]; %%%compute RMS error error_rel_rms_power(j) = 100*sqrt(mean(rel_rms.^2)); error_rel2_rms_power(j) = 100*sqrt(mean(rel2_rms.^2)) %error_tmp = [z_o count error_rel_rms(i) error_rel2_rms(i)]; %save(RMSresults,'error_tmp','-ascii','-append') TextAreaText{j} = ['z = ',num2str(z_o),', Power = ',num2str(power),', RMS = ',num2str(error_rel2_rms_power(j)),'%'] [LowestRMS2,powerIndex2] = min(error_rel2_rms_power); %[LowestRMS1,powerIndex1] = min(error_rel_rms_power); error_rel2_rms(i) = LowestRMS2 %error_rel_rms(i) = LowestRMS1; %error_tmp = [z_o count error_rel_rms(i) error_rel2_rms(i)]; optimalPower(i) = powers(powerIndex2); %error_rel_rms_power(i) = LowestRMS1; OP = optimalPower(i); optimalPowerForZ{i} = ['Power ',num2str(OP),' for z = ',num2str(z_o)] app.FittingCTRMSTextArea.Value = [TextAreaText';optimalPowerForZ{i}]; clc; close all; clearvars -except j i select_PFitcase new_results_Size p_val sm_val z_loc ... choice p_length z_length power M C_v R mu dirext rootdir z_o gs TextAreaText ... SavesFolder resultsOutput results C_f compound s_choice sm_length noise_flag powers.... x_spacing resultPos data SpacingOption Spacing GridFit noise_IA Fitting app RMSresults... optimalPower optimalPowerForZ error_rel_rms error_tmp error_rel2_rms error_rel2_rms_power; end clear error_rel2_rms_power; TextAreaText = {}; optimalPowerForZ{i} averageRMS = ['Average RMS = ',num2str(sum(error_rel2_rms)/length(error_rel2_rms))] app.FittingCTRMSTextArea.Value = [optimalPowerForZ';averageRMS]; end for i = 1:z_length r_max = 50; z_o = z_loc(i); power = optimalPower(i); SavesFolder = [rootdir,'/z_',num2str(z_o)]; mkdir(SavesFolder) RMSdetails = [SavesFolder,'/RMS_details.txt']; RMS_mod_details = [SavesFolder,'/RMS_mod_details.txt']; neg_analytical_C = [SavesFolder,'/Neg_analytical_vals.txt']; data = IA_minus_Concentration_mod(noise_IA,z_o,mu,M,C_v,R,SavesFolder,x_spacing); ax = app.UIAxes; app.UIAxes_2.NextPlot = 'replacechildren'; fig=figure; title(app.UIAxes, ['IA output: z = ',num2str(z_o)]) xlabel(app.UIAxes, 'X') ylabel(app.UIAxes, 'IA') scatter(ax,data(:,1),data(:,2)); saveIAScatterFigure(data,SavesFolder,z_o) if SpacingOption ~= 'Analytical..' C_f = 0.0166%2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... %5sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) r = 50; x_loc = 0:0.5:50; for n = 1:length(x_loc) x_o = x_loc(n); a = sqrt(r^2-x_o^2); fun = @(t) compute_C(t,C_v,x_o,z_o,R,C_f); %disp('int1') solution = integral(fun,-a,a); %line integral along the y-direction %disp('int2') %unit? if(solution==0) RampToZeroLocation = x_o; break; end %solution = solution*1000/(1*10^6*M)*mu-(2.0*rand(size(solution))-1*ones(size(solution)))*noise_IA; %unit? end data = addRamping(data,RampToZeroLocation); end ax = app.UIAxes; fig=figure; title(app.UIAxes, ['IA output: z = ',num2str(z_o)]) xlabel(app.UIAxes, 'X') ylabel(app.UIAxes, 'IA') scatter(ax,data(:,1),data(:,2)); saveIAScatterFigure(data,SavesFolder,z_o); % Starting PolyFit and CT results=Variable_Fitting_CT_NR(app,data,z_o,compound,power,SavesFolder,mu,Fitting); results_tmp = find(results(:,1)<35 + 1e-5 & results(:,1)>-eps); new_results_Size = [results_tmp(1) results_tmp(end)]; %still have all the points from CT analysis resultsOutput(:,i) = results(:,2)/(1/(1*10^3*M)); fresults = [SavesFolder,'/CT_results_z_',num2str(z_o),'.mat']; save(fresults,'resultsOutput') t1=results(new_results_Size(1):new_results_Size(2),1); rw = r_max; %sqrt(50^2 - z_o^2); %%%assume that C(r,50) is also zero (= C(50,z)) z_oo = 0; C_f = 2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) temp = zeros(size(t1)); rel_rms = zeros(size(temp)); rel2_rms = []; count = 0; neg_ana_C = []; for j = 1:length(t1) x_o=t1(j); temp(j) = (2*C_v./pi*atan(R./(sqrt(0.5*(x_o.^2+z_o.^2-R.^2 + sqrt((x_o.^2+z_o.^2 ... -R.^2).^2 + 4*z_o.^2*R^2)))))-C_f)*1/(1*10^3*M);%units mole/cm^3 rel_rms(j) = (results(new_results_Size(1)+j-1,2)-temp(j))/temp(j); if (temp(j) > 0.0) && (x_o < r_max + 1e-5) rel2_rms = [rel2_rms;rel_rms(j)]; end end % results(:,2) % pause error_tmp = [t1 results(new_results_Size(1):new_results_Size(2),2) temp rel_rms]; save(RMSdetails,'error_tmp','-ascii') save(RMS_mod_details,'rel2_rms','-ascii') if (count>0) save(neg_analytical_C,'neg_ana_C','-ascii') end %%%compute RMS error error_rel_rms(i) = 100*sqrt(mean(rel_rms.^2)); error_rel2_rms(i) = 100*sqrt(mean(rel2_rms.^2)); error_tmp = [z_o count error_rel_rms(i) error_rel2_rms(i)]; save(RMSresults,'error_tmp','-ascii','-append') errorCalc(i) = error_rel2_rms(i); TextAreaText{i} = ['z = ',num2str(z_o),', RMS = ',num2str(error_rel2_rms(i)),'%']; averageRMS = ['Average RMS = ',num2str(sum(errorCalc)/length(errorCalc)),'%']; TextAreaText Location = ['Location ',num2str(i),' of ',num2str(z_length)]; averageRMS = ['Average RMS = ',num2str(sum(errorCalc)/length(errorCalc))]; app.FittingCTRMSTextArea.Value = [optimalPowerForZ';Location;averageRMS]; ax = app.UIAxes_2; fig=figure; scatter(ax,results(:,1),results(:,2),'o'); ax.NextPlot = 'add'; scatter(ax,t1,temp,'x') if (count>0) scatter(ax,neg_ana_C(:,1),neg_ana_C(:,2),'+','MarkerEdgeColor',[0 0 0],'LineWidth',1) end xlabel(ax,'r axis [mm]'); ylabel(ax,'C(r,z) [mole/cm^3]'); if (count>0) legend(ax,'Fitted Solution', 'Exact Solution','Org. Neg. Analyt. Sol') else legend(ax,'Fitted Solution', 'Exact Solution') end title(ax,{['z = ',num2str(z_o),', Rel RMS (org.) = ',num2str(error_rel_rms(i)),'%, Rel RMS (mod.) = ',num2str(error_rel2_rms(i)),'%'];... [' # points with neg analytical conc. = ',num2str(count)]}); xlim(ax,[0 r_max]); saveCTComparison(results,temp,z_o,t1,SavesFolder,neg_ana_C,error_rel_rms(i),count,error_rel2_rms(i),r_max); clc; close all; clearvars -except j i select_PFitcase new_results_Size p_val sm_val z_loc optimalPower... choice p_length z_length power M C_v R mu dirext rootdir z_o gs TextAreaText... SavesFolder resultsOutput results C_f compound s_choice sm_length noise_flag powers optimalPowerForZ.... x_spacing resultPos data SpacingOption Spacing GridFit noise_IA Fitting app RMSresults errorCalc; end end function fun = compute_C(t,C_v,x_o,z_o,R,C_f) fun = 2.*C_v./pi.*atan(R./(sqrt(0.5.*(x_o.^2+t.^2+z_o.^2-R.^2+ ... sqrt((x_o.^2+t.^2+z_o.^2-R.^2).^2+4.*z_o.^2.*R.^2)))))-C_f; %t represents y coordinates if (fun < 0.0) fun = 0.0*fun; end end
github
nrodrig4/Matlab-Codes-Vapor-Droplet-Evaporation-master
normalIA_and_CT.m
.m
Matlab-Codes-Vapor-Droplet-Evaporation-master/normalIA_and_CT.m
6,876
utf_8
a6784cf14d20c8ab8f728198ebc3c66d
function [resultsOutput,new_results_Size] = normalIA_and_CT(app,z_length,z_loc,mu,compound,M,C_v,R,x_spacing,noise_IA,rootdir,SpacingOption,power,Fitting,error_rel_rms,error_rel2_rms,RMSresults) for i = 1:z_length r_max = 50; z_o = z_loc(i); SavesFolder = [rootdir,'/z_',num2str(z_o)]; mkdir(SavesFolder) RMSdetails = [SavesFolder,'/RMS_details.txt']; RMS_mod_details = [SavesFolder,'/RMS_mod_details.txt']; neg_analytical_C = [SavesFolder,'/Neg_analytical_vals.txt']; data = IA_minus_Concentration_mod(noise_IA,z_o,mu,M,C_v,R,SavesFolder,x_spacing); ax = app.UIAxes; app.UIAxes_2.NextPlot = 'replacechildren'; fig=figure; title(app.UIAxes, ['IA output: z = ',num2str(z_o)]) xlabel(app.UIAxes, 'X') ylabel(app.UIAxes, 'IA') scatter(ax,data(:,1),data(:,2)); saveIAScatterFigure(data,SavesFolder,z_o) if SpacingOption ~= 'Analytical..' C_f = 0.0166%2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... %5sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) r = 50; x_loc = 0:0.5:50; for j = 1:length(x_loc) x_o = x_loc(j); a = sqrt(r^2-x_o^2); fun = @(t) compute_C(t,C_v,x_o,z_o,R,C_f); %disp('int1') solution = integral(fun,-a,a); %line integral along the y-direction %disp('int2') %unit? if(solution==0) RampToZeroLocation = x_o; break; end %solution = solution*1000/(1*10^6*M)*mu-(2.0*rand(size(solution))-1*ones(size(solution)))*noise_IA; %unit? end data = addRamping(data,RampToZeroLocation); end ax = app.UIAxes; fig=figure; title(app.UIAxes, ['IA output: z = ',num2str(z_o)]) xlabel(app.UIAxes, 'X') ylabel(app.UIAxes, 'IA') scatter(ax,data(:,1),data(:,2)); saveIAScatterFigure(data,SavesFolder,z_o); % Starting PolyFit and CT results=Variable_Fitting_CT_NR(app,data,z_o,compound,power,SavesFolder,mu,Fitting); results_tmp = find(results(:,1)<35 + 1e-5 & results(:,1)>-eps); new_results_Size = [results_tmp(1) results_tmp(end)]; %still have all the points from CT analysis resultsOutput(:,i) = results(:,2)/(1/(1*10^3*M)); fresults = [SavesFolder,'/CT_results_z_',num2str(z_o),'.mat']; save(fresults,'resultsOutput') t1=results(new_results_Size(1):new_results_Size(2),1); rw = r_max; %sqrt(50^2 - z_o^2); %%%assume that C(r,50) is also zero (= C(50,z)) z_oo = 0; C_f = 2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))); %analytical C at (rw,z_oo) temp = zeros(size(t1)); rel_rms = zeros(size(temp)); rel2_rms = []; count = 0; neg_ana_C = []; for j = 1:length(t1) x_o=t1(j); temp(j) = (2*C_v./pi*atan(R./(sqrt(0.5*(x_o.^2+z_o.^2-R.^2 + sqrt((x_o.^2+z_o.^2 ... -R.^2).^2 + 4*z_o.^2*R^2)))))-C_f)*1/(1*10^3*M);%units mole/cm^3 rel_rms(j) = (results(new_results_Size(1)+j-1,2)-temp(j))/temp(j); if (temp(j) > 0.0) && (x_o < r_max + 1e-5) rel2_rms = [rel2_rms;rel_rms(j)]; end end % results(:,2) % pause error_tmp = [t1 results(new_results_Size(1):new_results_Size(2),2) temp rel_rms]; save(RMSdetails,'error_tmp','-ascii') save(RMS_mod_details,'rel2_rms','-ascii') if (count>0) save(neg_analytical_C,'neg_ana_C','-ascii') end %%%compute RMS error error_rel_rms(i) = 100*sqrt(mean(rel_rms.^2)); error_rel2_rms(i) = 100*sqrt(mean(rel2_rms.^2)); error_tmp = [z_o count error_rel_rms(i) error_rel2_rms(i)]; save(RMSresults,'error_tmp','-ascii','-append') errorCalc(i) = error_rel2_rms(i); TextAreaText{i} = ['z = ',num2str(z_o),', RMS = ',num2str(error_rel2_rms(i)),'%']; averageRMS = ['Average RMS = ',num2str(sum(errorCalc)/length(errorCalc)),'%']; TextAreaText averageRMS = ['Average RMS = ',num2str(sum(errorCalc)/length(errorCalc))]; app.FittingCTRMSTextArea.Value = [TextAreaText';averageRMS]; ax = app.UIAxes_2; fig=figure; scatter(ax,results(:,1),results(:,2),'o'); ax.NextPlot = 'add'; scatter(ax,t1,temp,'x') if (count>0) scatter(ax,neg_ana_C(:,1),neg_ana_C(:,2),'+','MarkerEdgeColor',[0 0 0],'LineWidth',1) end xlabel(ax,'r axis [mm]'); ylabel(ax,'C(r,z) [mole/cm^3]'); if (count>0) legend(ax,'Fitted Solution', 'Exact Solution','Org. Neg. Analyt. Sol') else legend(ax,'Fitted Solution', 'Exact Solution') end title(ax,{['z = ',num2str(z_o),', Rel RMS (org.) = ',num2str(error_rel_rms(i)),'%, Rel RMS (mod.) = ',num2str(error_rel2_rms(i)),'%'];... [' # points with neg analytical conc. = ',num2str(count)]}); xlim(ax,[0 r_max]); saveCTComparison(results,temp,z_o,t1,SavesFolder,neg_ana_C,error_rel_rms(i),count,error_rel2_rms(i),r_max); clc; close all; clearvars -except j i select_PFitcase new_results_Size p_val sm_val z_loc... choice p_length z_length power M C_v R mu dirext rootdir z_o gs TextAreaText... SavesFolder resultsOutput results C_f compound s_choice sm_length noise_flag... x_spacing powers resultPos data SpacingOption Spacing GridFit noise_IA Fitting app RMSresults errorCalc; end end function fun = compute_C(t,C_v,x_o,z_o,R,C_f) fun = 2.*C_v./pi.*atan(R./(sqrt(0.5.*(x_o.^2+t.^2+z_o.^2-R.^2+ ... sqrt((x_o.^2+t.^2+z_o.^2-R.^2).^2+4.*z_o.^2.*R.^2)))))-C_f; %t represents y coordinates if (fun < 0.0) fun = 0.0*fun; end end
github
nrodrig4/Matlab-Codes-Vapor-Droplet-Evaporation-master
gridfit.m
.m
Matlab-Codes-Vapor-Droplet-Evaporation-master/gridfit.m
35,038
utf_8
be54090de8b2dea9c071c9308ca41c67
function [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes,varargin) % gridfit: estimates a surface on a 2d grid, based on scattered data % Replicates are allowed. All methods extrapolate to the grid % boundaries. Gridfit uses a modified ridge estimator to % generate the surface, where the bias is toward smoothness. % % Gridfit is not an interpolant. Its goal is a smooth surface % that approximates your data, but allows you to control the % amount of smoothing. % % usage #1: zgrid = gridfit(x,y,z,xnodes,ynodes); % usage #2: [zgrid,xgrid,ygrid] = gridfit(x,y,z,xnodes,ynodes); % usage #3: zgrid = gridfit(x,y,z,xnodes,ynodes,prop,val,prop,val,...); % % Arguments: (input) % x,y,z - vectors of equal lengths, containing arbitrary scattered data % The only constraint on x and y is they cannot ALL fall on a % single line in the x-y plane. Replicate points will be treated % in a least squares sense. % % ANY points containing a NaN are ignored in the estimation % % xnodes - vector defining the nodes in the grid in the independent % variable (x). xnodes need not be equally spaced. xnodes % must completely span the data. If they do not, then the % 'extend' property is applied, adjusting the first and last % nodes to be extended as necessary. See below for a complete % description of the 'extend' property. % % If xnodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % ynodes - vector defining the nodes in the grid in the independent % variable (y). ynodes need not be equally spaced. % % If ynodes is a scalar integer, then it specifies the number % of equally spaced nodes between the min and max of the data. % % Also see the extend property. % % Additional arguments follow in the form of property/value pairs. % Valid properties are: % 'smoothness', 'interp', 'regularizer', 'solver', 'maxiter' % 'extend', 'tilesize', 'overlap' % % Any UNAMBIGUOUS shortening (even down to a single letter) is % valid for property names. All properties have default values, % chosen (I hope) to give a reasonable result out of the box. % % 'smoothness' - scalar or vector of length 2 - determines the % eventual smoothness of the estimated surface. A larger % value here means the surface will be smoother. Smoothness % must be a non-negative real number. % % If this parameter is a vector of length 2, then it defines % the relative smoothing to be associated with the x and y % variables. This allows the user to apply a different amount % of smoothing in the x dimension compared to the y dimension. % % Note: the problem is normalized in advance so that a % smoothness of 1 MAY generate reasonable results. If you % find the result is too smooth, then use a smaller value % for this parameter. Likewise, bumpy surfaces suggest use % of a larger value. (Sometimes, use of an iterative solver % with too small a limit on the maximum number of iterations % will result in non-convergence.) % % DEFAULT: 1 % % % 'interp' - character, denotes the interpolation scheme used % to interpolate the data. % % DEFAULT: 'triangle' % % 'bilinear' - use bilinear interpolation within the grid % (also known as tensor product linear interpolation) % % 'triangle' - split each cell in the grid into a triangle, % then linear interpolation inside each triangle % % 'nearest' - nearest neighbor interpolation. This will % rarely be a good choice, but I included it % as an option for completeness. % % % 'regularizer' - character flag, denotes the regularization % paradignm to be used. There are currently three options. % % DEFAULT: 'gradient' % % 'diffusion' or 'laplacian' - uses a finite difference % approximation to the Laplacian operator (i.e, del^2). % % We can think of the surface as a plate, wherein the % bending rigidity of the plate is specified by the user % as a number relative to the importance of fidelity to % the data. A stiffer plate will result in a smoother % surface overall, but fit the data less well. I've % modeled a simple plate using the Laplacian, del^2. (A % projected enhancement is to do a better job with the % plate equations.) % % We can also view the regularizer as a diffusion problem, % where the relative thermal conductivity is supplied. % Here interpolation is seen as a problem of finding the % steady temperature profile in an object, given a set of % points held at a fixed temperature. Extrapolation will % be linear. Both paradigms are appropriate for a Laplacian % regularizer. % % 'gradient' - attempts to ensure the gradient is as smooth % as possible everywhere. Its subtly different from the % 'diffusion' option, in that here the directional % derivatives are biased to be smooth across cell % boundaries in the grid. % % The gradient option uncouples the terms in the Laplacian. % Think of it as two coupled PDEs instead of one PDE. Why % are they different at all? The terms in the Laplacian % can balance each other. % % 'springs' - uses a spring model connecting nodes to each % other, as well as connecting data points to the nodes % in the grid. This choice will cause any extrapolation % to be as constant as possible. % % Here the smoothing parameter is the relative stiffness % of the springs connecting the nodes to each other compared % to the stiffness of a spting connecting the lattice to % each data point. Since all springs have a rest length % (length at which the spring has zero potential energy) % of zero, any extrapolation will be minimized. % % Note: The 'springs' regularizer tends to drag the surface % towards the mean of all the data, so too large a smoothing % parameter may be a problem. % % % 'solver' - character flag - denotes the solver used for the % resulting linear system. Different solvers will have % different solution times depending upon the specific % problem to be solved. Up to a certain size grid, the % direct \ solver will often be speedy, until memory % swaps causes problems. % % What solver should you use? Problems with a significant % amount of extrapolation should avoid lsqr. \ may be % best numerically for small smoothnesss parameters and % high extents of extrapolation. % % Large numbers of points will slow down the direct % \, but when applied to the normal equations, \ can be % quite fast. Since the equations generated by these % methods will tend to be well conditioned, the normal % equations are not a bad choice of method to use. Beware % when a small smoothing parameter is used, since this will % make the equations less well conditioned. % % DEFAULT: 'normal' % % '\' - uses matlab's backslash operator to solve the sparse % system. 'backslash' is an alternate name. % % 'symmlq' - uses matlab's iterative symmlq solver % % 'lsqr' - uses matlab's iterative lsqr solver % % 'normal' - uses \ to solve the normal equations. % % % 'maxiter' - only applies to iterative solvers - defines the % maximum number of iterations for an iterative solver % % DEFAULT: min(10000,length(xnodes)*length(ynodes)) % % % 'extend' - character flag - controls whether the first and last % nodes in each dimension are allowed to be adjusted to % bound the data, and whether the user will be warned if % this was deemed necessary to happen. % % DEFAULT: 'warning' % % 'warning' - Adjust the first and/or last node in % x or y if the nodes do not FULLY contain % the data. Issue a warning message to this % effect, telling the amount of adjustment % applied. % % 'never' - Issue an error message when the nodes do % not absolutely contain the data. % % 'always' - automatically adjust the first and last % nodes in each dimension if necessary. % No warning is given when this option is set. % % % 'tilesize' - grids which are simply too large to solve for % in one single estimation step can be built as a set % of tiles. For example, a 1000x1000 grid will require % the estimation of 1e6 unknowns. This is likely to % require more memory (and time) than you have available. % But if your data is dense enough, then you can model % it locally using smaller tiles of the grid. % % My recommendation for a reasonable tilesize is % roughly 100 to 200. Tiles of this size take only % a few seconds to solve normally, so the entire grid % can be modeled in a finite amount of time. The minimum % tilesize can never be less than 3, although even this % size tile is so small as to be ridiculous. % % If your data is so sparse than some tiles contain % insufficient data to model, then those tiles will % be left as NaNs. % % DEFAULT: inf % % % 'overlap' - Tiles in a grid have some overlap, so they % can minimize any problems along the edge of a tile. % In this overlapped region, the grid is built using a % bi-linear combination of the overlapping tiles. % % The overlap is specified as a fraction of the tile % size, so an overlap of 0.20 means there will be a 20% % overlap of successive tiles. I do allow a zero overlap, % but it must be no more than 1/2. % % 0 <= overlap <= 0.5 % % Overlap is ignored if the tilesize is greater than the % number of nodes in both directions. % % DEFAULT: 0.20 % % % 'autoscale' - Some data may have widely different scales on % the respective x and y axes. If this happens, then % the regularization may experience difficulties. % % autoscale = 'on' will cause gridfit to scale the x % and y node intervals to a unit length. This should % improve the regularization procedure. The scaling is % purely internal. % % autoscale = 'off' will disable automatic scaling % % DEFAULT: 'on' % % % Arguments: (output) % zgrid - (nx,ny) array containing the fitted surface % % xgrid, ygrid - as returned by meshgrid(xnodes,ynodes) % % % Speed considerations: % Remember that gridfit must solve a LARGE system of linear % equations. There will be as many unknowns as the total % number of nodes in the final lattice. While these equations % may be sparse, solving a system of 10000 equations may take % a second or so. Very large problems may benefit from the % iterative solvers or from tiling. % % % Example usage: % % x = rand(100,1); % y = rand(100,1); % z = exp(x+2*y); % xnodes = 0:.1:1; % ynodes = 0:.1:1; % % g = gridfit(x,y,z,xnodes,ynodes); % % Note: this is equivalent to the following call: % % g = gridfit(x,y,z,xnodes,ynodes, ... % 'smooth',1, ... % 'interp','triangle', ... % 'solver','normal', ... % 'regularizer','gradient', ... % 'extend','warning', ... % 'tilesize',inf); % % % Author: John D'Errico % e-mail address: [email protected] % Release: 2.0 % Release date: 5/23/06 % set defaults params.smoothness = 1; params.interp = 'triangle'; params.regularizer = 'gradient'; params.solver = 'backslash'; params.maxiter = []; params.extend = 'warning'; params.tilesize = inf; params.overlap = 0.20; params.mask = []; params.autoscale = 'on'; params.xscale = 1; params.yscale = 1; % was the params struct supplied? if ~isempty(varargin) if isstruct(varargin{1}) % params is only supplied if its a call from tiled_gridfit params = varargin{1}; if length(varargin)>1 % check for any overrides params = parse_pv_pairs(params,varargin{2:end}); end else % check for any overrides of the defaults params = parse_pv_pairs(params,varargin); end end % check the parameters for acceptability params = check_params(params); % ensure all of x,y,z,xnodes,ynodes are column vectors, % also drop any NaN data x=x(:); y=y(:); z=z(:); k = isnan(x) | isnan(y) | isnan(z); if any(k) x(k)=[]; y(k)=[]; z(k)=[]; end xmin = min(x); xmax = max(x); ymin = min(y); ymax = max(y); % did they supply a scalar for the nodes? if length(xnodes)==1 xnodes = linspace(xmin,xmax,xnodes)'; xnodes(end) = xmax; % make sure it hits the max end if length(ynodes)==1 ynodes = linspace(ymin,ymax,ynodes)'; ynodes(end) = ymax; % make sure it hits the max end xnodes=xnodes(:); ynodes=ynodes(:); dx = diff(xnodes); dy = diff(ynodes); nx = length(xnodes); ny = length(ynodes); ngrid = nx*ny; % set the scaling if autoscale was on if strcmpi(params.autoscale,'on') params.xscale = mean(dx); params.yscale = mean(dy); params.autoscale = 'off'; end % check to see if any tiling is necessary if (params.tilesize < max(nx,ny)) % split it into smaller tiles. compute zgrid and ygrid % at the very end if requested zgrid = tiled_gridfit(x,y,z,xnodes,ynodes,params); else % its a single tile. % mask must be either an empty array, or a boolean % aray of the same size as the final grid. nmask = size(params.mask); if ~isempty(params.mask) && ((nmask(2)~=nx) || (nmask(1)~=ny)) if ((nmask(2)==ny) || (nmask(1)==nx)) error 'Mask array is probably transposed from proper orientation.' else error 'Mask array must be the same size as the final grid.' end end if ~isempty(params.mask) params.maskflag = 1; else params.maskflag = 0; end % default for maxiter? if isempty(params.maxiter) params.maxiter = min(10000,nx*ny); end % check lengths of the data n = length(x); if (length(y)~=n) || (length(z)~=n) error 'Data vectors are incompatible in size.' end if n<3 error 'Insufficient data for surface estimation.' end % verify the nodes are distinct if any(diff(xnodes)<=0) || any(diff(ynodes)<=0) error 'xnodes and ynodes must be monotone increasing' end % do we need to tweak the first or last node in x or y? if xmin<xnodes(1) switch params.extend case 'always' xnodes(1) = xmin; case 'warning' warning('GRIDFIT:extend',['xnodes(1) was decreased by: ',num2str(xnodes(1)-xmin),', new node = ',num2str(xmin)]) xnodes(1) = xmin; case 'never' error(['Some x (',num2str(xmin),') falls below xnodes(1) by: ',num2str(xnodes(1)-xmin)]) end end if xmax>xnodes(end) switch params.extend case 'always' xnodes(end) = xmax; case 'warning' warning('GRIDFIT:extend',['xnodes(end) was increased by: ',num2str(xmax-xnodes(end)),', new node = ',num2str(xmax)]) xnodes(end) = xmax; case 'never' error(['Some x (',num2str(xmax),') falls above xnodes(end) by: ',num2str(xmax-xnodes(end))]) end end if ymin<ynodes(1) switch params.extend case 'always' ynodes(1) = ymin; case 'warning' warning('GRIDFIT:extend',['ynodes(1) was decreased by: ',num2str(ynodes(1)-ymin),', new node = ',num2str(ymin)]) ynodes(1) = ymin; case 'never' error(['Some y (',num2str(ymin),') falls below ynodes(1) by: ',num2str(ynodes(1)-ymin)]) end end if ymax>ynodes(end) switch params.extend case 'always' ynodes(end) = ymax; case 'warning' y ymax ynodes warning('GRIDFIT:extend',['ynodes(end) was increased by: ',num2str(ymax-ynodes(end)),', new node = ',num2str(ymax)]) ynodes(end) = ymax; case 'never' error(['Some y (',num2str(ymax),') falls above ynodes(end) by: ',num2str(ymax-ynodes(end))]) end end % determine which cell in the array each point lies in [junk,indx] = histc(x,xnodes); %#ok [junk,indy] = histc(y,ynodes); %#ok % any point falling at the last node is taken to be % inside the last cell in x or y. k=(indx==nx); indx(k)=indx(k)-1; k=(indy==ny); indy(k)=indy(k)-1; ind = indy + ny*(indx-1); % Do we have a mask to apply? if params.maskflag % if we do, then we need to ensure that every % cell with at least one data point also has at % least all of its corners unmasked. params.mask(ind) = 1; params.mask(ind+1) = 1; params.mask(ind+ny) = 1; params.mask(ind+ny+1) = 1; end % interpolation equations for each point tx = min(1,max(0,(x - xnodes(indx))./dx(indx))); ty = min(1,max(0,(y - ynodes(indy))./dy(indy))); % Future enhancement: add cubic interpolant switch params.interp case 'triangle' % linear interpolation inside each triangle k = (tx > ty); L = ones(n,1); L(k) = ny; t1 = min(tx,ty); t2 = max(tx,ty); A = sparse(repmat((1:n)',1,3),[ind,ind+ny+1,ind+L], ... [1-t2,t1,t2-t1],n,ngrid); case 'nearest' % nearest neighbor interpolation in a cell k = round(1-ty) + round(1-tx)*ny; A = sparse((1:n)',ind+k,ones(n,1),n,ngrid); case 'bilinear' % bilinear interpolation in a cell A = sparse(repmat((1:n)',1,4),[ind,ind+1,ind+ny,ind+ny+1], ... [(1-tx).*(1-ty), (1-tx).*ty, tx.*(1-ty), tx.*ty], ... n,ngrid); end rhs = z; % do we have relative smoothing parameters? if numel(params.smoothness) == 1 % it was scalar, so treat both dimensions equally smoothparam = params.smoothness; xyRelativeStiffness = [1;1]; else % It was a vector, so anisotropy reigns. % I've already checked that the vector was of length 2 smoothparam = sqrt(prod(params.smoothness)); xyRelativeStiffness = params.smoothness(:)./smoothparam; end % Build regularizer. Add del^4 regularizer one day. switch params.regularizer case 'springs' % zero "rest length" springs [i,j] = meshgrid(1:nx,1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = nx*(ny-1); stiffness = 1./(dy/params.yscale); Areg = sparse(repmat((1:m)',1,2),[ind,ind+1], ... xyRelativeStiffness(2)*stiffness(j(:))*[-1 1], ... m,ngrid); [i,j] = meshgrid(1:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); m = (nx-1)*ny; stiffness = 1./(dx/params.xscale); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny], ... xyRelativeStiffness(1)*stiffness(i(:))*[-1 1],m,ngrid)]; [i,j] = meshgrid(1:(nx-1),1:(ny-1)); ind = j(:) + ny*(i(:)-1); m = (nx-1)*(ny-1); stiffness = 1./sqrt((dx(i(:))/params.xscale/xyRelativeStiffness(1)).^2 + ... (dy(j(:))/params.yscale/xyRelativeStiffness(2)).^2); Areg = [Areg;sparse(repmat((1:m)',1,2),[ind,ind+ny+1], ... stiffness*[-1 1],m,ngrid)]; Areg = [Areg;sparse(repmat((1:m)',1,2),[ind+1,ind+ny], ... stiffness*[-1 1],m,ngrid)]; case {'diffusion' 'laplacian'} % thermal diffusion using Laplacian (del^2) [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ... 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = Areg + sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ... 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid); case 'gradient' % Subtly different from the Laplacian. A point for future % enhancement is to do it better for the triangle interpolation % case. [i,j] = meshgrid(1:nx,2:(ny-1)); ind = j(:) + ny*(i(:)-1); dy1 = dy(j(:)-1)/params.yscale; dy2 = dy(j(:))/params.yscale; Areg = sparse(repmat(ind,1,3),[ind-1,ind,ind+1], ... xyRelativeStiffness(2)*[-2./(dy1.*(dy1+dy2)), ... 2./(dy1.*dy2), -2./(dy2.*(dy1+dy2))],ngrid,ngrid); [i,j] = meshgrid(2:(nx-1),1:ny); ind = j(:) + ny*(i(:)-1); dx1 = dx(i(:)-1)/params.xscale; dx2 = dx(i(:))/params.xscale; Areg = [Areg;sparse(repmat(ind,1,3),[ind-ny,ind,ind+ny], ... xyRelativeStiffness(1)*[-2./(dx1.*(dx1+dx2)), ... 2./(dx1.*dx2), -2./(dx2.*(dx1+dx2))],ngrid,ngrid)]; end nreg = size(Areg,1); % Append the regularizer to the interpolation equations, % scaling the problem first. Use the 1-norm for speed. NA = norm(A,1); NR = norm(Areg,1); A = [A;Areg*(smoothparam*NA/NR)]; rhs = [rhs;zeros(nreg,1)]; % do we have a mask to apply? if params.maskflag unmasked = find(params.mask); end % solve the full system, with regularizer attached switch params.solver case {'\' 'backslash'} if params.maskflag % there is a mask to use zgrid=nan(ny,nx); zgrid(unmasked) = A(:,unmasked)\rhs; else % no mask zgrid = reshape(A\rhs,ny,nx); end case 'normal' % The normal equations, solved with \. Can be faster % for huge numbers of data points, but reasonably % sized grids. The regularizer makes A well conditioned % so the normal equations are not a terribly bad thing % here. if params.maskflag % there is a mask to use Aunmasked = A(:,unmasked); zgrid=nan(ny,nx); zgrid(unmasked) = (Aunmasked'*Aunmasked)\(Aunmasked'*rhs); else zgrid = reshape((A'*A)\(A'*rhs),ny,nx); end case 'symmlq' % iterative solver - symmlq - requires a symmetric matrix, % so use it to solve the normal equations. No preconditioner. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = symmlq(A(:,unmasked)'*A(:,unmasked), ... A(:,unmasked)'*rhs,tol,params.maxiter); else [zgrid,flag] = symmlq(A'*A,A'*rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % SYMMLQ iterated MAXIT times but did not converge. warning('GRIDFIT:solver',['Symmlq performed ',num2str(params.maxiter), ... ' iterations but did not converge.']) case 3 % SYMMLQ stagnated, successive iterates were the same warning('GRIDFIT:solver','Symmlq stagnated without apparent convergence.') otherwise warning('GRIDFIT:solver',['One of the scalar quantities calculated in',... ' symmlq was too small or too large to continue computing.']) end case 'lsqr' % iterative solver - lsqr. No preconditioner here. tol = abs(max(z)-min(z))*1.e-13; if params.maskflag % there is a mask to use zgrid=nan(ny,nx); [zgrid(unmasked),flag] = lsqr(A(:,unmasked),rhs,tol,params.maxiter); else [zgrid,flag] = lsqr(A,rhs,tol,params.maxiter); zgrid = reshape(zgrid,ny,nx); end % display a warning if convergence problems switch flag case 0 % no problems with convergence case 1 % lsqr iterated MAXIT times but did not converge. warning('GRIDFIT:solver',['Lsqr performed ', ... num2str(params.maxiter),' iterations but did not converge.']) case 3 % lsqr stagnated, successive iterates were the same warning('GRIDFIT:solver','Lsqr stagnated without apparent convergence.') case 4 warning('GRIDFIT:solver',['One of the scalar quantities calculated in',... ' LSQR was too small or too large to continue computing.']) end end % switch params.solver end % if params.tilesize... % only generate xgrid and ygrid if requested. if nargout>1 [xgrid,ygrid]=meshgrid(xnodes,ynodes); end % ============================================ % End of main function - gridfit % ============================================ % ============================================ % subfunction - parse_pv_pairs % ============================================ function params=parse_pv_pairs(params,pv_pairs) % parse_pv_pairs: parses sets of property value pairs, allows defaults % usage: params=parse_pv_pairs(default_params,pv_pairs) % % arguments: (input) % default_params - structure, with one field for every potential % property/value pair. Each field will contain the default % value for that property. If no default is supplied for a % given property, then that field must be empty. % % pv_array - cell array of property/value pairs. % Case is ignored when comparing properties to the list % of field names. Also, any unambiguous shortening of a % field/property name is allowed. % % arguments: (output) % params - parameter struct that reflects any updated property/value % pairs in the pv_array. % % Example usage: % First, set default values for the parameters. Assume we % have four parameters that we wish to use optionally in % the function examplefun. % % - 'viscosity', which will have a default value of 1 % - 'volume', which will default to 1 % - 'pie' - which will have default value 3.141592653589793 % - 'description' - a text field, left empty by default % % The first argument to examplefun is one which will always be % supplied. % % function examplefun(dummyarg1,varargin) % params.Viscosity = 1; % params.Volume = 1; % params.Pie = 3.141592653589793 % % params.Description = ''; % params=parse_pv_pairs(params,varargin); % params % % Use examplefun, overriding the defaults for 'pie', 'viscosity' % and 'description'. The 'volume' parameter is left at its default. % % examplefun(rand(10),'vis',10,'pie',3,'Description','Hello world') % % params = % Viscosity: 10 % Volume: 1 % Pie: 3 % Description: 'Hello world' % % Note that capitalization was ignored, and the property 'viscosity' % was truncated as supplied. Also note that the order the pairs were % supplied was arbitrary. npv = length(pv_pairs); n = npv/2; if n~=floor(n) error 'Property/value pairs must come in PAIRS.' end if n<=0 % just return the defaults return end if ~isstruct(params) error 'No structure for defaults was supplied' end % there was at least one pv pair. process any supplied propnames = fieldnames(params); lpropnames = lower(propnames); for i=1:n p_i = lower(pv_pairs{2*i-1}); v_i = pv_pairs{2*i}; ind = strmatch(p_i,lpropnames,'exact'); if isempty(ind) ind = find(strncmp(p_i,lpropnames,length(p_i))); if isempty(ind) error(['No matching property found for: ',pv_pairs{2*i-1}]) elseif length(ind)>1 error(['Ambiguous property name: ',pv_pairs{2*i-1}]) end end p_i = propnames{ind}; % override the corresponding default in params params = setfield(params,p_i,v_i); %#ok end % ============================================ % subfunction - check_params % ============================================ function params = check_params(params) % check the parameters for acceptability % smoothness == 1 by default if isempty(params.smoothness) params.smoothness = 1; else if (numel(params.smoothness)>2) || any(params.smoothness<=0) error 'Smoothness must be scalar (or length 2 vector), real, finite, and positive.' end end % regularizer - must be one of 4 options - the second and % third are actually synonyms. valid = {'springs', 'diffusion', 'laplacian', 'gradient'}; if isempty(params.regularizer) params.regularizer = 'diffusion'; end ind = find(strncmpi(params.regularizer,valid,length(params.regularizer))); if (length(ind)==1) params.regularizer = valid{ind}; else error(['Invalid regularization method: ',params.regularizer]) end % interp must be one of: % 'bilinear', 'nearest', or 'triangle' % but accept any shortening thereof. valid = {'bilinear', 'nearest', 'triangle'}; if isempty(params.interp) params.interp = 'triangle'; end ind = find(strncmpi(params.interp,valid,length(params.interp))); if (length(ind)==1) params.interp = valid{ind}; else error(['Invalid interpolation method: ',params.interp]) end % solver must be one of: % 'backslash', '\', 'symmlq', 'lsqr', or 'normal' % but accept any shortening thereof. valid = {'backslash', '\', 'symmlq', 'lsqr', 'normal'}; if isempty(params.solver) params.solver = '\'; end ind = find(strncmpi(params.solver,valid,length(params.solver))); if (length(ind)==1) params.solver = valid{ind}; else error(['Invalid solver option: ',params.solver]) end % extend must be one of: % 'never', 'warning', 'always' % but accept any shortening thereof. valid = {'never', 'warning', 'always'}; if isempty(params.extend) params.extend = 'warning'; end ind = find(strncmpi(params.extend,valid,length(params.extend))); if (length(ind)==1) params.extend = valid{ind}; else error(['Invalid extend option: ',params.extend]) end % tilesize == inf by default if isempty(params.tilesize) params.tilesize = inf; elseif (length(params.tilesize)>1) || (params.tilesize<3) error 'Tilesize must be scalar and > 0.' end % overlap == 0.20 by default if isempty(params.overlap) params.overlap = 0.20; elseif (length(params.overlap)>1) || (params.overlap<0) || (params.overlap>0.5) error 'Overlap must be scalar and 0 < overlap < 1.' end % ============================================ % subfunction - tiled_gridfit % ============================================ function zgrid=tiled_gridfit(x,y,z,xnodes,ynodes,params) % tiled_gridfit: a tiled version of gridfit, continuous across tile boundaries % usage: [zgrid,xgrid,ygrid]=tiled_gridfit(x,y,z,xnodes,ynodes,params) % % Tiled_gridfit is used when the total grid is far too large % to model using a single call to gridfit. While gridfit may take % only a second or so to build a 100x100 grid, a 2000x2000 grid % will probably not run at all due to memory problems. % % Tiles in the grid with insufficient data (<4 points) will be % filled with NaNs. Avoid use of too small tiles, especially % if your data has holes in it that may encompass an entire tile. % % A mask may also be applied, in which case tiled_gridfit will % subdivide the mask into tiles. Note that any boolean mask % provided is assumed to be the size of the complete grid. % % Tiled_gridfit may not be fast on huge grids, but it should run % as long as you use a reasonable tilesize. 8-) % Note that we have already verified all parameters in check_params % Matrix elements in a square tile tilesize = params.tilesize; % Size of overlap in terms of matrix elements. Overlaps % of purely zero cause problems, so force at least two % elements to overlap. overlap = max(2,floor(tilesize*params.overlap)); % reset the tilesize for each particular tile to be inf, so % we will never see a recursive call to tiled_gridfit Tparams = params; Tparams.tilesize = inf; nx = length(xnodes); ny = length(ynodes); zgrid = zeros(ny,nx); % linear ramp for the bilinear interpolation rampfun = inline('(t-t(1))/(t(end)-t(1))','t'); % loop over each tile in the grid h = waitbar(0,'Relax and have a cup of JAVA. Its my treat.'); warncount = 0; xtind = 1:min(nx,tilesize); while ~isempty(xtind) && (xtind(1)<=nx) xinterp = ones(1,length(xtind)); if (xtind(1) ~= 1) xinterp(1:overlap) = rampfun(xnodes(xtind(1:overlap))); end if (xtind(end) ~= nx) xinterp((end-overlap+1):end) = 1-rampfun(xnodes(xtind((end-overlap+1):end))); end ytind = 1:min(ny,tilesize); while ~isempty(ytind) && (ytind(1)<=ny) % update the waitbar waitbar((xtind(end)-tilesize)/nx + tilesize*ytind(end)/ny/nx) yinterp = ones(length(ytind),1); if (ytind(1) ~= 1) yinterp(1:overlap) = rampfun(ynodes(ytind(1:overlap))); end if (ytind(end) ~= ny) yinterp((end-overlap+1):end) = 1-rampfun(ynodes(ytind((end-overlap+1):end))); end % was a mask supplied? if ~isempty(params.mask) submask = params.mask(ytind,xtind); Tparams.mask = submask; end % extract data that lies in this grid tile k = (x>=xnodes(xtind(1))) & (x<=xnodes(xtind(end))) & ... (y>=ynodes(ytind(1))) & (y<=ynodes(ytind(end))); k = find(k); if length(k)<4 if warncount == 0 warning('GRIDFIT:tiling','A tile was too underpopulated to model. Filled with NaNs.') end warncount = warncount + 1; % fill this part of the grid with NaNs zgrid(ytind,xtind) = NaN; else % build this tile zgtile = gridfit(x(k),y(k),z(k),xnodes(xtind),ynodes(ytind),Tparams); % bilinear interpolation (using an outer product) interp_coef = yinterp*xinterp; % accumulate the tile into the complete grid zgrid(ytind,xtind) = zgrid(ytind,xtind) + zgtile.*interp_coef; end % step to the next tile in y if ytind(end)<ny ytind = ytind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (ytind(end)+max(3,overlap))>=ny % extend this tile to the edge ytind = ytind(1):ny; end else ytind = ny+1; end end % while loop over y % step to the next tile in x if xtind(end)<nx xtind = xtind + tilesize - overlap; % are we within overlap elements of the edge of the grid? if (xtind(end)+max(3,overlap))>=nx % extend this tile to the edge xtind = xtind(1):nx; end else xtind = nx+1; end end % while loop over x % close down the waitbar close(h) if warncount>0 warning('GRIDFIT:tiling',[num2str(warncount),' tiles were underpopulated & filled with NaNs']) end
github
nrodrig4/Matlab-Codes-Vapor-Droplet-Evaporation-master
IA_minus_Concentration_mod.m
.m
Matlab-Codes-Vapor-Droplet-Evaporation-master/IA_minus_Concentration_mod.m
1,673
utf_8
34c06378b7fcb0eb5f68893321662da7
%IA function function mat = Integrated_Absorbance_minus_Concentration_mod(noise_IA,z_o,mu,M,C_v,R,SavesFolder,x_spacing) %Setting up General Parameters and pre-allocating memory for speed r = 50; x_loc = x_spacing'; mat = zeros(length(x_loc),2); %creating file name for Integrated Absorbance Data filename = strcat(SavesFolder,'/IA_',num2str(z_o),'.txt'); rw = 50; z_oo = 0; %Weber's Disc Analytical Solution C_f = 2*C_v/pi*atan(R/(sqrt(0.5*(rw^2+z_oo^2-R^2+ ... sqrt((rw^2+z_oo^2-R^2)^2+4*z_oo^2*R^2))))) %analytical C at (rw,z_oo) %calculating Integrated Absorbance (minus Weber's disc at C(50,0) for i = 1:length(x_loc) x_o = x_loc(i); a = sqrt(r^2-x_o^2); fun = @(t) compute_C(t,C_v,x_o,z_o,R,C_f); %disp('int1') solution = integral(fun,-a,a); %line integral along the y-direction %disp('int2') solution = solution*1000/(1*10^6*M)*mu-(2.0*rand(size(solution))-1*ones(size(solution)))*noise_IA; %unit? mat(i,1) = x_o; mat(i,2) = solution; end dlmwrite(filename,mat,'delimiter','\t','precision',10) end function fun = compute_C(t,C_v,x_o,z_o,R,C_f) fun = 2.*C_v./pi.*atan(R./(sqrt(0.5.*(x_o.^2+t.^2+z_o.^2-R.^2+ ... sqrt((x_o.^2+t.^2+z_o.^2-R.^2).^2+4.*z_o.^2.*R.^2)))))-C_f; %t represents y coordinates if (fun < 0.0) fun = 0.0*fun; end end
github
carsonburr/code_world_godot_ext-master
echo_diagnostic.m
.m
code_world_godot_ext-master/thirdparty/speex/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
uygarsumbul/spines-master
readDataset_spines_mod_shuffleNodesWithinBranchTypes.m
.m
spines-master/repo/readDataset_spines_mod_shuffleNodesWithinBranchTypes.m
22,314
utf_8
26728e15e7edf60ada823c3c08a9a601
function [allTrees, allPAs] = readDataset_spines_mod_shuffleNodesWithinBranchTypes(code,directory,options) if ~isfield(options,'normalize') || isempty(options.normalize); normalize = false; else; normalize = options.normalize; end; if ~isfield(options,'absoluteLengths') || isempty(options.absoluteLengths); absoluteLengths = true; else; absoluteLengths = options.absoluteLengths; end; if ~isfield(options,'neuronParts') || isempty(options.neuronParts); neuronParts = [-10:10]; else; neuronParts = options.neuronParts; end; if ~isfield(options,'anisotropyDivisors') || isempty(options.anisotropyDivisors); anisotropyDivisors = [1 1 1]; else; anisotropyDivisors = options.anisotropyDivisors; end; if ~isfield(options,'SCALECONSTANT') || isempty(options.SCALECONSTANT); SCALECONSTANT = 1; else; SCALECONSTANT = options.SCALECONSTANT; end; if ~isfield(options,'removeShortLeaves') || isempty(options.removeShortLeaves); removeShortLeaves = false; else; removeShortLeaves = options.removeShortLeaves; end; if ~isfield(options,'pruneRatio') || isempty(options.pruneRatio); pruneRatio = 1; else; pruneRatio = options.pruneRatio; end; if ~isfield(options,'removeBranches') || isempty(options.removeBranches); removeBranches = false; else; removeBranches = options.removeBranches; end; if ~isfield(options,'resolution') || isempty(options.resolution); resolution = [1 1 1]; else; resolution = options.resolution; end; allTrees = cell(0); allNodesAndEdges = cell(0); for kk = 1:numel(code) thisFileName = strcat(directory,code{kk}{1}); %,code{kk}{2}); [nodes,edges,radii,nodeTypes,features,~] = readSWCfile(thisFileName,neuronParts,resolution); apicalTuft = find(nodeTypes==5); tmp = features(apicalTuft, 12-7:18-7); tmp = tmp(randperm(numel(apicalTuft)), :); features(apicalTuft, 12-7:18-7) = tmp; apicalOblique = find(nodeTypes==3); tmp = features(apicalOblique, 12-7:18-7); tmp = tmp(randperm(numel(apicalOblique)), :); features(apicalOblique, 12-7:18-7) = tmp; basal = find(nodeTypes==7); tmp = features(basal, 12-7:18-7); tmp = tmp(randperm(numel(basal)), :); features(basal, 12-7:18-7) = tmp; apical = find(nodeTypes==4); tmp = features(apical, 12-7:18-7); tmp = tmp(randperm(numel(apical)), :); features(apical, 12-7:18-7) = tmp; soma = find(nodeTypes==1,1); for dd=1:3; nodes(:,dd)=nodes(:,dd)-(nodes(soma,dd)); end; principalAxes = calculatePrincipalAxes(nodes); allPAs(:,kk)=principalAxes(:,1); features = [features nodeTypes]; nodes(:,1) = nodes(:,1)/anisotropyDivisors(1); nodes(:,2) = nodes(:,2)/anisotropyDivisors(2); nodes(:,3) = nodes(:,3)/anisotropyDivisors(3); [tree,rawLength,nodes,edges]=generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,false); % 1:soma, 2:axon, 3:basal dendrite, 4:apical dendrite if removeShortLeaves; tree = pruneShortLeaves(tree,treeLength(tree)*pruneRatio); end; if normalize; tree = normalizeNeuron(tree); end; allTrees{end+1} = tree; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,nodeType,features,abort] = readSWCfile(fileName,validNodeTypes,resolution) abort = false; nodes = []; edges = []; nodeTypes = []; validNodeTypes = setdiff(validNodeTypes,1); [nodeID, nodeType, xPos, yPos, zPos, radii, parentNodeID,d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9] = textread(fileName, '%u%d%f%f%f%f%d%d%d%f%f%f%f%f%f%f%f%f','commentstyle', 'shell'); xPos = xPos * resolution(1); yPos = yPos * resolution(2); zPos = zPos * resolution(3); features = [d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9]; if ~any(parentNodeID==-1) disp(strcat('root not found in ',fileName)); nodes = []; edges = []; radii = []; nodeTypes = []; features = []; abort = true; return; end nodeType(find(parentNodeID==-1))=1; % Every tree should start from a node of type 1 (soma) firstSomaNode = find(nodeType == 1 & parentNodeID == -1, 1); somaNodes = find(nodeType == 1); somaX = mean(xPos(somaNodes)); somaY = mean(yPos(somaNodes)); somaZ = mean(zPos(somaNodes)); % set soma radius to 0, to avoid multiple counting of soma volume through different subsets. ignore soma volume somaRadius = 0; %mean(radii(somaNodes)); xPos(firstSomaNode) = somaX; yPos(firstSomaNode) = somaY; zPos(firstSomaNode) = somaZ; radii(firstSomaNode) = somaRadius; features(firstSomaNode,:) = zeros(1,size(features,2)); parentNodeID(ismember(parentNodeID,somaNodes)) = firstSomaNode; % assign a single soma parent nodesToDelete = setdiff(somaNodes,firstSomaNode); % delete all the soma nodes except for the firstSomaNode nodeID(nodesToDelete)=[]; nodeType(nodesToDelete)=[]; xPos(nodesToDelete)=[]; yPos(nodesToDelete)=[]; zPos(nodesToDelete)=[]; radii(nodesToDelete)=[]; parentNodeID(nodesToDelete)=[]; features(nodesToDelete,:)=[]; for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end validNodes = nodeID(ismember(nodeType,validNodeTypes)); additionalValidNodes = []; for kk = 1:numel(validNodes) thisParentNodeID = parentNodeID(validNodes(kk)); thisParentNodeType = nodeType(thisParentNodeID); while ~ismember(thisParentNodeType,validNodeTypes) if thisParentNodeType == 1 break; end additionalValidNodes = union(additionalValidNodes, thisParentNodeID); nodeType(thisParentNodeID) = validNodeTypes(1); thisParentNodeID = parentNodeID(thisParentNodeID); thisParentNodeType = nodeType(thisParentNodeID); end end validNodes = [firstSomaNode; validNodes; additionalValidNodes']; validNodes = unique(validNodes); nodeID = nodeID(validNodes); nodeType = nodeType(validNodes); parentNodeID = parentNodeID(validNodes); xPos = xPos(validNodes); yPos = yPos(validNodes); zPos = zPos(validNodes); radii = radii(validNodes); features = features(validNodes, :); for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end nodes = [xPos yPos zPos]; edges = [nodeID parentNodeID]; edges(any(edges==-1,2),:) = []; %nodeTypes = unique(nodeType)'; %[nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features); % remove the root nodes until the first node %[nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features); % remove zero branches nodes = nodes + 1; % added on Mar 7, 2012 - band tracing starts at 1 - relevant if the tree will be warped somaNode = find(nodeType == 1, 1); % swap on edges edges(edges==1) = 0; edges(edges==somaNode) = 1; edges(edges==0) = somaNode; % swap on nodes tmp = nodes(1,:); nodes(1,:) = nodes(somaNode,:); nodes(somaNode,:) = tmp; % swap on radii tmpR = radii(1); radii(1) = radii(somaNode); radii(somaNode) = tmpR; % swap on features tmpF = features(1,:); features(1,:) = features(somaNode,:); features(somaNode,:) = tmpF; % swap on node types tmpT = nodeType(1); nodeType(1) = nodeType(somaNode,:); nodeType(somaNode,:) = tmpT; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features) if size(nodes,1) < 2 return; end % node 1 is assigned as the root node root = 1; expandedEdges = [edges edges(:,1)]; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); while numel(child) < 2 nodes = [nodes(1:root-1,:); nodes(root+1:end,:)]; radii = [radii(1:root-1); radii(root+1:end)]; features = [features(1:root-1,:); features(root+1:end,:)]; edges(any(edges==root,2),:) = []; edges(edges>root) = edges(edges>root) - 1; expandedEdges = [edges edges(:,1)]; if child > root child = child-1; end root = child; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features) kk = 1; while kk < size(edges,1) node1 = edges(kk,1); node2 = edges(kk,2); if norm(nodes(node1,:)-nodes(node2,:)) < 1e-10 % BE CAREFUL / ARBITRARY edges(edges==node1) = node2; edges(edges>node1) = edges(edges>node1)-1; edges(kk,:) = []; % remove edge nodes(node1,:) = []; % remove node radii(node1) = []; % remove area features(node1,:) = []; % remove features else kk = kk + 1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii] = removeOutOfBoundsBranches(nodes,edges,radii,bounds) if size(nodes,1) < 2 return; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); while ~isempty(thisNode) selfOrDescendant = selfOrDescendantFromEdges(edges, thisNode, thisNode); edges(ismember(edges(:,1),selfOrDescendant) | ismember(edges(:,2),selfOrDescendant),:) = []; nodes(selfOrDescendant,:) = []; radii(selfOrDescendant) = []; selfOrDescendent = sort(selfOrDescendant,'descend'); for kk=1:numel(selfOrDescendant) nn=selfOrDescendant(kk); edges(edges>nn) = edges(edges>nn)-1; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sod = selfOrDescendantFromEdges(edges, sod, node) children = edges(find(edges(:,1)==node),2); sod = [sod children]; if ~isempty(children) for kk=1:numel(children) sod = selfOrDescendantFromEdges(edges, sod, children(kk)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree,rawLength,nodes,edges] = generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,uniformCSAreas) areas = pi*radii.^2; % 1 is assumed to be the root node. edges is nx2: each row is [child parent] h = hist(edges(:,2),[1:size(nodes,1)]); irreducibleNodes = union(find(h~=1),1); % 1 is the root node % put all the irreducible nodes at the beginning for kk = 1:numel(irreducibleNodes) % swap on edges edges(edges==kk) = 0; edges(edges==irreducibleNodes(kk)) = kk; edges(edges==0) = irreducibleNodes(kk); % swap on nodes tmp = nodes(kk,:); nodes(kk,:) = nodes(irreducibleNodes(kk),:); nodes(irreducibleNodes(kk),:) = tmp; % swap on areas tmpA = areas(kk); areas(kk) = areas(irreducibleNodes(kk)); areas(irreducibleNodes(kk)) = tmpA; % swap on features tmpF = features(kk,:); features(kk,:) = features(irreducibleNodes(kk),:); features(irreducibleNodes(kk),:) = tmpF; end numelNodes = numel(irreducibleNodes); %initialize tree with root as 1 tree{1}{1} = []; tree{1}{3} = nodes(1,:); tree{1}{4}{1} = nodes(1,:); tree{1}{4}{2} = 0; tree{1}{4}{3} = [[0;0;0] [0;0;0]]; tree{1}{4}{4} = 0; for kk = 1:numelNodes tree{kk}{2} = []; end rawLength = 0; for kk = 2:numelNodes tmpParent = edges(find(edges(:,1)==kk),2); % assume that the edges are ordered pairs: (child, parent) path = nodes(kk,:); thisFeature = features(kk, :); if uniformCSAreas pathAreas = 1; else pathAreas = (areas(kk)+areas(tmpParent)+sqrt(areas(kk)*areas(tmpParent)))/3; end while tmpParent > numelNodes newTmpParent = edges(find(edges(:,1)==tmpParent),2); path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; if uniformCSAreas pathAreas = [pathAreas; 1]; else pathAreas = [pathAreas; (areas(tmpParent)+areas(newTmpParent)+sqrt(areas(tmpParent)*areas(newTmpParent)))/3]; % now modeled as a cylinder end tmpParent = newTmpParent; end path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; rawPathLengths = sqrt(sum(diff(path,1,1).^2,2)); rawLength = rawLength + sum(rawPathLengths); tree{kk}{1} = tmpParent; tree{tmpParent}{2} = [tree{tmpParent}{2} kk]; tree{kk}{3} = nodes(kk,:); tree{kk}{4}{1} = path; tree{kk}{4}{2} = rawPathLengths; tree{kk}{4}{4} = pathAreas; tree{kk}{4}{5} = thisFeature; end tree = calculateDistanceFromSoma(tree, 1, []); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = pruneShortLeaves(tree,lengthThreshold) if numel(tree)<2 return; end root = rootFinder(tree); leaves = findLeaves(tree); leaves = setdiff(leaves, tree{root}{2})'; leaves = [leaves zeros(size(leaves))]; for kk = 1:size(leaves,1) leaves(kk,2) = sum(tree{leaves(kk)}{4}{2}); end leaves = sortrows(leaves,2); leaves = leaves(:,1); counter = 1; while counter <= numel(leaves) if (sum(tree{leaves(counter)}{4}{2}) > lengthThreshold) leaves(counter) = []; else counter = counter + 1; end end for counter = 1:numel(leaves) leaf = leaves(counter); if (sum(tree{leaf}{4}{2}) <= lengthThreshold) parent = tree{leaf}{1}; siblings = setdiff(tree{parent}{2},leaf); % remove the leaf from the child relationship tree{parent}{2} = setdiff(tree{parent}{2}, leaf); % change node numbers of parents/children if larger than this leaf's number for node = 1:numel(tree) if tree{node}{1} > leaf tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > leaf) = children(children > leaf)-1; end % update the parent, sibling, leaf numbers parent(parent>leaf) = parent(parent>leaf)-1; siblings(siblings>leaf) = siblings(siblings>leaf)-1; leaves(leaves>leaf) = leaves(leaves>leaf)-1; % remove leaf from tree tree(leaf) = []; % update the root root = rootFinder(tree); % if the removal made the parent node a reducible node... if (numel(siblings) == 1) && (parent ~= root) % the grandparent removes the reducible parent from the list of children, and inherits the single child tree{tree{parent}{1}}{2} = [setdiff(tree{tree{parent}{1}}{2},parent) siblings]; % the single child's parent becomes the grandparent tree{siblings}{1} = tree{parent}{1}; % the single child adds the reducible node's geometric information to itself tree{siblings}{4}{1} = [tree{siblings}{4}{1}(1:end-1,:); tree{parent}{4}{1}]; % critical nodes tree{siblings}{4}{2} = [tree{siblings}{4}{2}; tree{parent}{4}{2}]; % lengths % tree{siblings}{4}{3} = [tree{siblings}{4}{3} tree{parent}{4}{3}(:,2:end)]; % orientations tree{siblings}{4}{4} = [tree{siblings}{4}{4}; tree{parent}{4}{4}]; % areas tree{siblings}{4}{5} = [tree{siblings}{4}{5}; tree{parent}{4}{5}]; % features % if isempty(tree{siblings}{4}{5}) % tree{siblings}{4}{5} = tree{parent}{4}{5}; % else % tree{siblings}{4}{5} = [tree{siblings}{4}{5}; uint32(tree{parent}{4}{5}(2:end)+numel(tree{siblings}{4}{5})-1)]; % end % change node numbers of parents/children if larger than the parent's number for node = 1:numel(tree) if tree{node}{1} > parent tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > parent) = children(children > parent)-1; end % update leaf numbers leaves(leaves>parent) = leaves(leaves>parent)-1; % remove the reducible parent from tree tree(parent) = []; end end tmpLeaves = leaves(counter+1:end); tmpLeaves = [tmpLeaves zeros(size(tmpLeaves))]; if ~isempty(tmpLeaves) for kk = 1:size(tmpLeaves,1) tmpLeaves(kk,2) = sum(tree{tmpLeaves(kk,1)}{4}{2}); end tmpLeaves = sortrows(tmpLeaves,2); leaves(counter+1:end) = tmpLeaves(:,1); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [localMass,newNodes] = switchToMassRepresentation(nodes,edges) localMass = zeros(size(nodes,1),1); newNodes = zeros(size(nodes,1),3); for kk=1:size(nodes,1); parent = edges(find(edges(:,1)==kk),2); if ~isempty(parent) localMass(kk) = norm(nodes(parent,:)-nodes(kk,:)); newNodes(kk,:) = (nodes(parent,:)+nodes(kk,:))/2; else localMass(kk) = 0; newNodes(kk,:) = nodes(kk,:); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function principalAxes = calculatePrincipalAxes(xyz, weights) if nargin < 2; weights = ones(size(xyz,1),1); end; % find the inertia tensor inertiaTensor = zeros(3); inertiaTensor(1,1) = sum(weights .* (xyz(:,2).^2 + xyz(:,3).^2)); inertiaTensor(2,2) = sum(weights .* (xyz(:,1).^2 + xyz(:,3).^2)); inertiaTensor(3,3) = sum(weights .* (xyz(:,1).^2 + xyz(:,2).^2)); inertiaTensor(1,2) = -sum(weights .* xyz(:,1) .* xyz(:,2)); inertiaTensor(1,3) = -sum(weights .* xyz(:,1) .* xyz(:,3)); inertiaTensor(2,3) = -sum(weights .* xyz(:,2) .* xyz(:,3)); inertiaTensor(2,1) = inertiaTensor(1,2); inertiaTensor(3,1) = inertiaTensor(1,3); inertiaTensor(3,2) = inertiaTensor(2,3); % find the principal axes of the inertia tensor [principalAxes, evMatrix] = eig(inertiaTensor); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tr = normalizeNeuron(tr) % normalize the total dendritic length lengthOnly = true; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{2}) tr{node}{4}{1} = tr{node}{4}{1}/totalLength; tr{node}{4}{2} = tr{node}{4}{2}/totalLength; tr{node}{4}{3} = tr{node}{4}{3}/totalLength; end tr{node}{3} = tr{node}{3}/totalLength; end % normalize the total dendritic volume by changing the cross-sectional areas, and keeping the lengths the same lengthOnly = false; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{4}) tr{node}{4}{4} = tr{node}{4}{4}/totalLength; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree nodes areas rawLength] = integrateTree(tree,node,nodes,areas,rawLength,startingPos,interval) tree{node}{3} = startingPos; children = tree{node}{2}; for child = 1:numel(children) thisBranch = tree{children(child)}{4}{1}; thisBranch = thisBranch(end:-1:1,:); branchAreas = tree{children(child)}{4}{4}; branchAreas = branchAreas(end:-1:1); [thisBranch pathLengths branchAreas] = integrateBranch(thisBranch,branchAreas,startingPos,interval); tree{children(child)}{4}{1} = thisBranch(end:-1:1,:); nodes = [nodes; tree{children(child)}{4}{1}]; tree{children(child)}{4}{2} = pathLengths(end:-1:1); tree{children(child)}{4}{4} = branchAreas; areas = [areas; tree{children(child)}{4}{4}]; rawLength = rawLength+sum(pathLengths); [tree nodes areas rawLength] = integrateTree(tree,children(child),nodes,areas,rawLength,thisBranch(end,:),interval); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [path pathLengths newAreas] = integrateBranch(branchCoordinates,areas,startingPos,interval) path=startingPos; curPos=0; curEdgePos=0; nextPillar=2; curCoord = branchCoordinates(1,:); edgeVectors = diff(branchCoordinates,1,1); edgeLengths=sqrt(sum(edgeVectors.^2,2)); totalLength=sum(edgeLengths); curVec=edgeVectors(1,:); curVec = curVec/norm(curVec); nextPillarDistance=edgeLengths(1); newAreas = []; while curPos<totalLength xyzSteps = abs((-curCoord+sqrt(curCoord.^2+2*curVec*interval))./(curVec+1e-6)); step = min(max(xyzSteps),nextPillarDistance); path = [path; path(end,:)+curCoord*step+curVec*step^2/2]; curEdgePos = curEdgePos+step; curCoord = curCoord+step*curVec; curPos = curPos+step; nextPillarDistance = nextPillarDistance-step; newAreas = [areas(min(nextPillar,size(edgeVectors,1))); newAreas]; % inverted orientation for areas to avoid inversion of array in integrateTree! if nextPillarDistance<totalLength/1e6 % 1e-6 precision if nextPillar>size(edgeVectors,1) break; end curCoord=branchCoordinates(nextPillar,:); curVec=edgeVectors(nextPillar,:); curVec=curVec/norm(curVec); nextPillarDistance = edgeLengths(nextPillar,:); nextPillar=nextPillar+1; curEdgePos=0; end end pathLengths = sqrt(sum(diff(path,1,1).^2,2)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = rotateTree(tree,rotMatrix) for kk = 1:numel(tree) tree{kk}{3} = tree{kk}{3}*rotMatrix; if ~isempty(tree{kk}{4}{1}) tree{kk}{4}{1} = tree{kk}{4}{1}*rotMatrix; tree{kk}{4}{3} = rotMatrix' * tree{kk}{4}{3}; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rotMatrix = findRotationMatrix(rotAxis,rotAngle) ux=rotAxis(1); uy=rotAxis(2); uz=rotAxis(3); rotMatrix = (cos(rotAngle)*eye(3) + sin(rotAngle)*[0 -uz uy;uz 0 -ux;-uy ux 0] + (1-cos(rotAngle))*kron(rotAxis,rotAxis'))'; if any(any(isnan(rotMatrix))) rotMatrix = eye(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = calculateDistanceFromSoma(tree, thisNode, parent) if ~isempty(parent) reference = tree{parent}{4}{5}(1, 4); tmp = cumsum([0; tree{thisNode}{4}{2}]); somaBorder = find(tree{thisNode}{4}{5}(:,19-7)<2, 1); if ~isempty(somaBorder) && somaBorder>1 tmp(somaBorder:end) = tmp(somaBorder-1); end tree{thisNode}{4}{5}(:, 4) = reference + tmp(end) - tmp; else tree{thisNode}{4}{5}(1, 4) = 0; end children = tree{thisNode}{2}; for kk = 1:numel(children) tree = calculateDistanceFromSoma(tree, children(kk), thisNode); end
github
uygarsumbul/spines-master
save1000WithinDomainShuffledTrees.m
.m
spines-master/repo/save1000WithinDomainShuffledTrees.m
1,553
utf_8
42eed829143646f2c9485add1896afdf
function save1000ShuffledTrees code{1}{1} = 'aibs_8_spinerecon_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_9_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_13_mouse2_spinerecon_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_18_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_19_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_20_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_21_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_22_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_23_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_24_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_25_stitched_connected_labeled.eswc'; directory = '/home/uygar/spines/data/upsampledFinalReconstructions_updated3-22-17/'; options.resolution = [0.12 0.12 0.1]; options.resolution20x = [0.62 0.62 0.75]; parfor kk = 1:1000 trees = readDataset_spines_mod_shuffleNodesWithinBranchTypes(code,directory,options); mySaveFunction(kk, trees); end function mySaveFunction(kk, trees) filename = ['/home/uygar/spines/data/shuffledTrees_' num2str(kk) '.mat']; save(filename, 'trees');
github
uygarsumbul/spines-master
readDataset_spines_mod_shuffleNodes.m
.m
spines-master/repo/readDataset_spines_mod_shuffleNodes.m
21,724
utf_8
37c69dc1c0170986da79f8214b1428bc
function [allTrees, allPAs] = readDataset_spines_mod_shuffleNodes(code,directory,options) if ~isfield(options,'normalize') || isempty(options.normalize); normalize = false; else; normalize = options.normalize; end; if ~isfield(options,'absoluteLengths') || isempty(options.absoluteLengths); absoluteLengths = true; else; absoluteLengths = options.absoluteLengths; end; if ~isfield(options,'neuronParts') || isempty(options.neuronParts); neuronParts = [-10:10]; else; neuronParts = options.neuronParts; end; if ~isfield(options,'anisotropyDivisors') || isempty(options.anisotropyDivisors); anisotropyDivisors = [1 1 1]; else; anisotropyDivisors = options.anisotropyDivisors; end; if ~isfield(options,'SCALECONSTANT') || isempty(options.SCALECONSTANT); SCALECONSTANT = 1; else; SCALECONSTANT = options.SCALECONSTANT; end; if ~isfield(options,'removeShortLeaves') || isempty(options.removeShortLeaves); removeShortLeaves = false; else; removeShortLeaves = options.removeShortLeaves; end; if ~isfield(options,'pruneRatio') || isempty(options.pruneRatio); pruneRatio = 1; else; pruneRatio = options.pruneRatio; end; if ~isfield(options,'removeBranches') || isempty(options.removeBranches); removeBranches = false; else; removeBranches = options.removeBranches; end; if ~isfield(options,'resolution') || isempty(options.resolution); resolution = [1 1 1]; else; resolution = options.resolution; end; allTrees = cell(0); allNodesAndEdges = cell(0); for kk = 1:numel(code) thisFileName = strcat(directory,code{kk}{1}); %,code{kk}{2}); [nodes,edges,radii,nodeTypes,features,~] = readSWCfile(thisFileName,neuronParts,resolution); tmp = features(:, 12-7:18-7); tmp = tmp(randperm(size(tmp, 1)), :); features(:, 12-7:18-7) = tmp; soma = find(nodeTypes==1,1); for dd=1:3; nodes(:,dd)=nodes(:,dd)-(nodes(soma,dd)); end; principalAxes = calculatePrincipalAxes(nodes); allPAs(:,kk)=principalAxes(:,1); features = [features nodeTypes]; nodes(:,1) = nodes(:,1)/anisotropyDivisors(1); nodes(:,2) = nodes(:,2)/anisotropyDivisors(2); nodes(:,3) = nodes(:,3)/anisotropyDivisors(3); [tree,rawLength,nodes,edges]=generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,false); % 1:soma, 2:axon, 3:basal dendrite, 4:apical dendrite if removeShortLeaves; tree = pruneShortLeaves(tree,treeLength(tree)*pruneRatio); end; if normalize; tree = normalizeNeuron(tree); end; allTrees{end+1} = tree; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,nodeType,features,abort] = readSWCfile(fileName,validNodeTypes,resolution) abort = false; nodes = []; edges = []; nodeTypes = []; validNodeTypes = setdiff(validNodeTypes,1); [nodeID, nodeType, xPos, yPos, zPos, radii, parentNodeID,d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9] = textread(fileName, '%u%d%f%f%f%f%d%d%d%f%f%f%f%f%f%f%f%f','commentstyle', 'shell'); xPos = xPos * resolution(1); yPos = yPos * resolution(2); zPos = zPos * resolution(3); features = [d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9]; if ~any(parentNodeID==-1) disp(strcat('root not found in ',fileName)); nodes = []; edges = []; radii = []; nodeTypes = []; features = []; abort = true; return; end nodeType(find(parentNodeID==-1))=1; % Every tree should start from a node of type 1 (soma) firstSomaNode = find(nodeType == 1 & parentNodeID == -1, 1); somaNodes = find(nodeType == 1); somaX = mean(xPos(somaNodes)); somaY = mean(yPos(somaNodes)); somaZ = mean(zPos(somaNodes)); % set soma radius to 0, to avoid multiple counting of soma volume through different subsets. ignore soma volume somaRadius = 0; %mean(radii(somaNodes)); xPos(firstSomaNode) = somaX; yPos(firstSomaNode) = somaY; zPos(firstSomaNode) = somaZ; radii(firstSomaNode) = somaRadius; features(firstSomaNode,:) = zeros(1,size(features,2)); parentNodeID(ismember(parentNodeID,somaNodes)) = firstSomaNode; % assign a single soma parent nodesToDelete = setdiff(somaNodes,firstSomaNode); % delete all the soma nodes except for the firstSomaNode nodeID(nodesToDelete)=[]; nodeType(nodesToDelete)=[]; xPos(nodesToDelete)=[]; yPos(nodesToDelete)=[]; zPos(nodesToDelete)=[]; radii(nodesToDelete)=[]; parentNodeID(nodesToDelete)=[]; features(nodesToDelete,:)=[]; for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end validNodes = nodeID(ismember(nodeType,validNodeTypes)); additionalValidNodes = []; for kk = 1:numel(validNodes) thisParentNodeID = parentNodeID(validNodes(kk)); thisParentNodeType = nodeType(thisParentNodeID); while ~ismember(thisParentNodeType,validNodeTypes) if thisParentNodeType == 1 break; end additionalValidNodes = union(additionalValidNodes, thisParentNodeID); nodeType(thisParentNodeID) = validNodeTypes(1); thisParentNodeID = parentNodeID(thisParentNodeID); thisParentNodeType = nodeType(thisParentNodeID); end end validNodes = [firstSomaNode; validNodes; additionalValidNodes']; validNodes = unique(validNodes); nodeID = nodeID(validNodes); nodeType = nodeType(validNodes); parentNodeID = parentNodeID(validNodes); xPos = xPos(validNodes); yPos = yPos(validNodes); zPos = zPos(validNodes); radii = radii(validNodes); features = features(validNodes, :); for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end nodes = [xPos yPos zPos]; edges = [nodeID parentNodeID]; edges(any(edges==-1,2),:) = []; %nodeTypes = unique(nodeType)'; %[nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features); % remove the root nodes until the first node %[nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features); % remove zero branches nodes = nodes + 1; % added on Mar 7, 2012 - band tracing starts at 1 - relevant if the tree will be warped somaNode = find(nodeType == 1, 1); % swap on edges edges(edges==1) = 0; edges(edges==somaNode) = 1; edges(edges==0) = somaNode; % swap on nodes tmp = nodes(1,:); nodes(1,:) = nodes(somaNode,:); nodes(somaNode,:) = tmp; % swap on radii tmpR = radii(1); radii(1) = radii(somaNode); radii(somaNode) = tmpR; % swap on features tmpF = features(1,:); features(1,:) = features(somaNode,:); features(somaNode,:) = tmpF; % swap on node types tmpT = nodeType(1); nodeType(1) = nodeType(somaNode,:); nodeType(somaNode,:) = tmpT; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features) if size(nodes,1) < 2 return; end % node 1 is assigned as the root node root = 1; expandedEdges = [edges edges(:,1)]; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); while numel(child) < 2 nodes = [nodes(1:root-1,:); nodes(root+1:end,:)]; radii = [radii(1:root-1); radii(root+1:end)]; features = [features(1:root-1,:); features(root+1:end,:)]; edges(any(edges==root,2),:) = []; edges(edges>root) = edges(edges>root) - 1; expandedEdges = [edges edges(:,1)]; if child > root child = child-1; end root = child; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features) kk = 1; while kk < size(edges,1) node1 = edges(kk,1); node2 = edges(kk,2); if norm(nodes(node1,:)-nodes(node2,:)) < 1e-10 % BE CAREFUL / ARBITRARY edges(edges==node1) = node2; edges(edges>node1) = edges(edges>node1)-1; edges(kk,:) = []; % remove edge nodes(node1,:) = []; % remove node radii(node1) = []; % remove area features(node1,:) = []; % remove features else kk = kk + 1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii] = removeOutOfBoundsBranches(nodes,edges,radii,bounds) if size(nodes,1) < 2 return; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); while ~isempty(thisNode) selfOrDescendant = selfOrDescendantFromEdges(edges, thisNode, thisNode); edges(ismember(edges(:,1),selfOrDescendant) | ismember(edges(:,2),selfOrDescendant),:) = []; nodes(selfOrDescendant,:) = []; radii(selfOrDescendant) = []; selfOrDescendent = sort(selfOrDescendant,'descend'); for kk=1:numel(selfOrDescendant) nn=selfOrDescendant(kk); edges(edges>nn) = edges(edges>nn)-1; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sod = selfOrDescendantFromEdges(edges, sod, node) children = edges(find(edges(:,1)==node),2); sod = [sod children]; if ~isempty(children) for kk=1:numel(children) sod = selfOrDescendantFromEdges(edges, sod, children(kk)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree,rawLength,nodes,edges] = generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,uniformCSAreas) areas = pi*radii.^2; % 1 is assumed to be the root node. edges is nx2: each row is [child parent] h = hist(edges(:,2),[1:size(nodes,1)]); irreducibleNodes = union(find(h~=1),1); % 1 is the root node % put all the irreducible nodes at the beginning for kk = 1:numel(irreducibleNodes) % swap on edges edges(edges==kk) = 0; edges(edges==irreducibleNodes(kk)) = kk; edges(edges==0) = irreducibleNodes(kk); % swap on nodes tmp = nodes(kk,:); nodes(kk,:) = nodes(irreducibleNodes(kk),:); nodes(irreducibleNodes(kk),:) = tmp; % swap on areas tmpA = areas(kk); areas(kk) = areas(irreducibleNodes(kk)); areas(irreducibleNodes(kk)) = tmpA; % swap on features tmpF = features(kk,:); features(kk,:) = features(irreducibleNodes(kk),:); features(irreducibleNodes(kk),:) = tmpF; end numelNodes = numel(irreducibleNodes); %initialize tree with root as 1 tree{1}{1} = []; tree{1}{3} = nodes(1,:); tree{1}{4}{1} = nodes(1,:); tree{1}{4}{2} = 0; tree{1}{4}{3} = [[0;0;0] [0;0;0]]; tree{1}{4}{4} = 0; for kk = 1:numelNodes tree{kk}{2} = []; end rawLength = 0; for kk = 2:numelNodes tmpParent = edges(find(edges(:,1)==kk),2); % assume that the edges are ordered pairs: (child, parent) path = nodes(kk,:); thisFeature = features(kk, :); if uniformCSAreas pathAreas = 1; else pathAreas = (areas(kk)+areas(tmpParent)+sqrt(areas(kk)*areas(tmpParent)))/3; end while tmpParent > numelNodes newTmpParent = edges(find(edges(:,1)==tmpParent),2); path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; if uniformCSAreas pathAreas = [pathAreas; 1]; else pathAreas = [pathAreas; (areas(tmpParent)+areas(newTmpParent)+sqrt(areas(tmpParent)*areas(newTmpParent)))/3]; % now modeled as a cylinder end tmpParent = newTmpParent; end path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; rawPathLengths = sqrt(sum(diff(path,1,1).^2,2)); rawLength = rawLength + sum(rawPathLengths); tree{kk}{1} = tmpParent; tree{tmpParent}{2} = [tree{tmpParent}{2} kk]; tree{kk}{3} = nodes(kk,:); tree{kk}{4}{1} = path; tree{kk}{4}{2} = rawPathLengths; tree{kk}{4}{4} = pathAreas; tree{kk}{4}{5} = thisFeature; end tree = calculateDistanceFromSoma(tree, 1, []); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = pruneShortLeaves(tree,lengthThreshold) if numel(tree)<2 return; end root = rootFinder(tree); leaves = findLeaves(tree); leaves = setdiff(leaves, tree{root}{2})'; leaves = [leaves zeros(size(leaves))]; for kk = 1:size(leaves,1) leaves(kk,2) = sum(tree{leaves(kk)}{4}{2}); end leaves = sortrows(leaves,2); leaves = leaves(:,1); counter = 1; while counter <= numel(leaves) if (sum(tree{leaves(counter)}{4}{2}) > lengthThreshold) leaves(counter) = []; else counter = counter + 1; end end for counter = 1:numel(leaves) leaf = leaves(counter); if (sum(tree{leaf}{4}{2}) <= lengthThreshold) parent = tree{leaf}{1}; siblings = setdiff(tree{parent}{2},leaf); % remove the leaf from the child relationship tree{parent}{2} = setdiff(tree{parent}{2}, leaf); % change node numbers of parents/children if larger than this leaf's number for node = 1:numel(tree) if tree{node}{1} > leaf tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > leaf) = children(children > leaf)-1; end % update the parent, sibling, leaf numbers parent(parent>leaf) = parent(parent>leaf)-1; siblings(siblings>leaf) = siblings(siblings>leaf)-1; leaves(leaves>leaf) = leaves(leaves>leaf)-1; % remove leaf from tree tree(leaf) = []; % update the root root = rootFinder(tree); % if the removal made the parent node a reducible node... if (numel(siblings) == 1) && (parent ~= root) % the grandparent removes the reducible parent from the list of children, and inherits the single child tree{tree{parent}{1}}{2} = [setdiff(tree{tree{parent}{1}}{2},parent) siblings]; % the single child's parent becomes the grandparent tree{siblings}{1} = tree{parent}{1}; % the single child adds the reducible node's geometric information to itself tree{siblings}{4}{1} = [tree{siblings}{4}{1}(1:end-1,:); tree{parent}{4}{1}]; % critical nodes tree{siblings}{4}{2} = [tree{siblings}{4}{2}; tree{parent}{4}{2}]; % lengths % tree{siblings}{4}{3} = [tree{siblings}{4}{3} tree{parent}{4}{3}(:,2:end)]; % orientations tree{siblings}{4}{4} = [tree{siblings}{4}{4}; tree{parent}{4}{4}]; % areas tree{siblings}{4}{5} = [tree{siblings}{4}{5}; tree{parent}{4}{5}]; % features % if isempty(tree{siblings}{4}{5}) % tree{siblings}{4}{5} = tree{parent}{4}{5}; % else % tree{siblings}{4}{5} = [tree{siblings}{4}{5}; uint32(tree{parent}{4}{5}(2:end)+numel(tree{siblings}{4}{5})-1)]; % end % change node numbers of parents/children if larger than the parent's number for node = 1:numel(tree) if tree{node}{1} > parent tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > parent) = children(children > parent)-1; end % update leaf numbers leaves(leaves>parent) = leaves(leaves>parent)-1; % remove the reducible parent from tree tree(parent) = []; end end tmpLeaves = leaves(counter+1:end); tmpLeaves = [tmpLeaves zeros(size(tmpLeaves))]; if ~isempty(tmpLeaves) for kk = 1:size(tmpLeaves,1) tmpLeaves(kk,2) = sum(tree{tmpLeaves(kk,1)}{4}{2}); end tmpLeaves = sortrows(tmpLeaves,2); leaves(counter+1:end) = tmpLeaves(:,1); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [localMass,newNodes] = switchToMassRepresentation(nodes,edges) localMass = zeros(size(nodes,1),1); newNodes = zeros(size(nodes,1),3); for kk=1:size(nodes,1); parent = edges(find(edges(:,1)==kk),2); if ~isempty(parent) localMass(kk) = norm(nodes(parent,:)-nodes(kk,:)); newNodes(kk,:) = (nodes(parent,:)+nodes(kk,:))/2; else localMass(kk) = 0; newNodes(kk,:) = nodes(kk,:); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function principalAxes = calculatePrincipalAxes(xyz, weights) if nargin < 2; weights = ones(size(xyz,1),1); end; % find the inertia tensor inertiaTensor = zeros(3); inertiaTensor(1,1) = sum(weights .* (xyz(:,2).^2 + xyz(:,3).^2)); inertiaTensor(2,2) = sum(weights .* (xyz(:,1).^2 + xyz(:,3).^2)); inertiaTensor(3,3) = sum(weights .* (xyz(:,1).^2 + xyz(:,2).^2)); inertiaTensor(1,2) = -sum(weights .* xyz(:,1) .* xyz(:,2)); inertiaTensor(1,3) = -sum(weights .* xyz(:,1) .* xyz(:,3)); inertiaTensor(2,3) = -sum(weights .* xyz(:,2) .* xyz(:,3)); inertiaTensor(2,1) = inertiaTensor(1,2); inertiaTensor(3,1) = inertiaTensor(1,3); inertiaTensor(3,2) = inertiaTensor(2,3); % find the principal axes of the inertia tensor [principalAxes, evMatrix] = eig(inertiaTensor); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tr = normalizeNeuron(tr) % normalize the total dendritic length lengthOnly = true; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{2}) tr{node}{4}{1} = tr{node}{4}{1}/totalLength; tr{node}{4}{2} = tr{node}{4}{2}/totalLength; tr{node}{4}{3} = tr{node}{4}{3}/totalLength; end tr{node}{3} = tr{node}{3}/totalLength; end % normalize the total dendritic volume by changing the cross-sectional areas, and keeping the lengths the same lengthOnly = false; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{4}) tr{node}{4}{4} = tr{node}{4}{4}/totalLength; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree nodes areas rawLength] = integrateTree(tree,node,nodes,areas,rawLength,startingPos,interval) tree{node}{3} = startingPos; children = tree{node}{2}; for child = 1:numel(children) thisBranch = tree{children(child)}{4}{1}; thisBranch = thisBranch(end:-1:1,:); branchAreas = tree{children(child)}{4}{4}; branchAreas = branchAreas(end:-1:1); [thisBranch pathLengths branchAreas] = integrateBranch(thisBranch,branchAreas,startingPos,interval); tree{children(child)}{4}{1} = thisBranch(end:-1:1,:); nodes = [nodes; tree{children(child)}{4}{1}]; tree{children(child)}{4}{2} = pathLengths(end:-1:1); tree{children(child)}{4}{4} = branchAreas; areas = [areas; tree{children(child)}{4}{4}]; rawLength = rawLength+sum(pathLengths); [tree nodes areas rawLength] = integrateTree(tree,children(child),nodes,areas,rawLength,thisBranch(end,:),interval); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [path pathLengths newAreas] = integrateBranch(branchCoordinates,areas,startingPos,interval) path=startingPos; curPos=0; curEdgePos=0; nextPillar=2; curCoord = branchCoordinates(1,:); edgeVectors = diff(branchCoordinates,1,1); edgeLengths=sqrt(sum(edgeVectors.^2,2)); totalLength=sum(edgeLengths); curVec=edgeVectors(1,:); curVec = curVec/norm(curVec); nextPillarDistance=edgeLengths(1); newAreas = []; while curPos<totalLength xyzSteps = abs((-curCoord+sqrt(curCoord.^2+2*curVec*interval))./(curVec+1e-6)); step = min(max(xyzSteps),nextPillarDistance); path = [path; path(end,:)+curCoord*step+curVec*step^2/2]; curEdgePos = curEdgePos+step; curCoord = curCoord+step*curVec; curPos = curPos+step; nextPillarDistance = nextPillarDistance-step; newAreas = [areas(min(nextPillar,size(edgeVectors,1))); newAreas]; % inverted orientation for areas to avoid inversion of array in integrateTree! if nextPillarDistance<totalLength/1e6 % 1e-6 precision if nextPillar>size(edgeVectors,1) break; end curCoord=branchCoordinates(nextPillar,:); curVec=edgeVectors(nextPillar,:); curVec=curVec/norm(curVec); nextPillarDistance = edgeLengths(nextPillar,:); nextPillar=nextPillar+1; curEdgePos=0; end end pathLengths = sqrt(sum(diff(path,1,1).^2,2)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = rotateTree(tree,rotMatrix) for kk = 1:numel(tree) tree{kk}{3} = tree{kk}{3}*rotMatrix; if ~isempty(tree{kk}{4}{1}) tree{kk}{4}{1} = tree{kk}{4}{1}*rotMatrix; tree{kk}{4}{3} = rotMatrix' * tree{kk}{4}{3}; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rotMatrix = findRotationMatrix(rotAxis,rotAngle) ux=rotAxis(1); uy=rotAxis(2); uz=rotAxis(3); rotMatrix = (cos(rotAngle)*eye(3) + sin(rotAngle)*[0 -uz uy;uz 0 -ux;-uy ux 0] + (1-cos(rotAngle))*kron(rotAxis,rotAxis'))'; if any(any(isnan(rotMatrix))) rotMatrix = eye(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = calculateDistanceFromSoma(tree, thisNode, parent) if ~isempty(parent) reference = tree{parent}{4}{5}(1, 4); tmp = cumsum([0; tree{thisNode}{4}{2}]); somaBorder = find(tree{thisNode}{4}{5}(:,19-7)<2, 1); if ~isempty(somaBorder) && somaBorder>1 tmp(somaBorder:end) = tmp(somaBorder-1); end tree{thisNode}{4}{5}(:, 4) = reference + tmp(end) - tmp; else tree{thisNode}{4}{5}(1, 4) = 0; end children = tree{thisNode}{2}; for kk = 1:numel(children) tree = calculateDistanceFromSoma(tree, children(kk), thisNode); end
github
uygarsumbul/spines-master
readDataset_spines_mod.m
.m
spines-master/repo/readDataset_spines_mod.m
21,610
utf_8
a3561864846b71a1cbd86029910f5e8c
function [allTrees, allPAs] = readDataset_spines(code,directory,options) if ~isfield(options,'normalize') || isempty(options.normalize); normalize = false; else; normalize = options.normalize; end; if ~isfield(options,'absoluteLengths') || isempty(options.absoluteLengths); absoluteLengths = true; else; absoluteLengths = options.absoluteLengths; end; if ~isfield(options,'neuronParts') || isempty(options.neuronParts); neuronParts = [-10:10]; else; neuronParts = options.neuronParts; end; if ~isfield(options,'anisotropyDivisors') || isempty(options.anisotropyDivisors); anisotropyDivisors = [1 1 1]; else; anisotropyDivisors = options.anisotropyDivisors; end; if ~isfield(options,'SCALECONSTANT') || isempty(options.SCALECONSTANT); SCALECONSTANT = 1; else; SCALECONSTANT = options.SCALECONSTANT; end; if ~isfield(options,'removeShortLeaves') || isempty(options.removeShortLeaves); removeShortLeaves = false; else; removeShortLeaves = options.removeShortLeaves; end; if ~isfield(options,'pruneRatio') || isempty(options.pruneRatio); pruneRatio = 1; else; pruneRatio = options.pruneRatio; end; if ~isfield(options,'removeBranches') || isempty(options.removeBranches); removeBranches = false; else; removeBranches = options.removeBranches; end; if ~isfield(options,'resolution') || isempty(options.resolution); resolution = [1 1 1]; else; resolution = options.resolution; end; allTrees = cell(0); allNodesAndEdges = cell(0); for kk = 1:numel(code) thisFileName = strcat(directory,code{kk}{1}); %,code{kk}{2}); [nodes,edges,radii,nodeTypes,features,~] = readSWCfile(thisFileName,neuronParts,resolution); soma = find(nodeTypes==1,1); for dd=1:3; nodes(:,dd)=nodes(:,dd)-(nodes(soma,dd)); end; principalAxes = calculatePrincipalAxes(nodes); allPAs(:,kk)=principalAxes(:,1); features = [features nodeTypes]; nodes(:,1) = nodes(:,1)/anisotropyDivisors(1); nodes(:,2) = nodes(:,2)/anisotropyDivisors(2); nodes(:,3) = nodes(:,3)/anisotropyDivisors(3); [tree,rawLength,nodes,edges]=generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,false); % 1:soma, 2:axon, 3:basal dendrite, 4:apical dendrite if removeShortLeaves; tree = pruneShortLeaves(tree,treeLength(tree)*pruneRatio); end; if normalize; tree = normalizeNeuron(tree); end; allTrees{end+1} = tree; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,nodeType,features,abort] = readSWCfile(fileName,validNodeTypes,resolution) abort = false; nodes = []; edges = []; nodeTypes = []; validNodeTypes = setdiff(validNodeTypes,1); [nodeID, nodeType, xPos, yPos, zPos, radii, parentNodeID,d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9] = textread(fileName, '%u%d%f%f%f%f%d%d%d%f%f%f%f%f%f%f%f%f','commentstyle', 'shell'); xPos = xPos * resolution(1); yPos = yPos * resolution(2); zPos = zPos * resolution(3); features = [d1,d2,f1,f2,f3,f4,f5,f6,f7,f8,f9]; if ~any(parentNodeID==-1) disp(strcat('root not found in ',fileName)); nodes = []; edges = []; radii = []; nodeTypes = []; features = []; abort = true; return; end nodeType(find(parentNodeID==-1))=1; % Every tree should start from a node of type 1 (soma) firstSomaNode = find(nodeType == 1 & parentNodeID == -1, 1); somaNodes = find(nodeType == 1); somaX = mean(xPos(somaNodes)); somaY = mean(yPos(somaNodes)); somaZ = mean(zPos(somaNodes)); % set soma radius to 0, to avoid multiple counting of soma volume through different subsets. ignore soma volume somaRadius = 0; %mean(radii(somaNodes)); xPos(firstSomaNode) = somaX; yPos(firstSomaNode) = somaY; zPos(firstSomaNode) = somaZ; radii(firstSomaNode) = somaRadius; features(firstSomaNode,:) = zeros(1,size(features,2)); parentNodeID(ismember(parentNodeID,somaNodes)) = firstSomaNode; % assign a single soma parent nodesToDelete = setdiff(somaNodes,firstSomaNode); % delete all the soma nodes except for the firstSomaNode nodeID(nodesToDelete)=[]; nodeType(nodesToDelete)=[]; xPos(nodesToDelete)=[]; yPos(nodesToDelete)=[]; zPos(nodesToDelete)=[]; radii(nodesToDelete)=[]; parentNodeID(nodesToDelete)=[]; features(nodesToDelete,:)=[]; for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end validNodes = nodeID(ismember(nodeType,validNodeTypes)); additionalValidNodes = []; for kk = 1:numel(validNodes) thisParentNodeID = parentNodeID(validNodes(kk)); thisParentNodeType = nodeType(thisParentNodeID); while ~ismember(thisParentNodeType,validNodeTypes) if thisParentNodeType == 1 break; end additionalValidNodes = union(additionalValidNodes, thisParentNodeID); nodeType(thisParentNodeID) = validNodeTypes(1); thisParentNodeID = parentNodeID(thisParentNodeID); thisParentNodeType = nodeType(thisParentNodeID); end end validNodes = [firstSomaNode; validNodes; additionalValidNodes']; validNodes = unique(validNodes); nodeID = nodeID(validNodes); nodeType = nodeType(validNodes); parentNodeID = parentNodeID(validNodes); xPos = xPos(validNodes); yPos = yPos(validNodes); zPos = zPos(validNodes); radii = radii(validNodes); features = features(validNodes, :); for kk = 1:numel(nodeID) while ~any(nodeID==kk) nodeID(nodeID>kk) = nodeID(nodeID>kk)-1; parentNodeID(parentNodeID>kk) = parentNodeID(parentNodeID>kk)-1; end end nodes = [xPos yPos zPos]; edges = [nodeID parentNodeID]; edges(any(edges==-1,2),:) = []; %nodeTypes = unique(nodeType)'; %[nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features); % remove the root nodes until the first node %[nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features); % remove zero branches nodes = nodes + 1; % added on Mar 7, 2012 - band tracing starts at 1 - relevant if the tree will be warped somaNode = find(nodeType == 1, 1); % swap on edges edges(edges==1) = 0; edges(edges==somaNode) = 1; edges(edges==0) = somaNode; % swap on nodes tmp = nodes(1,:); nodes(1,:) = nodes(somaNode,:); nodes(somaNode,:) = tmp; % swap on radii tmpR = radii(1); radii(1) = radii(somaNode); radii(somaNode) = tmpR; % swap on features tmpF = features(1,:); features(1,:) = features(somaNode,:); features(somaNode,:) = tmpF; % swap on node types tmpT = nodeType(1); nodeType(1) = nodeType(somaNode,:); nodeType(somaNode,:) = tmpT; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeImproperRootNodes(nodes,edges,radii,features) if size(nodes,1) < 2 return; end % node 1 is assigned as the root node root = 1; expandedEdges = [edges edges(:,1)]; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); while numel(child) < 2 nodes = [nodes(1:root-1,:); nodes(root+1:end,:)]; radii = [radii(1:root-1); radii(root+1:end)]; features = [features(1:root-1,:); features(root+1:end,:)]; edges(any(edges==root,2),:) = []; edges(edges>root) = edges(edges>root) - 1; expandedEdges = [edges edges(:,1)]; if child > root child = child-1; end root = child; child = expandedEdges([zeros(size(edges,1),1) edges==root]>0); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii,features] = removeZeroLengthEdges(nodes,edges,radii,features) kk = 1; while kk < size(edges,1) node1 = edges(kk,1); node2 = edges(kk,2); if norm(nodes(node1,:)-nodes(node2,:)) < 1e-10 % BE CAREFUL / ARBITRARY edges(edges==node1) = node2; edges(edges>node1) = edges(edges>node1)-1; edges(kk,:) = []; % remove edge nodes(node1,:) = []; % remove node radii(node1) = []; % remove area features(node1,:) = []; % remove features else kk = kk + 1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nodes,edges,radii] = removeOutOfBoundsBranches(nodes,edges,radii,bounds) if size(nodes,1) < 2 return; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); while ~isempty(thisNode) selfOrDescendant = selfOrDescendantFromEdges(edges, thisNode, thisNode); edges(ismember(edges(:,1),selfOrDescendant) | ismember(edges(:,2),selfOrDescendant),:) = []; nodes(selfOrDescendant,:) = []; radii(selfOrDescendant) = []; selfOrDescendent = sort(selfOrDescendant,'descend'); for kk=1:numel(selfOrDescendant) nn=selfOrDescendant(kk); edges(edges>nn) = edges(edges>nn)-1; end thisNode=find(nodes(:,1)<bounds.minX | nodes(:,1)>bounds.maxX | nodes(:,2)<bounds.minY | nodes(:,2)>bounds.maxY | nodes(:,3)<bounds.minZ | nodes(:,3)>bounds.maxZ,'first',1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sod = selfOrDescendantFromEdges(edges, sod, node) children = edges(find(edges(:,1)==node),2); sod = [sod children]; if ~isempty(children) for kk=1:numel(children) sod = selfOrDescendantFromEdges(edges, sod, children(kk)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree,rawLength,nodes,edges] = generateIrreducibleDoubleLinkedTree(nodes,edges,radii,features,uniformCSAreas) areas = pi*radii.^2; % 1 is assumed to be the root node. edges is nx2: each row is [child parent] h = hist(edges(:,2),[1:size(nodes,1)]); irreducibleNodes = union(find(h~=1),1); % 1 is the root node % put all the irreducible nodes at the beginning for kk = 1:numel(irreducibleNodes) % swap on edges edges(edges==kk) = 0; edges(edges==irreducibleNodes(kk)) = kk; edges(edges==0) = irreducibleNodes(kk); % swap on nodes tmp = nodes(kk,:); nodes(kk,:) = nodes(irreducibleNodes(kk),:); nodes(irreducibleNodes(kk),:) = tmp; % swap on areas tmpA = areas(kk); areas(kk) = areas(irreducibleNodes(kk)); areas(irreducibleNodes(kk)) = tmpA; % swap on features tmpF = features(kk,:); features(kk,:) = features(irreducibleNodes(kk),:); features(irreducibleNodes(kk),:) = tmpF; end numelNodes = numel(irreducibleNodes); %initialize tree with root as 1 tree{1}{1} = []; tree{1}{3} = nodes(1,:); tree{1}{4}{1} = nodes(1,:); tree{1}{4}{2} = 0; tree{1}{4}{3} = [[0;0;0] [0;0;0]]; tree{1}{4}{4} = 0; for kk = 1:numelNodes tree{kk}{2} = []; end rawLength = 0; for kk = 2:numelNodes tmpParent = edges(find(edges(:,1)==kk),2); % assume that the edges are ordered pairs: (child, parent) path = nodes(kk,:); thisFeature = features(kk, :); if uniformCSAreas pathAreas = 1; else pathAreas = (areas(kk)+areas(tmpParent)+sqrt(areas(kk)*areas(tmpParent)))/3; end while tmpParent > numelNodes newTmpParent = edges(find(edges(:,1)==tmpParent),2); path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; if uniformCSAreas pathAreas = [pathAreas; 1]; else pathAreas = [pathAreas; (areas(tmpParent)+areas(newTmpParent)+sqrt(areas(tmpParent)*areas(newTmpParent)))/3]; % now modeled as a cylinder end tmpParent = newTmpParent; end path = [path; nodes(tmpParent,:)]; thisFeature = [thisFeature; features(tmpParent,:)]; rawPathLengths = sqrt(sum(diff(path,1,1).^2,2)); rawLength = rawLength + sum(rawPathLengths); tree{kk}{1} = tmpParent; tree{tmpParent}{2} = [tree{tmpParent}{2} kk]; tree{kk}{3} = nodes(kk,:); tree{kk}{4}{1} = path; tree{kk}{4}{2} = rawPathLengths; tree{kk}{4}{4} = pathAreas; tree{kk}{4}{5} = thisFeature; end tree = calculateDistanceFromSoma(tree, 1, []); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = pruneShortLeaves(tree,lengthThreshold) if numel(tree)<2 return; end root = rootFinder(tree); leaves = findLeaves(tree); leaves = setdiff(leaves, tree{root}{2})'; leaves = [leaves zeros(size(leaves))]; for kk = 1:size(leaves,1) leaves(kk,2) = sum(tree{leaves(kk)}{4}{2}); end leaves = sortrows(leaves,2); leaves = leaves(:,1); counter = 1; while counter <= numel(leaves) if (sum(tree{leaves(counter)}{4}{2}) > lengthThreshold) leaves(counter) = []; else counter = counter + 1; end end for counter = 1:numel(leaves) leaf = leaves(counter); if (sum(tree{leaf}{4}{2}) <= lengthThreshold) parent = tree{leaf}{1}; siblings = setdiff(tree{parent}{2},leaf); % remove the leaf from the child relationship tree{parent}{2} = setdiff(tree{parent}{2}, leaf); % change node numbers of parents/children if larger than this leaf's number for node = 1:numel(tree) if tree{node}{1} > leaf tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > leaf) = children(children > leaf)-1; end % update the parent, sibling, leaf numbers parent(parent>leaf) = parent(parent>leaf)-1; siblings(siblings>leaf) = siblings(siblings>leaf)-1; leaves(leaves>leaf) = leaves(leaves>leaf)-1; % remove leaf from tree tree(leaf) = []; % update the root root = rootFinder(tree); % if the removal made the parent node a reducible node... if (numel(siblings) == 1) && (parent ~= root) % the grandparent removes the reducible parent from the list of children, and inherits the single child tree{tree{parent}{1}}{2} = [setdiff(tree{tree{parent}{1}}{2},parent) siblings]; % the single child's parent becomes the grandparent tree{siblings}{1} = tree{parent}{1}; % the single child adds the reducible node's geometric information to itself tree{siblings}{4}{1} = [tree{siblings}{4}{1}(1:end-1,:); tree{parent}{4}{1}]; % critical nodes tree{siblings}{4}{2} = [tree{siblings}{4}{2}; tree{parent}{4}{2}]; % lengths % tree{siblings}{4}{3} = [tree{siblings}{4}{3} tree{parent}{4}{3}(:,2:end)]; % orientations tree{siblings}{4}{4} = [tree{siblings}{4}{4}; tree{parent}{4}{4}]; % areas tree{siblings}{4}{5} = [tree{siblings}{4}{5}; tree{parent}{4}{5}]; % features % if isempty(tree{siblings}{4}{5}) % tree{siblings}{4}{5} = tree{parent}{4}{5}; % else % tree{siblings}{4}{5} = [tree{siblings}{4}{5}; uint32(tree{parent}{4}{5}(2:end)+numel(tree{siblings}{4}{5})-1)]; % end % change node numbers of parents/children if larger than the parent's number for node = 1:numel(tree) if tree{node}{1} > parent tree{node}{1} = tree{node}{1}-1; end children = tree{node}{2}; tree{node}{2}(children > parent) = children(children > parent)-1; end % update leaf numbers leaves(leaves>parent) = leaves(leaves>parent)-1; % remove the reducible parent from tree tree(parent) = []; end end tmpLeaves = leaves(counter+1:end); tmpLeaves = [tmpLeaves zeros(size(tmpLeaves))]; if ~isempty(tmpLeaves) for kk = 1:size(tmpLeaves,1) tmpLeaves(kk,2) = sum(tree{tmpLeaves(kk,1)}{4}{2}); end tmpLeaves = sortrows(tmpLeaves,2); leaves(counter+1:end) = tmpLeaves(:,1); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [localMass,newNodes] = switchToMassRepresentation(nodes,edges) localMass = zeros(size(nodes,1),1); newNodes = zeros(size(nodes,1),3); for kk=1:size(nodes,1); parent = edges(find(edges(:,1)==kk),2); if ~isempty(parent) localMass(kk) = norm(nodes(parent,:)-nodes(kk,:)); newNodes(kk,:) = (nodes(parent,:)+nodes(kk,:))/2; else localMass(kk) = 0; newNodes(kk,:) = nodes(kk,:); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function principalAxes = calculatePrincipalAxes(xyz, weights) if nargin < 2; weights = ones(size(xyz,1),1); end; % find the inertia tensor inertiaTensor = zeros(3); inertiaTensor(1,1) = sum(weights .* (xyz(:,2).^2 + xyz(:,3).^2)); inertiaTensor(2,2) = sum(weights .* (xyz(:,1).^2 + xyz(:,3).^2)); inertiaTensor(3,3) = sum(weights .* (xyz(:,1).^2 + xyz(:,2).^2)); inertiaTensor(1,2) = -sum(weights .* xyz(:,1) .* xyz(:,2)); inertiaTensor(1,3) = -sum(weights .* xyz(:,1) .* xyz(:,3)); inertiaTensor(2,3) = -sum(weights .* xyz(:,2) .* xyz(:,3)); inertiaTensor(2,1) = inertiaTensor(1,2); inertiaTensor(3,1) = inertiaTensor(1,3); inertiaTensor(3,2) = inertiaTensor(2,3); % find the principal axes of the inertia tensor [principalAxes, evMatrix] = eig(inertiaTensor); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tr = normalizeNeuron(tr) % normalize the total dendritic length lengthOnly = true; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{2}) tr{node}{4}{1} = tr{node}{4}{1}/totalLength; tr{node}{4}{2} = tr{node}{4}{2}/totalLength; tr{node}{4}{3} = tr{node}{4}{3}/totalLength; end tr{node}{3} = tr{node}{3}/totalLength; end % normalize the total dendritic volume by changing the cross-sectional areas, and keeping the lengths the same lengthOnly = false; totalLength = treeLength(tr,rootFinder(tr),lengthOnly); for node = 1:numel(tr) if ~isempty(tr{node}{4}{4}) tr{node}{4}{4} = tr{node}{4}{4}/totalLength; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tree nodes areas rawLength] = integrateTree(tree,node,nodes,areas,rawLength,startingPos,interval) tree{node}{3} = startingPos; children = tree{node}{2}; for child = 1:numel(children) thisBranch = tree{children(child)}{4}{1}; thisBranch = thisBranch(end:-1:1,:); branchAreas = tree{children(child)}{4}{4}; branchAreas = branchAreas(end:-1:1); [thisBranch pathLengths branchAreas] = integrateBranch(thisBranch,branchAreas,startingPos,interval); tree{children(child)}{4}{1} = thisBranch(end:-1:1,:); nodes = [nodes; tree{children(child)}{4}{1}]; tree{children(child)}{4}{2} = pathLengths(end:-1:1); tree{children(child)}{4}{4} = branchAreas; areas = [areas; tree{children(child)}{4}{4}]; rawLength = rawLength+sum(pathLengths); [tree nodes areas rawLength] = integrateTree(tree,children(child),nodes,areas,rawLength,thisBranch(end,:),interval); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [path pathLengths newAreas] = integrateBranch(branchCoordinates,areas,startingPos,interval) path=startingPos; curPos=0; curEdgePos=0; nextPillar=2; curCoord = branchCoordinates(1,:); edgeVectors = diff(branchCoordinates,1,1); edgeLengths=sqrt(sum(edgeVectors.^2,2)); totalLength=sum(edgeLengths); curVec=edgeVectors(1,:); curVec = curVec/norm(curVec); nextPillarDistance=edgeLengths(1); newAreas = []; while curPos<totalLength xyzSteps = abs((-curCoord+sqrt(curCoord.^2+2*curVec*interval))./(curVec+1e-6)); step = min(max(xyzSteps),nextPillarDistance); path = [path; path(end,:)+curCoord*step+curVec*step^2/2]; curEdgePos = curEdgePos+step; curCoord = curCoord+step*curVec; curPos = curPos+step; nextPillarDistance = nextPillarDistance-step; newAreas = [areas(min(nextPillar,size(edgeVectors,1))); newAreas]; % inverted orientation for areas to avoid inversion of array in integrateTree! if nextPillarDistance<totalLength/1e6 % 1e-6 precision if nextPillar>size(edgeVectors,1) break; end curCoord=branchCoordinates(nextPillar,:); curVec=edgeVectors(nextPillar,:); curVec=curVec/norm(curVec); nextPillarDistance = edgeLengths(nextPillar,:); nextPillar=nextPillar+1; curEdgePos=0; end end pathLengths = sqrt(sum(diff(path,1,1).^2,2)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = rotateTree(tree,rotMatrix) for kk = 1:numel(tree) tree{kk}{3} = tree{kk}{3}*rotMatrix; if ~isempty(tree{kk}{4}{1}) tree{kk}{4}{1} = tree{kk}{4}{1}*rotMatrix; tree{kk}{4}{3} = rotMatrix' * tree{kk}{4}{3}; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rotMatrix = findRotationMatrix(rotAxis,rotAngle) ux=rotAxis(1); uy=rotAxis(2); uz=rotAxis(3); rotMatrix = (cos(rotAngle)*eye(3) + sin(rotAngle)*[0 -uz uy;uz 0 -ux;-uy ux 0] + (1-cos(rotAngle))*kron(rotAxis,rotAxis'))'; if any(any(isnan(rotMatrix))) rotMatrix = eye(3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tree = calculateDistanceFromSoma(tree, thisNode, parent) if ~isempty(parent) reference = tree{parent}{4}{5}(1, 4); tmp = cumsum([0; tree{thisNode}{4}{2}]); somaBorder = find(tree{thisNode}{4}{5}(:,19-7)<2, 1); if ~isempty(somaBorder) && somaBorder>1 tmp(somaBorder:end) = tmp(somaBorder-1); end tree{thisNode}{4}{5}(:, 4) = reference + tmp(end) - tmp; else tree{thisNode}{4}{5}(1, 4) = 0; end children = tree{thisNode}{2}; for kk = 1:numel(children) tree = calculateDistanceFromSoma(tree, children(kk), thisNode); end
github
uygarsumbul/spines-master
save1000ShuffledTrees.m
.m
spines-master/repo/save1000ShuffledTrees.m
1,830
utf_8
f5430488baa773ac073930204d1cfc86
function save1000ShuffledTrees code{1}{1} = 'aibs_8_spinerecon_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_9_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_13_mouse2_spinerecon_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_14_stitched_connected_corrected_labeled.eswc'; % added on May 19, 2017 code{end+1}{1} = 'aibs_18_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_19_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_20_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_21_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_22_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_23_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_24_stitched_connected_labeled.eswc'; code{end+1}{1} = 'aibs_25_stitched_connected_labeled.eswc'; directory = '/home/uygar/spines/data/upsampledFinalReconstructions/'; % _updated3-22-17/'; options.resolution = [0.12 0.12 0.1]; options.resolution20x = [0.62 0.62 0.75]; parfor kk = 1:1000 trees = readDataset_spines_mod_shuffleNodes(code,directory,options); mySaveFunction(kk, trees); end trees = readDataset_spines_mod(code,directory,options); save /home/uygar/spines/data/shuffledTrees/trueTrees.mat trees function mySaveFunction(kk, trees) filename = ['/home/uygar/spines/data/shuffledTrees/shuffledTrees_' num2str(kk) '.mat']; save(filename, 'trees');
github
JinleiMa/Image-fusion-with-VSM-and-WLS-master
RollingGuidanceFilter_Guided.m
.m
Image-fusion-with-VSM-and-WLS-master/RollingGuidanceFilter_Guided.m
2,141
utf_8
ebf8d74ce32feb253b6ff563aea8ded5
% % Rolling Guidance Filter % % res = RollingGuidanceFilter(I,sigma_s,sigma_r,iteration) filters image % "I" by removing its small structures. The borderline between "small" % and "large" is determined by the parameter sigma_s. The sigma_r is % fixed to 0.1. The filter is an iteration process. "iteration" is used % to control the number of iterations. % % Paras: % @I : input image, DOUBLE image, any # of channels % @sigma_s : spatial sigma (default 3.0). Controlling the spatial % weight of bilateral filter and also the filtering scale of % rolling guidance filter. % @sigma_r : range sigma (default 0.1). Controlling the range weight of % bilateral filter. % @iteration : the iteration number of rolling guidance (default 4). % % % Example % ========== % I = im2double(imread('image.png')); % res = RollingGuidanceFilter(I,3,0.05,4); % figure, imshow(res); % % % Note % ========== % This implementation filters multi-channel/color image by separating its % channels, so the result of this implementation will be different with % that in the corresponding paper. To generate the results in the paper, % please refer to our executable file or C++ implementation on our % website. % % ========== % The Code is created based on the method described in the following paper: % [1] "Rolling Guidance Filter", Qi Zhang, Li Xu, Jiaya Jia, European % Conference on Computer Vision (ECCV), 2014 % % The code and the algorithm are for non-comercial use only. % % % Author: Qi Zhang ([email protected]) % Date : 08/14/2014 % Version : 1.0 % Copyright 2014, The Chinese University of Hong Kong. % function res = RollingGuidanceFilter_Guided(I,sigma_s,sigma_r,iteration) if ~exist('iteration','var') iteration = 4; end if ~exist('sigma_s','var') sigma_s = 3; end if ~exist('sigma_r','var') sigma_r = 0.1; end res = gaussFilter(I,sigma_s); for i=1:iteration for c=1:size(I,3) G = res(:,:,c); res(:,:,c) = guidedfilter(G,I(:,:,c),sigma_s,sigma_r^2); end end end
github
linhan94/robotics-slam-playground-master
visual_odometry_skeleton.m
.m
robotics-slam-playground-master/src/visual_odometry_skeleton.m
15,174
utf_8
b726de421122268eef9e9911a1177c9c
clear import gtsam.* %% Data Options NUM_FRAMES = 0; % 0 for all NUM_INITIALISE = 10; %TODO find a nice values WINDOW_SIZE = 6; %TODO find a nice value MAX_ITERATIONS = 30; LOOP_THRESHOLD = 1000; ADD_NOISE = true; % Try false for debugging (only) SAVE_FIGURES = true; % Save plots to hard-drive? PLOT_LANDMARKS = true; PLOT_FEATURES = true; outdir = strcat(fileparts(mfilename('fullpath')), '/output/'); blenddir = strcat(fileparts(mfilename('fullpath')), '/../blender/'); mkdir(outdir); %% Load data global features_gt; global camera_gt; global camera_out; global landmarks_gt; global landmarks_out; global landmarks_used; global calib; camera_gt = dlmread(strcat(blenddir, 'camera_poses.txt')); % each line is: frame_id,x,y,z,qx,qy,qz,qw camera_out = zeros(size(camera_gt)); % each line is: frame_id,x,y,z,qx,qy,qz,qw features_gt = dlmread(strcat(blenddir, 'tracks_dist.txt')); % each line is list of: landmark_id,feature_x,feature_y,feature_d,... landmarks_gt = dlmread(strcat(blenddir, 'landmarks_3d.txt')); % each line is: x,y,z landmarks_out = zeros(size(landmarks_gt)); % each line is: x,y,z,last_seen_frame_id % This table stores the last usage of each landmark (frame_id, whenever the % landmark was visible somewhere in the window). % The structure is used for two purposes: % 1st: Use landmarks only once, when building a window % 2nd: Decide whether a loop occured, based on stored frame-IDs landmarks_used = zeros(size(landmarks_gt,1),1); if NUM_FRAMES < 1 NUM_FRAMES = size(camera_gt, 1); end calib = Cal3_S2( ... 634.8, ... % focal 634.8, ... % focal 0, ... % skew 480,... % center 270); % center % Setup noise measurementNoiseSigma = 2; pointNoiseSigma = 3; pointPriorNoise = noiseModel.Isotropic.Sigma(3,pointNoiseSigma); measurementNoise = noiseModel.Isotropic.Sigma(2,measurementNoiseSigma); GPSNoise = noiseModel.Diagonal.Sigmas([2; 2; 2]); %set up GPS noise with a standard deviation of 2m in position in (x,y,z) %% Sanity checks assert(WINDOW_SIZE <= NUM_INITIALISE); assert(NUM_FRAMES <= size(camera_gt,1)); %% Setup figure figure; % Optionally choose size according to your needs %set(gcf,'units','pixel'); %set(gcf,'papersize',[960,960]); %set(gcf,'paperpositionmode','auto'); subplot(2,1,1); % Top for map, bottom for video axis equal; hold on; % Plot ground-truth trajectory as green line plot3(camera_gt(:,2), camera_gt(:,3), camera_gt(:,4), 'g'); %% Initialise with ground-truth data % Of course, this can not be done in real-life(!) for i=1:NUM_INITIALISE fprintf('Loading ground-truth data for frame %d...\n', i); camera_out(i,:) = camera_gt(i,:); f = 1; % column of current feature ID while f < size(features_gt, 2) && features_gt(i,f) > 0 feature_id = features_gt(i,f); % Initialise the point near ground-truth if ~in_map(feature_id) landmarks_out(feature_id,1:3) = landmarks_gt(feature_id,1:3); landmarks_used(feature_id,1) = NUM_INITIALISE; end f = f + 4; end end %% Add noise to 2D observations if ADD_NOISE disp('Adding noise...') for i=1:NUM_FRAMES % 2D features f = 1; while f < size(features_gt, 2) && features_gt(i,f) > 0 features_gt(i,f+1:f+2) = features_gt(i,f+1:f+2) + measurementNoiseSigma * randn(1,2); f = f + 4; end end end %% Visual-Odometry part: Optimise a window for each new frame for i=NUM_INITIALISE+1:NUM_FRAMES tic % measure time %% Load image (for plotting only) subplot(2,1,2); hold off; img = imread(strcat(blenddir, '/frames/',sprintf('%04d',i),'.jpg')); imshow(img); subplot(2,1,1); %% Adding new frame window_start = i - WINDOW_SIZE; fprintf('Building graph for frame %d (Starting at %d)...\n', i, window_start); graph = NonlinearFactorGraph; initialEstimate = Values; landmarks_in_window = 0; redetected_landmarks = 0; for j=window_start:i if j==i % Initialise assuming constant motion model lPose = get_pose(camera_out,j-1); llPose = get_pose(camera_out,j-2); rPose = llPose.between(lPose); cam_pose = lPose.compose(rPose); % Initialise from last pose (method above is better) % cam_pose = get_pose(camera_out,j-1); else cam_pose = get_pose(camera_out,j); end % GTSAM does not ensure that the rotation component of a pose is % orthogonal, hence do this manually (important!) rdet = det(cam_pose.rotation.matrix); if abs(rdet-1) > 0.0001 fprintf('Correcting R-det: %f \n', rdet); [U,S,V]=svd(cam_pose.rotation.matrix); % TODO, correct pose (single line missing) cam_pose = Pose3(Rot3(U*V'),cam_pose.translation()); end % Add GPS prior % if (j==1||j==250 || j==500) % graph.add(PoseTranslationPrior3D(symbol('p', j), get_pose(camera_gt,j), GPSNoise)); %get location from gound-truth data % end % TODO Initialise camera poses -- do not use positional priors though! initialEstimate.insert(symbol('p', j), cam_pose); % The following loop iterates over the (2D) features within frame 'j' f = 1; % column of current feature ID while f < size(features_gt, 2) && features_gt(j,f) > 0 feature_id = features_gt(j,f); % Initialise the point near ground-truth if landmarks_used(feature_id) ~= i if in_map(feature_id) % This landmark is known to the system % Was it seen in the current window or do we have a % potential loop-closure? if landmarks_used(feature_id) < window_start redetected_landmarks = redetected_landmarks+1; % Skip redetected landmarks and potentially close % loop later f = f + 4; continue; else % The landmark was already seen, when building the window of frames feature_pos = get_landmark(landmarks_out, feature_id); end else % "Triangulate" rep = [(features_gt(j,f+1) - calib.px) / calib.fx, (features_gt(j,f+2) - calib.py) / calib.fy, 1] * features_gt(j,f+3); rep = cam_pose.matrix * [rep'; 1]; feature_pos = Point3(rep(1),rep(2),rep(3)); % Ground-Truth position: Don't do this, unless you are debugging! % feature_pos = Point3(landmarks_gt(feature_id,1),landmarks_gt(feature_id,2),landmarks_gt(feature_id,3)); end % Prior & initial estimate % TODO graph.add(PriorFactorPoint3(symbol('f',feature_id), feature_pos, pointPriorNoise)); initialEstimate.insert(symbol('f',feature_id), feature_pos); landmarks_used(feature_id) = i; landmarks_in_window = landmarks_in_window + 1; end % TODO Measurements graph.add(GenericProjectionFactorCal3_S2(Point2(features_gt(j,f+1), features_gt(j,f+2)), measurementNoise, symbol('p', j), symbol('f', feature_id), calib)); f = f + 4; end subplot(2,1,1); end %% Loop-closing if redetected_landmarks > LOOP_THRESHOLD % Build a more complex graph if a loop was detected disp('Loop detected! Building large graph...'); % Add ALL landmarks seen so far disp('Adding all landmarks...'); for l = 1:size(landmarks_used,1) %% TODO if landmarks_used(l) ~= i if in_map(l) feature_pos = get_landmark(landmarks_out, l); graph.add(PriorFactorPoint3(symbol('f',l), feature_pos, pointPriorNoise)); initialEstimate.insert(symbol('f',l), feature_pos); landmarks_used(l) = i; end end %% end % Add measurements disp('Adding all poses & observations...'); graph.add(GenericProjectionFactorCal3_S2(Point2(features_gt(j,f+1), features_gt(j,f+2)),... measurementNoise, symbol('p', j), symbol('f', feature_id), calib)); for j = 1:window_start-1 %% TODO cam_pose = get_pose(camera_out,j); rdet = det(cam_pose.rotation.matrix); if abs(rdet-1) > 0.0001 fprintf('Correcting R-det: %f \n', rdet); [U,S,V]=svd(cam_pose.rotation.matrix); cam_pose = Pose3(Rot3(U*V'),cam_pose.translation()); end % Add GPS prior % if (j==1||j==250 || j==500) % graph.add(PoseTranslationPrior3D(symbol('p', j), get_pose(camera_gt,j), GPSNoise)); % end initialEstimate.insert(symbol('p', j), cam_pose); f = 1; % column of current feature ID while f < size(features_gt, 2) && features_gt(j,f) > 0 %% TODO feature_id = features_gt(j,f); graph.add(GenericProjectionFactorCal3_S2(Point2(features_gt(j,f+1), features_gt(j,f+2)),measurementNoise, symbol('p', j), symbol('f', feature_id), calib)); %% f = f + 4; end end % The following code has to be informed that the window is bigger now window_start = 1; end optimizer = LevenbergMarquardtOptimizer(graph, initialEstimate); initialError = graph.error(initialEstimate); %% Plot ground-truth and initial estimate of markers (2D) subplot(2,1,2); hold on; plot_features(i, 'g+'); % ground-truth %plot_features(i, 'cx', cam_pose, landmarks_gt); % initial estimate subplot(2,1,1); %% Plot ground-truth and initial estimate in 3D % plot3(camera_gt(i,2),camera_gt(i,3),camera_gt(i,4), 'g+'); % plot3(cam_pose.translation().x,cam_pose.translation().y,cam_pose.translation().z,'cx'); %optimizer.optimizeSafely; last_error = initialError; for m=1:MAX_ITERATIONS optimizer.iterate(); %% Print iteration information result = optimizer.values(); error = graph.error(result); fprintf('Initial error: %f, %d.-iteration error: %f (%3.3f %%)\n', initialError, m, error, 100 * error/ initialError); %% Optionally, plot the movement and orientation of the pose during optimisation % (slow) % pose = result.atPose3(symbol('p', i)); % pos = pose.translation(); % mat = pose.matrix; % h = mat * [0;0;1;1]; % This point indicates the orientation of the orientation of the pose % h = [h(1:3)'; pos.x,pos.y,pos.z]; % plot3(pos.x,pos.y,pos.z, 'bo'); % plot3(h(:,1),h(:,2),h(:,3), 'b.'); %% Optionally, plot the movement of features during optimisation % (slow) % subplot(2,1,2); % hold on; % plot_features(i, 'r.', pose, landmarks_gt); % subplot(2,1,1); % Break conditions if error < 10 %TODO find a nice value break end if last_error - error < 1 %TODO find a nice value break end last_error = error; end % result = optimizer.values(); % Optionally, retrieve marginals for plotting % marginals = Marginals(graph, result); error = graph.error(result); fprintf('Initial error: %f, Final error: %f (%3.3f %%)\n', initialError, error, 100 * error/ initialError); fprintf('Landmarks in window: %d\n', landmarks_in_window); % Read all poses that were optimised, 'pose' represents the most recent % frame afterwards for j=window_start:i pose = result.at(symbol('p', j)); pos = pose.translation(); quat = pose.rotation().quaternion(); camera_out(j,:) = [camera_gt(j,1) pos.x pos.y pos.z quat(2) quat(3) quat(4) quat(1)]; end % Read landmarks for l=1:length(landmarks_used) if landmarks_used(l) == i mark = result.at(symbol('f', l)); landmarks_out(l,:) = [mark.x mark.y mark.z]; end end %% Plotting % Plot markers on last frame if PLOT_FEATURES subplot(2,1,2); hold on; plot_features(i, 'rx', pose, landmarks_out); subplot(2,1,1); end % Plot trajectory try delete(tplt); end tplt = plot3(camera_out(1:i,2),camera_out(1:i,3),camera_out(1:i,4), 'r*'); % Plot all landmarks if PLOT_LANDMARKS try delete(mplt); end mplt = plot3(landmarks_out(:,1),landmarks_out(:,2),landmarks_out(:,3), ... 'Marker','.', 'Markersize',1, 'Color','black','LineStyle','none'); end % Update figure and optionally save drawnow if SAVE_FIGURES saveas(gcf, strcat(outdir, sprintf('plot-%04d',i),'.png')); end toc end % Export results to hard-drive disp('Exporting final results...'); dlmwrite(strcat(outdir, 'vo_output_poses.txt'),camera_out,'delimiter','\t','precision',6); %% Some helper functions: function p = get_pose(matrix, index) import gtsam.*; p = Pose3(Rot3.Quaternion(matrix(index,8), matrix(index,5), matrix(index,6), matrix(index,7)), ... Point3(matrix(index,2), matrix(index,3), matrix(index,4))); end function p = get_landmark(matrix, index) import gtsam.*; p = Point3(matrix(index,1),matrix(index,2),matrix(index,3)); end % Returns true if a landmark was previously mapped, otherwise false function t = in_map(landmark_index) import gtsam.*; global landmarks_used; if landmarks_used(landmark_index) > 0 t = true; else t = false; end end % Project 'landmarks' into the fhe frame with ID 'frame_id', using the 'camera_pose' % If no pose or landmarks are provided, ground-truth feature-locations are plotted. function plot_features(frame_id, style, camera_pose, landmarks) import gtsam.*; global calib; global features_gt; % Plot ground-truth if no pose or landmarks are provided plot_gt = false; if nargin < 3 plot_gt = true; else camera = SimpleCamera(camera_pose, calib); end % Iterate features f = 1; % column of current feature ID show_warning = false; while f < size(features_gt, 2) && features_gt(frame_id,f) > 0 if plot_gt plot(features_gt(frame_id,f+1),features_gt(frame_id,f+2),'g+'); else feature_id = features_gt(frame_id,f); try point2d = camera.project(Point3(landmarks(feature_id,1),landmarks(feature_id,2),landmarks(feature_id,3))); plot(point2d.x,point2d.y,style); catch show_warning = true; end end f = f+4; end if show_warning warning('Could not plot all features.'); end end
github
hsuisme/TensorCompletion-master
lrr.m
.m
TensorCompletion-master/lib/algorithms/lrr.m
3,529
utf_8
f415a5263180f31dc35bdec719b7bdf4
function [X,E,obj,err,iter] = lrr(A,B,lambda,opts) % Solve the Low-Rank Representation minimization problem by M-ADMM % % min_{X,E} ||X||_*+lambda*loss(E), s.t. A=BX+E % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - nb*na matrix % E - d*na matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(nb,na); E = zeros(d,na); J = X; Y1 = E; Y2 = X; BtB = B'*B; BtA = B'*A; I = eye(nb); invBtBI = (BtB+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Ek = E; Jk = J; % first super block {J,E} [J,nuclearnormJ] = prox_nuclear(X+Y2/mu,1/mu); if strcmp(loss,'l1') E = prox_l1(A-B*X+Y1/mu,lambda/mu); elseif strcmp(loss,'l21') E = prox_l21(A-B*X+Y1/mu,lambda/mu); elseif strcmp(loss,'l2') E = mu*(A-B*X+Y1/mu)/(lambda+mu); else error('not supported loss function'); end % second super block {X} X = invBtBI*(B'*(Y1/mu-E)+BtA-Y2/mu+J); dY1 = A-B*X-E; dY2 = X-J; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgJ = max(max(abs(Jk-J))); chg = max([chgX chgE chgJ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormJ+lambda*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnormJ+lambda*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
hsuisme/TensorCompletion-master
groupl1.m
.m
TensorCompletion-master/lib/algorithms/groupl1.m
2,730
utf_8
71035c51c2852449c2ddbc3091fe41ed
function [X,obj,err,iter] = groupl1(A,B,G,opts) % Solve the group l1-minimization problem by ADMM % % min_X \sum_{i=1}^n\sum_{g in G} ||(x_i)_g||_2, s.t. AX=B % % x_i is the i-th column of X % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % G - a cell indicates a partition of 1:na % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - na*nb matrix % obj - objective function value % err - residual ||AX-B||_F % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(na,nb); Z = X; Y1 = zeros(d,nb); Y2 = X; AtB = A'*B; I = eye(na); invAtAI = (A'*A+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Zk = Z; % update X for i = 1 : nb X(:,i) = prox_gl1(Z(:,i)-Y2(:,i)/mu,G,1/mu); end % update Z Z = invAtAI*(-(A'*Y1-Y2)/mu+AtB+X); dY1 = A*Z-B; dY2 = X-Z; chgX = max(max(abs(Xk-X))); chgZ = max(max(abs(Zk-Z))); chg = max([chgX chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = compute_obj(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = compute_obj(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function obj = compute_obj(X,G) obj = 0; for i = 1 : size(X,2) x = X(:,i); for j = 1 : length(G) obj = obj + norm(x(G{j})); end end
github
hsuisme/TensorCompletion-master
rpca.m
.m
TensorCompletion-master/lib/algorithms/rpca.m
2,944
utf_8
1930326cf4bf01c764909897658853ca
function [L,S,obj,err,iter] = rpca(X,lambda,opts) % Solve the Robust Principal Component Analysis minimization problem by M-ADMM % % min_{L,S} ||L||_*+lambda*loss(S), s.t. X=L+S % loss(S) = ||S||_1 or ||S||_{2,1} % % --------------------------------------------- % Input: % X - d*n matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(S) = ||S||_1 % 'l21': loss(S) = ||S||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % L - d*n matrix % S - d*n matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 19/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(X); L = zeros(d,n); S = L; Y = L; iter = 0; for iter = 1 : max_iter Lk = L; Sk = S; % update L [L,nuclearnormL] = prox_nuclear(-S+X-Y/mu,1/mu); % update S if strcmp(loss,'l1') S = prox_l1(-L+X-Y/mu,lambda/mu); elseif strcmp(loss,'l21') S = prox_l21(-L+X-Y/mu,lambda/mu); else error('not supported loss function'); end dY = L+S-X; chgL = max(max(abs(Lk-L))); chgS = max(max(abs(Sk-S))); chg = max([chgL chgS max(abs(dY(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormL+lambda*comp_loss(S,loss); err = norm(dY,'fro'); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; mu = min(rho*mu,max_mu); end obj = nuclearnormL+lambda*comp_loss(S,loss); err = norm(dY,'fro'); function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end end
github
hsuisme/TensorCompletion-master
tracelasso.m
.m
TensorCompletion-master/lib/algorithms/tracelasso.m
2,583
utf_8
536f5ce74c82d5f183c3c967e14d6cf6
function [x,obj,err,iter] = tracelasso(A,b,opts) % Solve the trace Lasso minimization problem by ADMM % % min_x ||A*Diag(x)||_*, s.t. Ax=b % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); Z = zeros(d,n); Y1 = zeros(d,1); Y2 = Z; Atb = A'*b; AtA = A'*A; invAtA = (AtA+diag(diag(AtA)))\eye(n); iter = 0; for iter = 1 : max_iter xk = x; Zk = Z; % update x x = invAtA*(-A'*Y1/mu+Atb+diagAtB(A,-Y2/mu+Z)); % update Z [Z,nuclearnorm] = prox_nuclear(A*diag(x)+Y2/mu,1/mu); dY1 = A*x-b; dY2 = A*diag(x)-Z; chgx = max(abs(xk-x)); chgZ = max(abs(Zk-Z)); chg = max([chgx chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function v = diagAtB(A,B) % A, B - d*n matrices % v = diag(A'*B), n*1 vector n = size(A,2); v = zeros(n,1); for i = 1 : n v(i) = A(:,i)'*B(:,i); end
github
hsuisme/TensorCompletion-master
groupl1R.m
.m
TensorCompletion-master/lib/algorithms/groupl1R.m
3,417
utf_8
daad367680f297bfd5a82197bec8b72d
function [X,E,obj,err,iter] = groupl1R(A,B,G,lambda,opts) % Solve the group l1 norm regularized minimization problem by M-ADMM % % min_{X,E} loss(E)+lambda*\sum_{i=1}^n\sum_{g in G} ||(x_i)_g||_2, s.t. AX+E=B % x_i is the i-th column of X % loss(E) = ||E||_1 or 0.5*||E||_F^2 % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % G - a cell indicates a partition of 1:na % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - na*nb matrix % E - d*nb matrix % obj - objective function value % err - residual ||AX+E-B||_F % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(na,nb); E = zeros(d,nb); Z = X; Y1 = E; Y2 = X; AtB = A'*B; I = eye(na); invAtAI = (A'*A+I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Ek = E; Zk = Z; % first super block {X,E} for i = 1 : nb X(:,i) = prox_gl1(Z(:,i)-Y2(:,i)/mu,G,1/mu); end if strcmp(loss,'l1') E = prox_l1(B-A*Z-Y1/mu,1/mu); elseif strcmp(loss,'l2') E = mu*(B-A*Z-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {Z} Z = invAtAI*(-A'*(Y1/mu+E)+AtB+Y2/mu+X); dY1 = A*Z+E-B; dY2 = X-Z; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chg = max([chgX chgE chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(E,loss)+lambda*compute_groupl1(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(E,loss)+lambda*compute_groupl1(X,G); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function obj = compute_groupl1(X,G) obj = 0; for i = 1 : size(X,2) x = X(:,i); for j = 1 : length(G) obj = obj + norm(x(G{j})); end end
github
hsuisme/TensorCompletion-master
mlap.m
.m
TensorCompletion-master/lib/algorithms/mlap.m
4,761
utf_8
ad408cb013b2ffa24973702254b4d4e0
function [Z,E,obj,err,iter] = mlap(X,lambda,alpha,opts) % Solve the Multi-task Low-rank Affinity Pursuit (MLAP) minimization problem by M-ADMM % % Reference: Cheng, Bin, Guangcan Liu, Jingdong Wang, Zhongyang Huang, and Shuicheng Yan. % Multi-task low-rank affinity pursuit for image segmentation. ICCV, 2011. % % min_{Z_i,E_i} \sum_{i=1}^K (||Z_i||_*+lambda*loss(E_i))+alpha*||Z||_{2,1}, % s.t. X_i=X_i*Z_i+E_i, i=1,...,K. % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % % --------------------------------------------- % Input: % X - d*n*K tensor % lambda - >0, parameter % alpha - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % Z - n*n*K tensor % E - d*n*K tensor % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n,K] = size(X); Z = zeros(n,n,K); E = zeros(d,n,K); J = Z; S = Z; Y = E; W = Z; V = Z; dY = Y; XmXS = E; XtX = zeros(n,n,K); invXtXI = zeros(n,n,K); I = eye(n); for i = 1 : K XtX(:,:,i) = X(:,:,i)'*X(:,:,i); invXtXI(:,:,i) = (XtX(:,:,i)+I)\I; end nuclearnormJ = zeros(K,1); iter = 0; for iter = 1 : max_iter Zk = Z; Ek = E; Jk = J; Sk = S; % first super block {J,S} for i = 1 : K [J(:,:,i),nuclearnormJ(i)] = prox_nuclear(Z(:,:,i)+W(:,:,i)/mu,1/mu); S(:,:,i) = invXtXI(:,:,i)*(XtX(:,:,i)-X(:,:,i)'*(E(:,:,i)-Y(:,:,i)/mu)+Z(:,:,i)+(V(:,:,i)-W(:,:,i))/mu); end % second super block {Z,E} Z = prox_tensor_l21((J+S-(W+V)/mu)/2,alpha/(2*mu)); for i = 1 : K XmXS(:,:,i) = X(:,:,i)-X(:,:,i)*S(:,:,i); end if strcmp(loss,'l1') for i = 1 : K E(:,:,i) = prox_l1(XmXS(:,:,i)+Y(:,:,i)/mu,lambda/mu); end elseif strcmp(loss,'l21') for i = 1 : K E(:,:,i) = prox_l21(XmXS(:,:,i)+Y(:,:,i)/mu,lambda/mu); end elseif strcmp(loss,'l2') for i = 1 : K E = (XmXS(:,:,i)+Y(:,:,i)/mu) / (lambda/mu+1); end else error('not supported loss function'); end dY = XmXS-E; dW = Z-J; dV = Z-S; chgZ = max(abs(Zk(:)-Z(:))); chgE = max(abs(Ek(:)-E(:))); chgJ = max(abs(Jk(:)-J(:))); chgS = max(abs(Sk(:)-S(:))); chg = max([chgZ chgE chgJ chgS max(abs(dY(:))) max(abs(dW(:))) max(abs(dV(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = sum(nuclearnormJ)+lambda*comp_loss(E,loss)+alpha*comp_loss(Z,'l21'); err = sqrt(norm(dY(:))^2+norm(dW(:))^2+norm(dV(:))^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; W = W + mu*dW; V = V + mu*dV; mu = min(rho*mu,max_mu); end obj = sum(nuclearnormJ)+lambda*comp_loss(E,loss)+alpha*comp_loss(Z,'l21'); err = sqrt(norm(dY(:))^2+norm(dW(:))^2+norm(dV(:))^2); function X = prox_tensor_l21(B,lambda) % proximal operator of tensor l21-norm, i.e., the sum of the l2 norm of all % tubes of a tensor. % % X - n1*n2*n3 tensor % B - n1*n2*n3 tensor % % min_X lambda*\sum_{i=1}^n1\sum_{j=1}^n2 ||X(i,j,:)||_2 + 0.5*||X-B||_F^2 [n1,n2,n3] = size(B); X = zeros(n1,n2,n3); for i = 1 : n1 for j = 1 : n2 v = B(i,j,:); nxi = norm(v(:)); if nxi > lambda X(i,j,:) = (1-lambda/nxi)*B(i,j,:); end end end
github
hsuisme/TensorCompletion-master
lrsr.m
.m
TensorCompletion-master/lib/algorithms/lrsr.m
3,838
utf_8
8bd2f6bd0800a5a346a5a4bfbb011702
function [X,E,obj,err,iter] = lrsr(A,B,lambda1,lambda2,opts) % Solve the Low-Rank and Sparse Representation (LRSR) minimization problem by M-ADMM % % min_{X,E} ||X||_*+lambda1*||X||_1+lambda2*loss(E), s.t. A=BX+E % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % --------------------------------------------- % Input: % A - d*na matrix % B - d*nb matrix % lambda1 - >0, parameter % lambda2 - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1': loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21' (default): loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % X - nb*na matrix % E - d*na matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l21'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,na] = size(A); [~,nb] = size(B); X = zeros(nb,na); E = zeros(d,na); Z = X; J = X; Y1 = E; Y2 = X; Y3 = X; BtB = B'*B; BtA = B'*A; I = eye(nb); invBtBI = (BtB+2*I)\I; iter = 0; for iter = 1 : max_iter Xk = X; Zk = Z; Ek = E; Jk = J; % first super block {Z,J,E} [Z,nuclearnormZ] = prox_nuclear(X+Y2/mu,1/mu); J = prox_l1(X+Y3/mu,lambda1/mu); if strcmp(loss,'l1') E = prox_l1(A-B*X+Y1/mu,lambda2/mu); elseif strcmp(loss,'l21') E = prox_l21(A-B*X+Y1/mu,lambda2/mu); elseif strcmp(loss,'l2') E = mu*(A-B*X+Y1/mu)/(lambda2+mu); else error('not supported loss function'); end % second super block {X} X = invBtBI*(B'*(Y1/mu-E)+BtA-(Y2+Y3)/mu+Z+J); dY1 = A-B*X-E; dY2 = X-Z; dY3 = X-J; chgX = max(max(abs(Xk-X))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chgJ = max(max(abs(Jk-J))); chg = max([chgX chgE chgZ chgJ max(abs(dY1(:))) max(abs(dY2(:))) max(abs(dY3(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormZ+lambda1*norm(J(:),1)+lambda2*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2+norm(dY3,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = nuclearnormZ+lambda1*norm(J(:),1)+lambda2*comp_loss(E,loss); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2+norm(dY3,'fro')^2); function out = comp_loss(E,normtype) switch normtype case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
hsuisme/TensorCompletion-master
fusedl1R.m
.m
TensorCompletion-master/lib/algorithms/fusedl1R.m
3,714
utf_8
145be29163c05b2175bd848ba37d18d1
function [x,e,obj,err,iter] = fusedl1R(A,b,lambda1,lambda2,opts) % Solve the fused Lasso regularized minimization problem by ADMM % % min_{x,e} loss(e) + lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|, % loss(e) = ||e||_1 or 0.5*||e||_2^2 % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % lambda1 - >=0, parameter % lambda2 - >=0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(e) = ||e||_1 % 'l2': loss(E) = 0.5*||e||_2^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % e - d*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 20/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; % default if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); e = zeros(d,1); z = x; Y1 = e; Y2 = x; Atb = A'*b; I = eye(n); invAtAI = (A'*A+I)\I; % parameters for "flsa" (from SLEP package) tol2 = 1e-10; % the duality gap for termination max_step = 50; % the maximal number of iterations x0 = zeros(n-1,1); % the starting point iter = 0; for iter = 1 : max_iter xk = x; ek = e; zk = z; % first super block {x,e} % flsa solves min_x 1/2||x-v||_2^2+lambda1*||x||_1+lambda2*\sum_{i=2}^p |x_i-x_{i-1}|, x = flsa(z-Y2/mu,x0,lambda1/mu,lambda2/mu,n,max_step,tol2,1,6); if strcmp(loss,'l1') e = prox_l1(b-A*z-Y1/mu,1/mu); elseif strcmp(loss,'l2') e = mu*(b-A*z-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {Z} z = invAtAI*(-A'*(Y1/mu+e)+Atb+Y2/mu+x); dY1 = A*z+e-b; dY2 = x-z; chgx = max(abs(xk-x)); chge = max(abs(ek-e)); chgz = max(abs(zk-z)); chg = max([chgx chge chgz max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(e,loss)+comp_fusedl1(x,lambda1,lambda2); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(e,loss)+comp_fusedl1(x,lambda1,lambda2); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function f = comp_fusedl1(x,lambda1,lambda2) % compute f = lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|. % x - p*1 vector f = 0; p = length(x); for i = 2 : p f = f+abs(x(i)-x(i-1)); end f = lambda1*norm(x,1)+lambda2*f;
github
hsuisme/TensorCompletion-master
fusedl1.m
.m
TensorCompletion-master/lib/algorithms/fusedl1.m
3,027
utf_8
e180c20b97ac834bfde5d505c23bdb1e
function [x,obj,err,iter] = fusedl1(A,b,lambda,opts) % Solve the fused Lasso (Fused L1) minimization problem by ADMM % % min_x ||x||_1 + lambda*\sum_{i=2}^p |x_i-x_{i-1}|, % s.t. Ax=b % % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % lambda - >=0, parameter % opts - Structure value in Matlab. The fields are % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 20/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); z = x; Y1 = zeros(d,1); Y2 = x; Atb = A'*b; I = eye(n); invAtAI = (A'*A+I)\I; % parameters for "flsa" (from SLEP package) tol2 = 1e-10; % the duality gap for termination max_step = 50; % the maximal number of iterations x0 = zeros(n-1,1); % the starting point iter = 0; for iter = 1 : max_iter xk = x; zk = z; % update x. % flsa solves min_x 1/2||x-v||_2^2+lambda1*||x||_1+lambda2*\sum_{i=2}^p |x_i-x_{i-1}| x = flsa(z-Y2/mu,x0,1/mu,lambda/mu,n,max_step,tol2,1,6); % update z z = invAtAI*(-A'*Y1/mu+Atb+Y2/mu+x); dY1 = A*z-b; dY2 = x-z; chgx = max(abs(xk-x)); chgz = max(abs(zk-z)); chg = max([chgx chgz max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_fusedl1(x,1,lambda); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_fusedl1(x,1,lambda); err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function f = comp_fusedl1(x,lambda1,lambda2) % compute f = lambda1*||x||_1 + lambda2*\sum_{i=2}^p |x_i-x_{i-1}|. % x - p*1 vector f = 0; p = length(x); for i = 2 : p f = f+abs(x(i)-x(i-1)); end f = lambda1*norm(x,1)+lambda2*f;
github
hsuisme/TensorCompletion-master
tracelassoR.m
.m
TensorCompletion-master/lib/algorithms/tracelassoR.m
3,247
utf_8
8bc2e00ce23aaa6478590829303525b6
function [x,e,obj,err,iter] = tracelassoR(A,b,lambda,opts) % Solve the trace Lasso regularized minimization problem by M-ADMM % % min_{x,e} loss(e)+lambda*||A*Diag(x)||_*, s.t. Ax+e=b % loss(e) = ||e||_1 or 0.5*||e||_2^2 % --------------------------------------------- % Input: % A - d*n matrix % b - d*1 vector % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(e) = ||e||_1 % 'l2': loss(e) = 0.5*||e||_2^2 % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % x - n*1 vector % e - d*1 vector % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 18/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end [d,n] = size(A); x = zeros(n,1); Z = zeros(d,n); e = zeros(d,1); Y1 = e; Y2 = Z; Atb = A'*b; AtA = A'*A; invAtA = (AtA+diag(diag(AtA)))\eye(n); iter = 0; for iter = 1 : max_iter xk = x; ek = e; Zk = Z; % first super block {Z,e} [Z,nuclearnorm] = prox_nuclear(A*diag(x)-Y2/mu,lambda/mu); if strcmp(loss,'l1') e = prox_l1(b-A*x-Y1/mu,1/mu); elseif strcmp(loss,'l2') e = mu*(b-A*x-Y1/mu)/(1+mu); else error('not supported loss function'); end % second super block {x} x = invAtA*(-A'*(Y1/mu+e)+Atb+diagAtB(A,Y2/mu+Z)); dY1 = A*x+e-b; dY2 = Z-A*diag(x); chgx = max(abs(xk-x)); chge = max(abs(ek-e)); chgZ = max(max(abs(Zk-Z))); chg = max([chgx chge chgZ max(abs(dY1(:))) max(abs(dY2(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = comp_loss(e,loss)+lambda*nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y1 = Y1 + mu*dY1; Y2 = Y2 + mu*dY2; mu = min(rho*mu,max_mu); end obj = comp_loss(e,loss)+lambda*nuclearnorm; err = sqrt(norm(dY1,'fro')^2+norm(dY2,'fro')^2); function v = diagAtB(A,B) % A, B - d*n matrices % v = diag(A'*B), n*1 vector n = size(A,2); v = zeros(n,1); for i = 1 : n v(i) = A(:,i)'*B(:,i); end
github
hsuisme/TensorCompletion-master
latlrr.m
.m
TensorCompletion-master/lib/algorithms/latlrr.m
3,636
utf_8
51a08d8f2880a125c6d1dda689ba9f7f
function [Z,L,obj,err,iter] = latlrr(X,lambda,opts) % Solve the Latent Low-Rank Representation by M-ADMM % % min_{Z,L,E} ||Z||_*+||L||_*+lambda*loss(E), % s.t., XZ+LX-X=E. % loss(E) = ||E||_1 or 0.5*||E||_F^2 or ||E||_{2,1} % --------------------------------------------- % Input: % X - d*n matrix % lambda - >0, parameter % opts - Structure value in Matlab. The fields are % opts.loss - 'l1' (default): loss(E) = ||E||_1 % 'l2': loss(E) = 0.5*||E||_F^2 % 'l21': loss(E) = ||E||_{2,1} % opts.tol - termination tolerance % opts.max_iter - maximum number of iterations % opts.mu - stepsize for dual variable updating in ADMM % opts.max_mu - maximum stepsize % opts.rho - rho>=1, ratio used to increase mu % opts.DEBUG - 0 or 1 % % Output: % Z - n*n matrix % L - d*d matrix % E - d*n matrix % obj - objective function value % err - residual % iter - number of iterations % % version 1.0 - 19/06/2016 % % Written by Canyi Lu ([email protected]) % tol = 1e-8; max_iter = 500; rho = 1.1; mu = 1e-4; max_mu = 1e10; DEBUG = 0; loss = 'l1'; if ~exist('opts', 'var') opts = []; end if isfield(opts, 'loss'); loss = opts.loss; end if isfield(opts, 'tol'); tol = opts.tol; end if isfield(opts, 'max_iter'); max_iter = opts.max_iter; end if isfield(opts, 'rho'); rho = opts.rho; end if isfield(opts, 'mu'); mu = opts.mu; end if isfield(opts, 'max_mu'); max_mu = opts.max_mu; end if isfield(opts, 'DEBUG'); DEBUG = opts.DEBUG; end eta1 = 1.02*2*norm(X,2)^2; % for Z eta2 = eta1; % for L eta3 = 1.02*2; % for E [d,n] = size(X); E = zeros(d,n); Z = zeros(n,n); L = zeros(d,d); Y = E; XtX = X'*X; XXt = X*X'; iter = 0; for iter = 1 : max_iter Lk = L; Ek = E; Zk = Z; % first super block {Z} [Z,nuclearnormZ] = prox_nuclear(Zk-(X'*(Y/mu+L*X-X-E)+XtX*Z)/eta1,1/(mu*eta1)); % second super block {L,E} temp = Lk-((Y/mu+X*Z-Ek)*X'+Lk*XXt-XXt)/eta2; [L,nuclearnormL] = prox_nuclear(temp,1/(mu*eta2)); if strcmp(loss,'l1') E = prox_l1(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3)); elseif strcmp(loss,'l21') E = prox_l21(Ek+(Y/mu+X*Z+Lk*X-X-Ek)/eta3,lambda/(mu*eta3)); elseif strcmp(loss,'l2') E = (Y+mu*(X*Z+Lk*X-X+(eta3-1)*Ek))/(lambda+mu*eta3); else error('not supported loss function'); end dY = X*Z+L*X-X-E; chgL = max(max(abs(Lk-L))); chgE = max(max(abs(Ek-E))); chgZ = max(max(abs(Zk-Z))); chg = max([chgL chgE chgZ max(abs(dY(:)))]); if DEBUG if iter == 1 || mod(iter, 10) == 0 obj = nuclearnormZ+nuclearnormL+lambda*comp_loss(E,loss); err = norm(dY,'fro')^2; disp(['iter ' num2str(iter) ', mu=' num2str(mu) ... ', obj=' num2str(obj) ', err=' num2str(err)]); end end if chg < tol break; end Y = Y + mu*dY; mu = min(rho*mu,max_mu); end obj = nuclearnormZ+nuclearnormZ+lambda*comp_loss(E,loss); err = norm(dY,'fro')^2; function out = comp_loss(E,loss) switch loss case 'l1' out = norm(E(:),1); case 'l21' out = 0; for i = 1 : size(E,2) out = out + norm(E(:,i)); end case 'l2' out = 0.5*norm(E,'fro')^2; end
github
gingsmith/fmtl-master
split_data.m
.m
fmtl-master/util/split_data.m
1,207
utf_8
667b79186ed24019b82fc2ae7e0e5e84
%% FUNCTION split_data % Splitting multi-task data into training / testing by percentage. % %% INPUT % X: {n * d} * t - input matrix % Y: {n * 1} * t - output matrix % percent: percentage of the splitting range (0, 1) % %% OUTPUT % X_train: the split of X that has the specified percent of samples % Y_train: the split of Y that has the specified percent of samples % X_test: the split of X that has the remaining samples % Y_test: the split of Y that has the remaining samples % selIdx: the selection index of for X_train and Y_train for each task %% function [X_train, Y_train, X_test, Y_test, selIdx] = split_data(X, Y, percent) if percent > 1 || percent < 0 error('splitting percentage error') end task_num = length(X); selIdx = cell(task_num, 0); X_train = cell(task_num, 0); Y_train = cell(task_num, 0); X_test = cell(task_num, 0); Y_test = cell(task_num, 0); for t = 1:task_num task_sample_size = length(Y{t}); tSelIdx = randperm(task_sample_size) < task_sample_size * percent; selIdx{t} = tSelIdx; X_train{t} = X{t}(tSelIdx,:); Y_train{t} = Y{t}(tSelIdx,:); X_test{t} = X{t}(~tSelIdx,:); Y_test{t} = Y{t}(~tSelIdx,:); end
github
tyger2020/HAWC-master
submit.m
.m
HAWC-master/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
tyger2020/HAWC-master
submitWithConfiguration.m
.m
HAWC-master/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
tyger2020/HAWC-master
savejson.m
.m
HAWC-master/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
tyger2020/HAWC-master
loadjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
loadubjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
saveubjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
submit.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/submit.m
1,876
utf_8
8d1c467b830a89c187c05b121cb8fbfd
function submit() addpath('./lib'); conf.assignmentSlug = 'linear-regression'; conf.itemName = 'Linear Regression with Multiple Variables'; conf.partArrays = { ... { ... '1', ... { 'warmUpExercise.m' }, ... 'Warm-up Exercise', ... }, ... { ... '2', ... { 'computeCost.m' }, ... 'Computing Cost (for One Variable)', ... }, ... { ... '3', ... { 'gradientDescent.m' }, ... 'Gradient Descent (for One Variable)', ... }, ... { ... '4', ... { 'featureNormalize.m' }, ... 'Feature Normalization', ... }, ... { ... '5', ... { 'computeCostMulti.m' }, ... 'Computing Cost (for Multiple Variables)', ... }, ... { ... '6', ... { 'gradientDescentMulti.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '7', ... { 'normalEqn.m' }, ... 'Normal Equations', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId) % Random Test Cases X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))']; Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2)); X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25]; Y2 = Y1.^0.5 + Y1; if partId == '1' out = sprintf('%0.5f ', warmUpExercise()); elseif partId == '2' out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]')); elseif partId == '3' out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10)); elseif partId == '4' out = sprintf('%0.5f ', featureNormalize(X2(:,2:4))); elseif partId == '5' out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]')); elseif partId == '6' out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10)); elseif partId == '7' out = sprintf('%0.5f ', normalEqn(X2, Y2)); end end
github
tyger2020/HAWC-master
submitWithConfiguration.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
tyger2020/HAWC-master
savejson.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
tyger2020/HAWC-master
loadjson.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
tyger2020/HAWC-master
loadubjson.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
tyger2020/HAWC-master
saveubjson.m
.m
HAWC-master/machine-learning-ex1 - Copy/ex1/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
tyger2020/HAWC-master
savejson.m
.m
HAWC-master/machine-learning-ex4/ex4/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
tyger2020/HAWC-master
loadjson.m
.m
HAWC-master/machine-learning-ex4/ex4/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
tyger2020/HAWC-master
loadubjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
saveubjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
submitWithConfiguration.m
.m
HAWC-master/ex3/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
tyger2020/HAWC-master
savejson.m
.m
HAWC-master/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
tyger2020/HAWC-master
loadjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
loadubjson.m
.m
HAWC-master/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
tyger2020/HAWC-master
saveubjson.m
.m
HAWC-master/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/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
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/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
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/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
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week04/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/machine-learning-ex4/ex4/submit.m
1,635
utf_8
ae9c236c78f9b5b09db8fbc2052990fc
function submit() addpath('./lib'); conf.assignmentSlug = 'neural-network-learning'; conf.itemName = 'Neural Networks Learning'; conf.partArrays = { ... { ... '1', ... { 'nnCostFunction.m' }, ... 'Feedforward and Cost Function', ... }, ... { ... '2', ... { 'nnCostFunction.m' }, ... 'Regularized Cost Function', ... }, ... { ... '3', ... { 'sigmoidGradient.m' }, ... 'Sigmoid Gradient', ... }, ... { ... '4', ... { 'nnCostFunction.m' }, ... 'Neural Network Gradient (Backpropagation)', ... }, ... { ... '5', ... { 'nnCostFunction.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(3 * sin(1:1:30), 3, 10); Xm = reshape(sin(1:32), 16, 2) / 5; ym = 1 + mod(1:16,4)'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); t = [t1(:) ; t2(:)]; if partId == '1' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); elseif partId == '2' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); elseif partId == '3' out = sprintf('%0.5f ', sigmoidGradient(X)); elseif partId == '4' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '5' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; end end
github
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/machine-learning-ex4/ex4/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/machine-learning-ex4/ex4/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/machine-learning-ex4/ex4/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/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
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week05/Programming Assignment/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
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/submit.m
1,765
utf_8
b1804fe5854d9744dca981d250eda251
function submit() addpath('./lib'); conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance'; conf.itemName = 'Regularized Linear Regression and Bias/Variance'; conf.partArrays = { ... { ... '1', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Cost Function', ... }, ... { ... '2', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Gradient', ... }, ... { ... '3', ... { 'learningCurve.m' }, ... 'Learning Curve', ... }, ... { ... '4', ... { 'polyFeatures.m' }, ... 'Polynomial Feature Mapping', ... }, ... { ... '5', ... { 'validationCurve.m' }, ... 'Validation Curve', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)']; y = sin(1:3:30)'; Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)']; yval = sin(1:10)'; if partId == '1' [J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', J); elseif partId == '2' [J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', grad); elseif partId == '3' [error_train, error_val] = ... learningCurve(X, y, Xval, yval, 1); out = sprintf('%0.5f ', [error_train(:); error_val(:)]); elseif partId == '4' [X_poly] = polyFeatures(X(2,:)', 8); out = sprintf('%0.5f ', X_poly); elseif partId == '5' [lambda_vec, error_train, error_val] = ... validationCurve(X, y, Xval, yval); out = sprintf('%0.5f ', ... [lambda_vec(:); error_train(:); error_val(:)]); end end
github
shawnngtq/machine-learning-master
submitWithConfiguration.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
shawnngtq/machine-learning-master
savejson.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
shawnngtq/machine-learning-master
loadjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
shawnngtq/machine-learning-master
loadubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
shawnngtq/machine-learning-master
saveubjson.m
.m
machine-learning-master/andrew-ng-machine-learning/week06/Programming Assignment/machine-learning-ex5/ex5/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
shawnngtq/machine-learning-master
submit.m
.m
machine-learning-master/andrew-ng-machine-learning/week02/Programming Assignment/machine-learning-ex1/ex1/submit.m
1,882
utf_8
a6e3fa010429b5a6b4ee97447dcf50b9
function submit() addpath('./lib'); conf.assignmentSlug = 'linear-regression'; conf.itemName = 'Linear Regression with Multiple Variables'; conf.partArrays = { ... { ... '1', ... { 'warmUpExercise.m' }, ... 'Warm-up Exercise', ... }, ... { ... '2', ... { 'computeCost.m' }, ... 'Computing Cost (for One Variable)', ... }, ... { ... '3', ... { 'gradientDescent.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '4', ... { 'featureNormalize.m' }, ... 'Feature Normalization', ... }, ... { ... '5', ... { 'computeCostMulti.m' }, ... 'Computing Cost (for Multiple Variables)', ... }, ... { ... '6', ... { 'gradientDescentMulti.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '7', ... { 'normalEqn.m' }, ... 'Normal Equations', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId) % Random Test Cases X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))']; Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2)); X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25]; Y2 = Y1.^0.5 + Y1; if partId == '1' out = sprintf('%0.5f ', warmUpExercise()); elseif partId == '2' out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]')); elseif partId == '3' out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10)); elseif partId == '4' out = sprintf('%0.5f ', featureNormalize(X2(:,2:4))); elseif partId == '5' out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]')); elseif partId == '6' out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10)); elseif partId == '7' out = sprintf('%0.5f ', normalEqn(X2, Y2)); end end