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
MRC-CBU/riksneurotools-master
connectivity_stats.m
.m
riksneurotools-master/Conn/connectivity_stats.m
8,352
utf_8
bf371d76a5ab3661bf8b941d4d843872
% Hacky function for thresholding connectivity matrices across groups % [email protected] Nov 2018 function connectivity_stats(S); try CM = S.CM; catch error('Need to pass a Nsubject x Nroi x Nroi connectivity matrix in S.CM') end try X = S.X; catch error('Need to pass a design matrix in S.X') end try contrasts = S.contrasts; catch error('Need to pass a contrast matrix in S.contrasts') end try Grp = S.Grp; catch error('Need to pass a Nsubject matrix indicating which group is subject belongs to') end try GrpPlot = S.GrpPlot; catch GrpPlot = []; % GrpPlot = eye(length(unique(Grp))); end try GrpPlotName = S.GrpPlotName; catch for g=1:size(GrpPlot,2) GrpPlotName{g} = sprintf('Grp%d',g); end end try rnam = S.rnam; catch for r=1:size(CM,2) rnam{r} = sprintf('ROI%d',r); end end try CorType = S.CorType; catch CorType = 'Unknown', end try FWE = S.FWE; catch FWE = 1, end try FDR = S.FDR; catch FDR = 0, end try Unc = S.Unc; catch Unc = 0, end try Alpha = S.Alpha; catch Alpha = 0.05, end try isDcor = S.isDcor; catch isDcor = 0, end try MeanRegress = S.MeanRegress; catch MeanRegress = 0, end try PlotTmap = S.PlotTmap; catch PlotTmap = 1, end try PlotPmap = S.PlotPmap; catch PlotPmap = 1, end %% Mean Regression if MeanRegress CMmr = NaN(size(CM)); meanCM = squeeze(mean(mean(CM,3),2)); mX = [meanCM ones(size(meanCM))]; XpX = mX*pinv(mX); for r = 1:size(CM,2); y = squeeze(CM(:,r,:)); CMmr(:,r,:) = y - XpX*y; CMmr(:,r,:) = CMmr(:,r,:) + repmat(mean(CM(:,r,:),1),[size(CM,1) 1 1]); % Adding back mean according to Linda; end CM = CMmr; CorType = ['MeanReg' CorType]; end % Linda's faster code but need to reshape results back into matrix form % CM = CM; % meanCM = squeeze(mean(mean(CM,3),2)); % beta=[meanCM ones(size(meanCM))]\squeeze(CM(:,:)); % CMmr(:,:)=squeeze(CM(:,:))-[meanCM ones(size(meanCM))]*beta; % CMmr(:,:)=squeeze(CMmr(:,:))+repmat(squeeze(nanmean(CM(:,:),1)),[length(meanCM) 1]); % Mean unchanged %figure; imagesc(squeeze(mean(CMmr,1))); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('CMmr(PreW=%d,Mean=%d)',PreWhiten,MeanVox)); %caxis([-1 1]); %set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); %% Plot averages and T-stats for combinations of Groups for g = 1:size(GrpPlot,1) ind = find(ismember(Grp,find(GrpPlot(g,:)))); tmp = CM(ind,:,:); if ~isDcor TransData = atanh(tmp); % Fisher transform (leading diagonals of 1 now Inf, but removed below) else TransData = log(CM(ind,:,:)+1); % Correct for bounded Dcor 0-1? (0.001 to stop log(0)=-Inf) end figure; imagesc(squeeze(mean(tmp,1))); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Mean %s:%s',CorType,GrpPlotName{g})); caxis([0 1]); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]) %% plot the T-stats across all subjects (vs 0) CMTmap = squeeze(mean(TransData,1))./(squeeze(std(TransData,0,1))/sqrt(length(ind))); CMTmap(find(eye(size(CMTmap)))) = NaN; CMPmap = t2p(CMTmap,size(CM,1)-1,0); CMPmap(find(eye(size(CMPmap)))) = 1; if PlotTmap figure; imagesc(CMTmap); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Tmap %s:%s',CorType,GrpPlotName{g})); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end if PlotPmap figure; imagesc(log10(CMPmap)); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Log10Pmap %s:%s',CorType,GrpPlotName{g})); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end end %% plot the T-stats comparing groups contrasts = [contrasts zeros(size(contrasts,1),size(X,2)-size(contrasts,2))]; Nroi = size(CM,2); Tmap = NaN(size(contrasts,1),Nroi,Nroi); Pmap = Tmap; Bmap = Tmap; %Alpha = Alpha / size(contrasts,1) % Could speed-up by using a multivariate GLM, but not too slow at moment for c = 1:size(contrasts,1) for ri = 1:Nroi for rj = (ri+1):Nroi y = squeeze(CM(:,ri,rj)); if ~isDcor; y = atanh(y); else y = log(y+1); end [Tmap(c,ri,rj),F,Pmap(c,ri,rj),df,R2,cR2,B,r,aR2,iR2] = glm(y,X,contrasts(c,:)',-1); Bmap(c,ri,rj) = contrasts(c,:)*B; Bmap(c,rj,ri) = Bmap(c,ri,rj); %Tmap(c,rj,ri) = Tmap(c,ri,rj); %Pmap(c,rj,ri) = Pmap(c,ri,rj); end end figure; imagesc(squeeze(Bmap(c,:,:))); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Mean %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); if PlotTmap figure; imagesc(squeeze(Tmap(c,:,:))); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Tmap %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end uPmap = squeeze(Pmap(c,:,:)); if PlotPmap figure; imagesc(log10(uPmap)); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Log10Pmap %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end if Unc % ThrPmap = uPmap; % ThrPmap(find(uPmap>=Alpha)) = 1; ThrPmap = squeeze(Tmap(c,:,:)); ThrPmap(find(uPmap>=Alpha)) = NaN; if PlotPmap & ~isempty(find(uPmap<Alpha)) figure; imagesc(ThrPmap); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('Unc %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end fprintf('\nContrast %s, Alpha = %8.7f, Unc\n',num2str(contrasts(c,:)),Alpha) % [ri,rj] = find(squeeze(ThrPmap)<1); [ri,rj] = find(squeeze(~isnan(ThrPmap))); for i = 1:length(ri) fprintf('%s (%d) --------- %s (%d) (T=%3.2f, p=%1.6f)\n',rnam{ri(i)},ri(i),rnam{rj(i)},rj(i),Tmap(c,ri(i),rj(i)),Pmap(c,ri(i),rj(i))) end end if FWE CorAlpha = Alpha / ((Nroi-1)*Nroi/2); % ThrPmap = uPmap; % ThrPmap(find(uPmap>=CorAlpha)) = 1; ThrPmap = squeeze(Tmap(c,:,:)); ThrPmap(find(uPmap>=CorAlpha)) = NaN; if PlotPmap & ~isempty(find(uPmap<CorAlpha)) figure; imagesc(ThrPmap); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('FWE %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end fprintf('\nContrast %s, Alpha = %8.7f, FWE\n',num2str(contrasts(c,:)),Alpha) % [ri,rj] = find(squeeze(ThrPmap)<1); [ri,rj] = find(squeeze(~isnan(ThrPmap))); for i = 1:length(ri) fprintf('%s (%d) --------- %s (%d) (T=%3.2f, p=%1.6f)\n',rnam{ri(i)},ri(i),rnam{rj(i)},rj(i),Tmap(c,ri(i),rj(i)),Pmap(c,ri(i),rj(i))) end end if FDR % ThrPmap = uPmap; ThrPmap = squeeze(Tmap(c,:,:)); ind = find(triu(ones(size(uPmap)),1)); [AboveThr, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(uPmap(ind),Alpha,'dep','no'); AboveThr = find(AboveThr); % Holm's method % [Ranked,Order] = sort(uPmap(ind),'ascend'); % N = length(Ranked); % AboveThr = []; % for f = 1:length(Ranked) % if Ranked(f) >= Alpha/(N+1-f); % break % else % AboveThr(end+1) = Order(f); % end % end ThrPmap(setdiff([1:length(ThrPmap(:))],ind(AboveThr))) = NaN; if PlotPmap & ~isempty(AboveThr) figure; imagesc(ThrPmap); colormap(jet); set(gca,'FontSize',12); colorbar; title(sprintf('FDR %s: %s',CorType,num2str(contrasts(c,:)))); set(gca,'dataAspectRatio',[1 1 1],'Xtick',[],'Ytick',[]); end fprintf('\nContrast %s, Alpha = %8.7f, FDR\n',num2str(contrasts(c,:)),Alpha) % [ri,rj] = find(squeeze(ThrPmap)<1); [ri,rj] = find(squeeze(~isnan(ThrPmap))); for i = 1:length(ri) fprintf('%s (%d) --------- %s (%d) (T=%3.2f, p=%1.6f)\n',rnam{ri(i)},ri(i),rnam{rj(i)},rj(i),Tmap(c,ri(i),rj(i)),Pmap(c,ri(i),rj(i))) end end end return
github
MRC-CBU/riksneurotools-master
check_pooled_error.m
.m
riksneurotools-master/GLM/check_pooled_error.m
22,146
utf_8
99321534cf307de8082b85273a1efc3d
function [Pool,Part,QV] = check_pooled_error(S); % Pedagogical script to illustrate assumptions about error term(s) in % repeated-measures multi-factorial ANOVAs performed on many observations % (eg voxels in fMRI). Requires SPM8+ on path. % % Based on Henson & Penny (2003) Tech Report ("H&P03"): % http://www.mrc-cbu.cam.ac.uk/people/rik.henson/personal/HensonPenny_ANOVA_03.pdf % % ...and used for figures in Henson (in press) "ANOVA". Brain Mapping: A % comprehensive reference. % % [email protected], Jan 2011 % % Estimates p-values for a number of contrasts (ANOVA effects) as a % function of a (small) number of subjects and a (large) number of voxels % (experiments), either pooling the error over all conditions (effects), % or partitioning the error for each effect. Data can be generated % according to either a single or partitioned error, which is either white % (IID/spherical) or coloured (non-IID; nonspherical) % % Outputs: % Pool = subjects X effects X voxel matrix of p-values, assuming a % pooled error % Part = subjects X effects X voxel matrix of p-values, assuming % partitioned errors % AQV = estimated error covariance of pooled model (from highest % number of subjects provided) % % Also produces some figures - explained below! % % Written for ease of understanding, in relation to what SPM does, rather % than speed or elegance! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 1: If the data are generated by a single IID error % (albeit unlikely), then pooling is more efficient than partitioning error % % Run by: % % S.ftit = 'Single white error'; % Just title for plot % [Pool,Part,QV] = check_pooled_error(S); % % ie using defaults below, ie a 2x2 ANOVA design with factors A and B % % Results: % % 1. When there is no true effect (B=0 for main effect of B; red lines), % approx 5 percent of voxels survive p<.05 in both types of model - ie % type I error controlled with both pooled and partitioned error % % 2. When there is an effect however (eg, big main effect of A, or smaller % interaction), a greater percentage of voxels survive p<.05 for pooled % than partitioned error model (ie more power, because greater df's with % which to estimate error) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 2: If the data are generated by partitioned but IID error % terms, such that fixed correlation between errors induced, then pooling % is still more efficient, with no bias (unless those error terms are % non-IID, eg different (nonspherical) errors, as in demos below). % % Run by: % % S.GenPart = 1; % S.ftit = 'Partitioned errors'; % [Pool,Part,QV] = check_pooled_error(S); % % Results: % % 1. Similar to above, noting that when there is no true effect % (B=0 for main effect of B; red lines), pooled model still unbiased % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 3: If there is greater correlation in the error (nonsphericity), % owing to similar scores across conditions from the same subject (which is % likely), then pooled error becomes biased, but partitioning error is less % biased (indeed, UNbiased when only one numerator df per effect, as here) % % Run by: % % S.GenPart = 0; % S.V = [1 0 0.5 0; 0 1 0 0; 0.5 0 1 0; 0 0 0 1]; % S.ftit = 'Correlated error'; % % Eg because only true effects of A and AxB, make these correlated % [Pool,Part,AQV] = check_pooled_error(S); % % Results: % % 1. Now note that >5% of voxels have p<.05 under pooled error model (thin % red line) - ie invalid - but still correct 5% for partitioned error model % (thick red line) - ie still valid. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 4: If you try to estimate error covariance for each voxel % separately (using ReML), that estimate is poor (unless large number of % subjects), resulting in "poor" p-values. % % Run by: % % S.GenPart = 0; % S.PreWhiten = 1; % Separate ReML for each voxel % S.V = [1 0 0.5 0; 0 1 0 0; 0.5 0 1 0; 0 0 0 1]; % S.ftit = 'Voxel-wise estimation of correlated error'; % [Pool,Part,AQV] = check_pooled_error(S); % % Results: % % 1. Warnings as ReML unable to estimate error covariance for some random % data (some voxels), particularly when few subjects % % 2. Note that >5% of voxels have p<.05 under pooled error model (thin % red line) - ie invalid. % % 3. Note that power to detect real effects also reduced for pooled versus % partitioned error (green and blue lines lowered). % % This danger is probably why partitioning error is preferred in % behavioural statistics when typically only one variate (one voxel) - any % method (eg Greenhouse-Geisser) for correcting for correlated errors, % based on one sample of data, will entail an inefficient estimate of that % correlation (with few df's), so a poor correction (eg too conservative % in case of G-G). % % (This is the same general problem that estimating covariance matrices % efficiently requires large numbers of observations!) % % In imaging data however, we have many samples (voxels), so if we assume % that error correlation across conditions is same across voxels, we can % pool the samples to get a more precise estimate of that error % correlation (ie effectively increase number of observations so as to % increase accuracy of estimate of error covariance). % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 5: If you try to estimate the error covariance by pooling % data across voxels, in a two-step procedure like that used in SPM, then % you recover greater efficiency of pooled than partitioned model (when % there is a true effect), together with valid results when there is no % effect. Note however that this is only true if the underlying error % correlation IS the same across voxels (see next Demo) % % Run by: % % S.GenPart = 0; % S.PreWhiten = 2; % One ReML from data pooled across voxels % S.V = [1 0 0.5 0; 0 1 0 0; 0.5 0 1 0; 0 0 0 1]; % S.ftit = 'Voxel-wide estimation of correlated error'; % [Pool,Part,AQV] = check_pooled_error(S); % % Results: % % 1. We recover the situation in Demonstration 1, where pooling error is % more powerful when effects exist, but still valid when they do not. % % 2. [ To visualise nonsphericity: figure,imagesc(AQV),colormap('gray') ] % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Demonstration 6: If you try to estimate the error covariance by pooling % data across voxels, in a two-step procedure like that used in SPM, BUT % the true error correlation structure varies across voxels, the type I % error is again inflated (though not by much, at least when elements of % error covariance vary randomly between 0 and N^2, where N is maximum % element of common covariance term above % % Run by: % % S.GenPart = 0; % S.PreWhiten = 2; % One ReML from data pooled across voxels % S,VarVox = 1; % S.V = [1 0 0.5 0; 0 1 0 0; 0.5 0 1 0; 0 0 0 1]; % S.ftit = 'Voxel-wide estimation of correlated but nonstationary error'; % [Pool,Part,AQV] = check_pooled_error(S); % % 1. Thin red line shows increased false positive rate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try f = S.f; % Factorial design flab = S.flab; % Factor labels for plotting catch % Unless otherwise specified, assume a 2x2 design with factors A/B: f = [1 1 0 0; % Main effect of A 1 0 1 0; % Main effect of B 1 0 0 1; % AxB Interaction 1 1 1 1]'; % Constant flab = {'meA'; 'meB'; 'int'}; % Factor labels for plotting end C = detrend(f,0); % Convert to contrasts try B = S.B; % True Betas for 4 effects above catch % Unless otherwise specified, assume main effect of A, no main effect % of B, weaker interaction (and zero grand mean) B = [1 0 0.5 0]'; end CB = C*B; % Convert to Betas for individual conditions try V = S.V; % Covariance of true error catch % Unless otherwise specified, assume IID error. Note that construction % of partitioned error below can also induce nonspherical errors V = speye(size(C,2)); end try subs = S.subs; % Range of subject numbers to explore catch subs = [8:2:24]; end try Nvox = S.Nvox; % Number of voxels to explore catch Nvox = 1000; end try VarVox = S.VarVox; % Whether true correlation constant across voxels catch VarVox = 0; end % Explained above... try GenPart = S.GenPart; catch GenPart = 0; end try PreWhiten = S.PreWhiten; catch PreWhiten = 0; end % Just figure title for plotting try ftit = S.ftit; catch ftit = []; end rand('state',0); Ngrp = length(subs); Ncon = size(f,1); Neff = size(C,2) - 1; % Ignore constant term (grand mean) Pool = zeros(Ngrp,Neff); % Suprathreshold P-values for Pooled Error Part = Pool; % Suprathreshold P-values for Partitioned Error QV=[]; for s = 1:Ngrp; Nsub = subs(s); N = Nsub * Ncon; oS = ones(Nsub,1); oC = ones(Ncon,1); zS = zeros(Nsub,1); zC = zeros(Ncon,1); iS = eye(Nsub); iC = eye(Ncon); Bs = randn(Nsub,1); % Subject effects if PreWhiten > 0 YY = zeros(N); Q = varcomps(Ncon,Nsub); end % Basic (familiar) design matrix X = [kron(iC,oS) kron(oC,iS)]; %figure,imagesc(X),colormap('gray'); fprintf('%d',Nsub); for v = 1:Nvox % Generic way of generating data (with subject effects) % y = mvnrnd(repmat(CB',Nsub,1),V) + repmat(mvnrnd(zS',iS),Ncon,1)'; % y = y(:); if ~GenPart % Generate data assuming single error term if VarVox vV = rand(4) * max(V(:)); vV=vV'*vV; else vV = V; end try e = mvnrnd(repmat(zC',Nsub,1),vV); % If have Matlab's stats toolbox... catch e = spm_normrnd(zC',vV,Nsub)'; % ...else use SPM end y = X*[CB; Bs] + e(:); else % Generate data assuming partitioned errors % Full design matrix for partitioned model (Fig 9a H&P03) Xf = [kron(f,oS) kron(f,iS)]; %figure,imagesc(Xf),colormap('gray'); e = mvnrnd(repmat(zC',Nsub,1),V); y = Xf*[B; e(:)]; end % Estimate using pooled error, with different types of pre-whitening if PreWhiten == 0 for e = 1:Neff Pool(s,e,v) = Fstat(X,y,C(:,e)); end elseif PreWhiten == 1 QV = rik_reml(y*y',X,Q); W = PreWfilter(QV); WX = W*X; for e = 1:Neff Pool(s,e,v) = Fstat(WX,y,C(:,e)); end elseif PreWhiten == 2 Ay{s}(:,v) = y'; YY = YY + y*y'; end % Estimate using partitioned errors (Section 5.1 of H&P03) for e = 1:Neff yc = kron(C(:,e),iS)'*y; Part(s,e,v) = Fstat(oS,yc,[1]); %faster...? %T = mean(y)*sN/std(yc); %p = (1 - spm_Tcdf(T,N-1))*2; end end fprintf('.') if PreWhiten == 2 % Estimate nonsphericity pooled across voxels QV = rik_reml(YY/Nvox,X,Q); W = PreWfilter(QV); WX = W*X; for v = 1:Nvox y = W * Ay{s}(:,v); % Pre-whiten (same) data % Estimate using pooled error for e = 1:Neff Pool(s,e,v) = Fstat(WX,y,C(:,e)); end end end fprintf('.') end fprintf('\n') cols = {'b-';'r-';'g-'}; figure,hold on for e=1:Neff for s=1:Ngrp pPool(s) = length(find(Pool(s,e,:)<.05))/Nvox; pPart(s) = length(find(Part(s,e,:)<.05))/Nvox; end plot(subs,pPool,cols{e},'LineWidth',1); plot(subs,pPart,cols{e},'LineWidth',2); end ylabel('Prop. Voxels with p<.05'); xlabel('Number of Subjects'); if ~isempty(flab) llab = {}; for e=1:Neff llab{end+1} = [flab{e} 'pool']; llab{end+1} = [flab{e} 'part']; end legend(llab,'Location','Best') end if ~isempty(ftit) title(ftit) end CovEst = full(V-diag(diag(V))); CovEst = max(CovEst(:)); % Silly filename label! eval(sprintf('print -f%d -djpeg75 GenPart%d_PreWhiten%d_Cov%3.2f.jpg',gcf,GenPart,PreWhiten,CovEst)); return %----------------------------------------------------------------- function [p,r,B] = Fstat(X,y,c); % F-statistic for GLM X, data y and F-contrast matrix c. % See Appendix A.1 of: % http://www.mrc-cbu.cam.ac.uk/people/rik.henson/personal/HensonPenny_ANOVA_03.pdf %------------------------------------------------------------------ if size(c,1) < size(X,2) c = [c; zeros(size(X,2)-size(c,1),1)]; end B = pinv(X)*y; Y = X*B; r = y - Y; c_0 = eye(size(X,2)) - c*pinv(c); X_0 = X*c_0; R = eye(size(X,1)) - X*pinv(X); R_0 = eye(size(X,1)) - X_0*pinv(X_0); M = R_0 - R; df = [rank(X)-rank(X_0) size(X,1)-rank(X)]; F = ((B'*X'*M*X*B)/df(1)) / ((y'*R*y)/df(2)); p = 1-spm_Fcdf(F,df); return function Q = varcomps(Ncon,Nsub) % make set of variance components %------------------------------------------------------------------ Q={}; nv=0; z=zeros(Ncon*Nsub); id=[1:Nsub]; for c1 = 1:Ncon nv = nv+1; v = z; v((c1-1)*Nsub + id, (c1-1)*Nsub + id)=eye(Nsub); Q{nv} = sparse(v); end for c1 = 1:Ncon for c2 = (c1+1):Ncon nv = nv+1; v = z; v( (c1-1)*Nsub + id, (c2-1)*Nsub + id )=eye(Nsub); v( (c2-1)*Nsub + id, (c1-1)*Nsub + id )=eye(Nsub); Q{nv} = sparse(v); end end return function W = PreWfilter(V); % make W a whitening filter W*W' = inv(V) %------------------------------------------------------------------ [u s] = spm_svd(V); s = spdiags(1./sqrt(diag(s)),0,length(s),length(s)); W = u*s*u'; W = sparse(W.*(abs(W) > 1e-6)); return function [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,D,t) % estimate covariance components (from spm_reml) %------------------------------------------------------------------ % ReML estimation of [improper] covariance components from y*y' % FORMAT [C,h,Ph,F,Fa,Fc] = spm_reml(YY,X,Q,N,D,t); % % YY - (m x m) sample covariance matrix Y*Y' {Y = (m x N) data matrix} % X - (m x p) design matrix % Q - {1 x q} covariance components % N - number of samples % D - Flag for positive-definite scheme % t - regularisation (default 4) % % C - (m x m) estimated errors = h(1)*Q{1} + h(2)*Q{2} + ... % h - (q x 1) ReML hyperparameters h % Ph - (q x q) conditional precision of h % % F - [-ve] free energy F = log evidence = p(Y|X,Q) = ReML objective % % Fa - accuracy % Fc - complexity (F = Fa - Fc) % % Performs a Fisher-Scoring ascent on F to find ReML variance parameter % estimates. % %__________________________________________________________________________ % % John Ashburner & Karl Friston % $Id: spm_reml.m 3791 2010-03-19 17:52:12Z karl $ % check defaults %-------------------------------------------------------------------------- try, N; catch, N = 1; end % assume a single sample if not specified try, K; catch, K = 32; end % default number of iterations try, D; catch, D = 0; end % default checking try, t; catch, t = 4; end % default regularisation % catch NaNs %-------------------------------------------------------------------------- W = Q; q = find(all(isfinite(YY))); YY = YY(q,q); for i = 1:length(Q) Q{i} = Q{i}(q,q); end % dimensions %-------------------------------------------------------------------------- n = length(Q{1}); m = length(Q); % ortho-normalise X %-------------------------------------------------------------------------- if isempty(X) X = sparse(n,0); else X = spm_svd(X(q,:),0); end % initialise h and specify hyperpriors %========================================================================== h = zeros(m,1); for i = 1:m h(i,1) = any(diag(Q{i})); end hE = sparse(m,1); hP = speye(m,m)/exp(32); dF = Inf; D = 8*(D > 0); % ReML (EM/VB) %-------------------------------------------------------------------------- for k = 1:K % compute current estimate of covariance %---------------------------------------------------------------------- C = sparse(n,n); for i = 1:m C = C + Q{i}*h(i); end % positive [semi]-definite check %---------------------------------------------------------------------- for i = 1:D if min(real(eig(full(C)))) < 0 % increase regularisation and re-evaluate C %-------------------------------------------------------------- t = t - 1; h = h - dh; dh = spm_dx(dFdhh,dFdh,{t}); h = h + dh; C = sparse(n,n); for i = 1:m C = C + Q{i}*h(i); end else break end end % E-step: conditional covariance cov(B|y) {Cq} %====================================================================== iC = spm_inv(C); iCX = iC*X; if ~isempty(X) Cq = spm_inv(X'*iCX); else Cq = sparse(0); end % M-step: ReML estimate of hyperparameters %====================================================================== % Gradient dF/dh (first derivatives) %---------------------------------------------------------------------- P = iC - iCX*Cq*iCX'; U = speye(n) - P*YY/N; for i = 1:m % dF/dh = -trace(dF/diC*iC*Q{i}*iC) %------------------------------------------------------------------ PQ{i} = P*Q{i}; dFdh(i,1) = -sum(sum(PQ{i}'.*U))*N/2; end % Expected curvature E{dF/dhh} (second derivatives) %---------------------------------------------------------------------- for i = 1:m for j = i:m % dF/dhh = -trace{P*Q{i}*P*Q{j}} %-------------------------------------------------------------- dFdhh(i,j) = -sum(sum(PQ{i}'.*PQ{j}))*N/2; dFdhh(j,i) = dFdhh(i,j); end end % add hyperpriors %---------------------------------------------------------------------- e = h - hE; dFdh = dFdh - hP*e; dFdhh = dFdhh - hP; % Fisher scoring: update dh = -inv(ddF/dhh)*dF/dh %---------------------------------------------------------------------- dh = spm_dx(dFdhh,dFdh,{t}); h = h + dh; % predicted change in F - increase regularisation if increasing %---------------------------------------------------------------------- pF = dFdh'*dh; if pF > dF t = t - 1; else t = t + 1/4; end % revert to SPD checking, if near phase-transition %---------------------------------------------------------------------- if abs(pF) > 1e6 [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,t - 2); return else dF = pF; end % Convergence (1% change in log-evidence) %====================================================================== %fprintf('%s %-23d: %10s%e [%+3.2f]\n',' ReML Iteration',k,'...',full(pF),t); % final estimate of covariance (with missing data points) %---------------------------------------------------------------------- if dF < 1e-1, break, end end % re-build predicted covariance %========================================================================== V = 0; for i = 1:m V = V + W{i}*h(i); end % check V is positive semi-definite (if not already checked) %========================================================================== if ~D if min(eig(V)) < 0 [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,2); return end end % log evidence = ln p(y|X,Q) = ReML objective = F = trace(R'*iC*R*YY)/2 ... %-------------------------------------------------------------------------- Ph = -dFdhh; if nargout > 3 % tr(hP*inv(Ph)) - nh + tr(pP*inv(Pp)) - np (pP = 0) %---------------------------------------------------------------------- Ft = trace(hP*inv(Ph)) - length(Ph) - length(Cq); % complexity - KL(Ph,hP) %---------------------------------------------------------------------- Fc = Ft/2 + e'*hP*e/2 + spm_logdet(Ph*inv(hP))/2 - N*spm_logdet(Cq)/2; % Accuracy - ln p(Y|h) %---------------------------------------------------------------------- Fa = Ft/2 - trace(C*P*YY*P)/2 - N*n*log(2*pi)/2 - N*spm_logdet(C)/2; % Free-energy %---------------------------------------------------------------------- F = Fa - Fc; end
github
MRC-CBU/riksneurotools-master
fMRI_GLM_efficiency.m
.m
riksneurotools-master/GLM/fMRI_GLM_efficiency.m
9,235
utf_8
46ee5b1e36bfbabd4f5db7b3269b0071
function [e,sots,stim,X,df] = fMRI_GLM_efficiency(S); % Matlab function to calculate efficiency for fMRI GLMs. % [email protected], 2005 % % See for example: % % Henson, R.N. (2006). Efficient experimental design for fMRI. In K. Friston, J. Ashburner, S. Kiebel, T. Nichols, and W. Penny (Eds), Statistical Parametric Mapping: The analysis of functional brain images. Elsevier, London, 2006. pp. 193-210. % http://www.mrc-cbu.cam.ac.uk/personal/rik.henson/personal/Henson_SPM_06_preprint.pdf % % http://imaging.mrc-cbu.cam.ac.uk/imaging/DesignEfficiency % % ...and used for figures in Henson (in press) "Design Efficiency". Brain Mapping: A % comprehensive reference. % % Needs SPM5+ on path % Written for ease of exposition, not speed! % % Function take one of: % % 1. cell array of stimulus onset times (SOTS), and possibly durations, eg from SPM % 2. vector of stimulus codes (ie order of events) (if onset times not calculated) % 3. a transition matrix in order to generate 1+2 (if no onsets or stimulus train available) % % Inputs (fields of structure S): % % S.Ns = Number of scans (REQUIRED) % S.CM = Cell array of T or F contrast matrices (NOTE THAT THE L1 NORM OF CONTRASTS SHOULD % MATCH IN ORDER TO COMPARE THEIR EFFICIENCIES, EG CM{1}=[1 -1 1 -1]/2 CAN BE % COMPARED WITH CM{2}=[1 -1 0 0] BECAUSE NORM(Cm{i},1)==2 IN BOTH CASES % S.sots = cell array of onset times for each condition in units of scans (OPTIONAL; SEE ABOVE) % S.durs = cell array of durations for each condition in units of scans (OPTIONAL; SEE ABOVE) % S.stim = vector of events (OPTIONAL; SEE ABOVE) % S.TM.prev = Np x Nh transition matrix history of Np possible sequences of the previous Nh events (OPTIONAL; SEE ABOVE) % S.TM.next = Np x Nj transition matrix of probabilities of each of next Nj event-types for each of Np possible histories (OPTIONAL; SEE ABOVE) % S.SOAmin = minimal SOA (REQUIRED IF STIMULUS TRAIN OR TRANSITION MATRIX PROVIDED) % S.Ni = Number of stimuli (events) (REQUIRED IF ONLY TRANSITION MATRIX PROVIDED) % S.bf = type of HRF basis function (based on spm_get_bf.m) (DEFAULTS TO CANONICAL HRF) % S.HC = highpass filter cut-off (s) (DEFAULTS TO 120) % S.TR = inter-scan interval (s) (DEFAULTS TO 2) % S.t0 = initial transient (s) to ignore (DEFAULTS TO 30) % % Outputs: % % e = efficiency for each contrast in S.CM % sots = stimulus onset times (in scans), eg for input into SPM % stim = vector of stimulus codes (event-types), just for interest! % X = GLM design matrix % df = degrees of freedom left given model and filter % % Examples: % % 0. Simple user-specified blocked design % % S=[]; % S.TR = 1; % S.Ns = 1000; % S.sots{1} = [0:48:1000]; % Condition 1 onsets % S.sots{2} = [16:48:1000]; % Condition 2 onsets % S.durs{1} = 16; S.durs{2} = 16; % Both 16s epochs % S.CM{1} = [1 -1]; S.CM{2} = [1 -1]; % Contrast conditions, and conditions vs baseline % % [e,sots,stim,X,df] = fMRI_GLM_efficiency(S); % % % 1. Code-generated, randomised design with 2 event-types, canonical HRF interest in both differential and common effects % % S=[]; % S.Ni = 2000; % S.TR = 2; % S.Ns = 1000; % Must be more than S.Ni*S.SOAmin/TR % S.CM{1} = [1 -1]; % A-B % S.CM{2} = [1 1]; % A+B % S.HC = 120; % S.TM.prev = [1 2]'; % S.TM.next = [0.5 0.5; 0.5 0.5]; % S.bf = 'hrf'; % % soas = [1:20] % to explore efficiency as function of SOA % % S.SOAmin = soas(1); % [e(1,:),sots,stim,X,df] = fMRI_GLM_efficiency(S); % call once to generate stimulus train % S.stim = stim % ensure same event-train for all SOA % % for s = 2:length(soas) % S.SOAmin = soas(s); % e(s,:) = fMRI_GLM_efficiency(S); % end % figure,plot(soas,e) % % % 2. Randomised design with FIR and null events (S continued from above) % % S.bf = 'Finite Impulse Response' % S.TM.prev = [1 2]'; % S.TM.next = [1/3 1/3; 1/3 1/3]; % S = rmfield(S,'stim'); % S.SOAmin = 2; e=[]; % [e,sots,stim,X,df] = fMRI_GLM_efficiency(S); % % % 3. Blocked design with canonical HRF % % S.bf = 'hrf' % S = rmfield(S,'stim'); % % bls = [1:60]; e=[]; % for s = 1:length(bls) % bl = bls(s); % try S = rmfield(S,'TM'); end % for b=1:bl % S.TM.prev(b,:) = [ones(1,bl-(b-1)) 2*ones(1,b-1)]; % S.TM.prev(b+bl,:) = [2*ones(1,bl-(b-1)) ones(1,b-1)]; % S.TM.next(b,:) = [0 1]; % S.TM.next(b+bl,:) = [1 0]; % end % e(s,:) = fMRI_GLM_efficiency(S); % end % figure,plot(bls,e) try Ns = S.Ns; catch error('Please provide number of scans (volumes) in S.Ns') end df = Ns; try CM = S.CM; catch error('Must pass a Nc x Nj matrix of contrasts, where Nc = number of contrasts and Nk = number of evemt-types') end try TR = S.TR; catch TR = 2; % Assume 2s TR unless specified otherwise end try t0 = S.t0; catch t0 = 30; % Ignore initial 30s transient end dt = 0.2; % Minimum time for convolution space (seconds) st = round(TR/dt); t0 = round(t0/TR); rand('state',0); try sots = S.sots; stim = []; % Can't be bothered to create stim if sots provided! catch try SOAmin = S.SOAmin; ds = SOAmin/TR; stim = S.stim; sots = gensots(stim,ds); catch try TM.prev = S.TM.prev; TM.next = S.TM.next; Ni = S.Ni; stim = genstim(TM,Ni); sots = gensots(stim,ds); catch error('Either provide onsets in S.sots, stimuli in S.stim and SOA in S.SOAmin, or transition matrix in S.TM and number of stimuli in Ni') end end end try durs = S.durs; for j = 1:length(sots) if length(durs{j}) == 1 durs{j} = repmat(durs{j},1,length(sots{j})); elseif length(durs{j}) ~= length(sots{j}) error('Number of durations (%d) does not match number of onsets (%d) for condition %d',length(durs{j}),length(ons{j}),j) end end catch for j = 1:length(sots) durs{j} = zeros(1,length(sots{j})); % assume events if durations not specified end end try bf = S.bf; catch bf = 'hrf'; % SPM's canonical HRF % bf = 'Finite Impulse Response' % FIR end if isstr(bf) xBF.dt = dt; xBF.name = bf; xBF.length = 30; xBF.order = 30/TR; bf = spm_get_bf(xBF); bf = bf.bf; else % Assume bf is a TxNk matrix of basis functions in units of dt end try HC = S.HC; catch HC = 120; end if HC > 0 HO = fix(2*(Ns*TR)/HC+1); K = spm_dctmtx(Ns,HO); df = df - size(K,2); K = eye(Ns) - K*K'; else K = eye(Ns); end Nj = length(sots); Nk = size(bf,2); Nt = Ns*st; %% Create neural timeseries s = [1:st:Nt]; X = zeros(Ns,Nj*Nk); for j = 1:Nj u = zeros(Nt,1); for i = 1:length(sots{j}) o = [sots{j}(i)*st : st : (sots{j}(i)+durs{j}(i))*st]; u(round(o)+1) = 1; end for k = 1:Nk b = conv(u,bf(:,k)); X(:,(j-1)*Nk + k) = b(s); end end %% highpass filter and remove any transients and mean X = K*X; X = X(t0:end,:); X = detrend(X,0); df = df - size(X,2) - 1; %cc = corrcoef(X*CM'); %max(abs(cc-eye(size(cc,2)))) %% Calculate efficiency for each contrast (row of CM) and average for all contrasts Nc = length(CM); bCM = {}; for c = 1:Nc bCM{c} = kron(CM{c},eye(Nk)/Nk); end iXX = pinv(X'*X); for c = 1:Nc e(1,c) = 1/trace(bCM{c}*iXX*bCM{c}'); fprintf('Contrast %d: Efficiency = %f\n',c,e(1,c)) end fprintf('\n') return function sots = gensots(stim,ds); Ni = length(stim); Aj = unique(stim(find(stim>0))); if Aj(1)~=1 | any(diff(Aj)~=1) error('Stimuli must be numbered ordinally from 1 onwards') end Nj = length(Aj); sots = cell(Nj,1); for i = 1:Ni if stim(i) > 0 sots{stim(i)}(end+1) = i*ds; end end return function stim = genstim(TM,Ni); Nh = size(TM.prev,2); Np = size(TM.prev,1); Nj = size(TM.next,2); if any(TM.next(:) > 1) | any(TM.next(:) < 0) | any(sum(TM.next,2) > 1) error('All values in TM.next must be [0,1], and sum along rows must be [0,1]') end hist = ones(1,Nh)*NaN; stim = []; for i = 1:Ni h = rfind(hist,TM.prev,Nj); r = rand; if r <= sum(TM.next(h,:)) j = 1; while j < Nj & r > TM.next(h,j) r = r-TM.next(h,j); j = j+1; end hist = [hist(2:end) j]; stim(end+1) = j; else stim(end+1) = 0; % Null event end end return function r = rfind(row,matrix,Nj); Nr = size(matrix,1); Nc = size(matrix,2); h = find(isfinite(row)); %Nj = Nr^(1/Nc); if isempty(h) r = floor(rand*Nj)+1; else for r = 1:Nr if all((row(h) - matrix(r,h)) == 0) break; elseif r==Nr error('Should not get here if TM correct!'); end end end return
github
MRC-CBU/riksneurotools-master
rsfMRI_GLM.m
.m
riksneurotools-master/GLM/rsfMRI_GLM.m
25,725
utf_8
2654812ab9bb94b923565c58d1b0db46
function [Zmat, Bmat, pZmat, pBmat, aY, X0r] = rsfMRI_GLM(S); % [Zmat, Bmat, pZmat, pBmat, aY, X0r] = rsfMRI_GLM(S); % % Function (using SPM8 functions) for estimating linear regressions % between fMRI timeseries in each pair of Nr ROIs, adjusting for bandpass % filter, confounding timeseries (eg CSF) and (SVD of) various expansions of % movement parameters, and properly modelling dfs based on comprehensive % model of error autocorrelation. % % [email protected], Jan 2013 % % Many thanks to Linda Geerligs for pointing out improvements! % % S.Y = [Ns x Nr] data matrix, where Ns = number of scans (ie resting-state fMRI timeseries) and Nr = number of ROIs % S.M = [Ns x 6] matrix of 6 movement parameters from realignment (x,y,z,pitch,roll,yaw) % S.C = [Ns x Nc] matrix of confounding timeseries, Nc = number of confounds (eg extracted from WM, CSF or Global masks) % S.G = [0/1] - whether to include global over ROIs (ie given current data) (default = 0) % S.TR = time between volumes (TR), in seconds % % (S.HPC (default = 100) = highpass cut-off (in seconds) % (S.LPC (default = 10) = lowpass cut-off (in seconds) % (S.CY (default = {}) = precomputed covariance over pooled voxels (optional) % (S.pflag (default=0) is whether to calculate partial regressions too (takes longer)) % (S.svd_thr (default=.99) is threshold for SVD of confounds) % (S.SpikeMovAbsThr (default='', ie none) = absolute threshold for outliers based on RMS of Difference of Translations % (S.SpikeMovRelThr (default='', ie none) = relative threshold (in SDs) for outliers based on RMS of Difference of Translations or Rotations % (S.SpikeDatRelThr (default='', ie none) = relative threshold (in SDs) for mean of Y over voxels (outliers, though arbitrary?) % (S.SpikeLag (default=1) = how many TRs after a spike are modelled out as separate regressors % (S.StandardiseY (default = 0) = whether to Z-score each ROI's timeseries to get standardised Betas) % (S.PreWhiten (default = 1) = whether to estimate autocorrelation of error and prewhiten (slower, but better Z-values (less important for Betas?)) % (S.GlobMove = user-specified calculation of global movement) % % Zmat = [Nr x Nr] matrix of Z-statistics for linear regression from seed (row) to target (column) ROI % Bmat = [Nr x Nr] matrix of betas for linear regression from seed (row) to target (column) ROI % pZmat = [Nr x Nr] matrix of Z-statistics for partial linear regression from seed (row) to target (column) ROI % pZmat = [Nr x Nr] matrix of betas for partial linear regression from seed (row) to target (column) ROI % aY = data adjusted for confounds % X0r = confounds (filter, confound ROIs, movement expansion) % % Note: % some Inf Z-values can be returned in Zmat (when p-value so low than inv_Ncdf is infinite) % (these could be replaced by the maximum Z-value in matrix?) % % Potential improvements: % regularised regression (particularly for pZmat), eg L1 with LASSO - or L2 implementable with spm_reml_sc? try Y = S.Y; catch error('Need Nscans x Nrois data matrix'); end try C = S.C; catch error('Need Nscans x Nc matrix of Nc confound timeseries (Nc can be zero)'); end try TR = S.TR; catch error('Need TR (in secondss)'); end try HPC = S.HPC; catch HPC = 1/0.01; warning('Assuming highpass cut-off of %d',HPC); end try LPC = S.LPC; catch LPC = 1/0.2; warning('Assuming lowpass cut-off of %d',LPC); end try CY = S.CY; catch CY = []; end try GlobalFlag = S.G; catch GlobalFlag = 0; end try SpikeMovAbsThr = S.SpikeMovAbsThr; catch SpikeMovAbsThr = ''; % SpikeMovAbsThr = 0.5; % mm from Power et al % SpikeMovAbsThr = 0.25; % mm from Satterthwaite et al 2013 end try SpikeMovRelThr = S.SpikeMovRelThr; catch % SpikeMovRelThr = ''; SpikeMovRelThr = 5; % 5 SDs of mean? end try SpikeDatRelThr = S.SpikeDatRelThr; catch SpikeDatRelThr = ''; % SpikeDatRelThr = 5; % 5 SDs of mean? end try SpikeLag = S.SpikeLag; catch SpikeLag = 1; % SpikeLag = 5; % 5 TRs after spike? end try StandardiseY = S.StandardiseY; catch StandardiseY = 0; end try PreWhiten = S.PreWhiten; catch PreWhiten = 1; end try VolterraLag = S.VolterraLag; catch VolterraLag = 5; % artifacts can last up to 5 TRs = 10s, according to Power et al (2013) end try pflag = S.pflag; catch pflag = 0; end try svd_thr = S.svd_thr; catch svd_thr = .99; end Ns = size(Y,1); Nr = size(Y,2); %% If want to try Matlab's LASSO (takes ages though) % lassoflag = 0; % if lassoflag % matlabpool open % opts = statset('UseParallel','always'); % end %% Create a DCT bandpass filter (so filtering part of model, countering Hallquist et al 2013 Neuroimage) K = spm_dctmtx(Ns,Ns); nHP = fix(2*(Ns*TR)/HPC + 1); nLP = fix(2*(Ns*TR)/LPC + 1); K = K(:,[2:nHP nLP:Ns]); % Remove initial constant Nk = size(K,2); fprintf('Bandpass filter using %d dfs (%d left)\n',Nk,Ns-Nk) %% Create comprehensive model of residual autocorrelation (to counter Eklund et al, 2012, Neuroimage) if PreWhiten T = (0:(Ns - 1))*TR; % time d = 2.^(floor(log2(TR/4)):log2(64)); % time constants (seconds) Q = {}; % dictionary of components for i = 1:length(d) for j = 0:1 Q{end + 1} = toeplitz((T.^j).*exp(-T/d(i))); end end end %% Detect outliers in movement and/or data %M = detrend(M,0); %M(:,4:6)= M(:,4:6)*180/pi; if ~isfield(S,'GlobMove') try M = S.M; catch error('Need Nscans x 6 movement parameter matrix'); end if size(M,2) == 6 dM = [zeros(1,6); diff(M,1,1)]; % First-order derivatives % Combine translations and rotations based on ArtRepair approximation for voxels 65mm from origin? %cdM = sqrt(sum(dM(:,1:3).^2,2) + 1.28*sum(dM(:,4:6).^2,2)); dM(:,4:6) = dM(:,4:6)*50; % Approximate way of converting rotations to translations, assuming sphere radius 50mm (and rotations in radians) from Linda Geerligs cdM = sum(abs(dM),2); else error('If not user-specified global movement passed, then must pass 3 translations and 3 rotations') end else cdM = S.GlobMove; try M = S.M; catch M=[]; end end if ~isempty(SpikeMovAbsThr) % Absolute movement threshold % rms = sqrt(mean(dM(:,1:3).^2,2)); % if want translations only % aspk = find(rms > SpikeMovAbsThr); aspk = find(cdM > SpikeMovAbsThr); fprintf('%d spikes in absolute movement differences (based on threshold of %4.2f)\n',length(aspk),SpikeMovAbsThr) else aspk = []; end if ~isempty(SpikeMovRelThr) % Relative (SD) threshold for translation and rotation % rms = sqrt(mean(dM(:,1:3).^2,2)); % rspk = find(rms > (mean(rms) + SpikeMovRelThr*std(rms))); % rms = sqrt(mean(dM(:,4:6).^2,2)); % rspk = [rspk; find(rms > (mean(rms) + SpikeMovRelThr*std(rms)))]; rspk = find(cdM > (mean(cdM) + SpikeMovRelThr*std(cdM))); fprintf('%d spikes in relative movement differences (based on threshold of %4.2f SDs)\n',length(rspk),SpikeMovRelThr) else rspk = []; end if ~isempty(SpikeDatRelThr) % Relative (SD) threshold across all ROIs (dangerous? Arbitrary?) dY = [zeros(1,Nr); diff(Y,1,1)]; rms = sqrt(mean(dY.^2,2)); dspk = find(rms > (mean(rms) + SpikeDatRelThr*std(rms))); fprintf('%d spikes in mean data across ROIs (based on threshold of %4.2f SDs)\n',length(dspk),SpikeDatRelThr) else dspk = []; end %% Create delta-function regressors for each spike spk = unique([aspk; rspk; dspk]); lspk = spk; for q = 2:SpikeLag lspk = [lspk; spk + (q-1)]; end spk = unique(lspk); if ~isempty(spk) RSP = zeros(Ns,length(spk)); n = 0; for p = 1:length(spk) if spk(p) <= Ns n=n+1; RSP(spk(p),n) = 1; end end fprintf('%d unique spikes in total\n',length(spk)) RSP = spm_en(RSP,0); else RSP = []; end %% Create expansions of movement parameters % Standard differential + second-order expansion (a la Satterthwaite et al, 2012) % sM = []; for m=1:6; for n=m:6; sM = [sM M(:,m).*M(:,n)]; end; end % Second-order expansion % sdM = []; for m=1:6; for n=m:6; sdM = [sdM dM(:,m).*dM(:,n)]; end; end % Second-order expansion of derivatives % aM = [M dM sM sdM]; % Above commented bits are subspace of more general Volterra expansion %U=[]; for c=1:6; U(c).u = M(:,c); U(c).name{1}=sprintf('m%d',c); end; [aM,aMname] = spm_Volterra(U,[1 0 0; 1 -1 0; 0 1 -1]',2); %U=[]; for c=1:6; U(c).u = M(:,c); U(c).name{1}=sprintf('m%d',c); end; [aM,aMname] = spm_Volterra(U,[1 0; 1 -1; 0 1]',2); %Only N and N+1 needed according to Satterthwaite et al 2013 bf = eye(VolterraLag); % artifacts can last up to 5 TRs = 10s, according to Power et al (2013) % bf = [1 0 0 0 0; 1 1 0 0 0; 1 1 1 0 0; 1 1 1 1 0; 1 1 1 1 1]; % only leads to a few less modes below, and small compared to filter anyway! bf = [bf; diff(bf)]; U=[]; for c=1:size(M,2); U(c).u = M(:,c); U(c).name{1}='c'; end; aM = spm_Volterra(U,bf',2); aM = spm_en(aM,0); %% Add Global? (Note: may be passed by User in S.C anyway) % (recommended by Rik and Power et al, 2013, though will entail negative % correlations, which can be problem for some graph-theoretic measures) if GlobalFlag C = [C mean(Y,2)]; end C = spm_en(C,0); %% Combine all confounds (assumes more data than confounds, ie Ns > Nc) and perform dimension reduction (cf PCA of correlation matrix) %X0 = [C RSP K(:,2:end) aM]; % exclude constant term from K XM = spm_en(ones(Ns,1)); % constant term X1 = [XM K RSP]; % Regressors that don't want to SVD X0 = [aM C]; % Regressors that will SVD below %X1 = [XM K C RSP]; % Regressors that don't want to SVD %X0 = [aM]; % Regressors that will SVD below X0r = X0; if ~isempty(X0) R1 = eye(Ns) - X1*pinv(X1); X0 = R1*X0; % Project out of SVD-regressors what explained by non-SVD regressors! X0 = spm_en(X0,0); % Possible of course that some dimensions tiny part of SVD of X (so excluded) by happen to correlate highly with y... % ...could explore some L1 (eg LASSO) or L2 regularisation of over-parameterised model instead, % but LASSO takes ages (still working on possible L2 approach with spm_reml) if svd_thr < 1 [U,S] = spm_svd(X0,0); S = diag(S).^2; S = full(cumsum(S)/sum(S)); Np = find(S > svd_thr); Np = Np(1); X0r = full(U(:,1:Np)); fprintf('%d SVD modes left (from %d original terms) - %4.2f%% variance of correlation explained\n',Np,size(X0,2),100*S(Np)) end end X0r = [K RSP X0r XM]; % Reinsert mean Nc = size(X0r,2); if Nc >= Ns; error('Not enough dfs (scans) to estimate'); else fprintf('%d confounds for %d scans (%d left)\n',Nc,Ns,Ns-Nc); end %% Create adjusted data, in case user wants for other metrics, eg, MI, and standardised data, if requested R = eye(Ns) - X0r*pinv(X0r); aY = R*Y; if StandardiseY Y = zscore(Y); else Y = Y/std(Y(:)); % Some normalisation necessary to avoid numerical underflow, eg in cov(Y') below end %% Pool data covariance over ROIs (assuming enough of them!), unless specified if isempty(CY) & PreWhiten CY = cov(Y'); % Correct to only do this after any standardisation? end %%%%%%%%%%%%%%%%%%%%%%%%%% Main Loop %% Do GLMs for all target ROIs for a given source ROI Ar = [1:Nr]; Zmat = zeros(Nr); % Matrix of Z statistics for each pairwise regression Bmat = zeros(Nr); if pflag pZmat = zeros(Nr); % Matrix of Z statistics for each pairwise partial regression pBmat = zeros(Nr); % Matrix of Z statistics for each pairwise partial regression else pZmat = []; pBmat = []; end %[V h] = rik_reml(CY,X0r,Q,1,0,4); % if could assume that error did not depend on seed timeseries %W = spm_inv(spm_sqrtm(V)); lNpc = 0; % Just for printing pflag output below for n = 1:Nr Ir = setdiff(Ar,n); Yr = Y(:,Ir); % Yr contains all other timeseries, so ANCOVA below run on Nr-2 timeseries in one go Xr = Y(:,n); % Xr = spm_en(Xr); % Normalise regressors so Betas can be compared directly across (seed) ROIs (not necessary if Standardised Y already)? X = [Xr X0r]; % if lassoflag == 1 % takes too long (particularly for cross-validation to determine lambda) % for pn = 1:length(Ir) % Ir = setdiff(Ar,pn); % % Yr = Y(:,Ir); % Yr contains all other timeseries, so ANCOVA below run on Nr-2 timeseries in one go % Xr = Y(:,pn); % Xr = spm_en(Xr,0); % Normalise regressors so Betas can be compared directly across (seed) ROIs (not necessary is Standardised Y already)? % % fprintf('l'); % [lB,lfit] = lasso(X0r,Yr(:,pn),'CV',10,'Options',opts); % keepX = find(lB(:,lfit.Index1SE)); % X = [Xr X0r(:,keepX)]; % Nc = length(keepX); % % [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up % W = spm_inv(spm_sqrtm(V)); % % %% Estimate T-value for regression of first column (seed timeseries) % [T(pn),dfall,Ball] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Nc)]'); % df(pn) = dfall(2); % B(pn) = Ball(1); % end % fprintf('\n'); % else %% Estimate autocorrelation of error (pooling across ROIs) and prewhitening matrix if PreWhiten [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up W = spm_inv(spm_sqrtm(V)); else W = speye(Ns); end %% Estimate T-value for regression of first column (seed timeseries) [T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr,[1 zeros(1,Nc)]'); try Zmat(n,Ir) = norminv(spm_Tcdf(T,df(2))); % Needs Matlab Stats toolbox, but has larger range of Z (so not so many "Inf"s) catch Zmat(n,Ir) = spm_invNcdf(spm_Tcdf(T,df(2))); end Bmat(n,Ir) = B(1,:); %% Estimate T-value for PARTIAL regression of first column (seed timeseries) - takes ages! if pflag for pn = 1:length(Ir) pIr = setdiff(Ar,[n Ir(pn)]); pY = spm_en(Y(:,pIr),0); % Is necessary for SVD below % SVD if svd_thr < 1 [U,S] = spm_svd([pY X0],0); S = diag(S).^2; S = full(cumsum(S)/sum(S)); Np = find(S > svd_thr); Np = Np(1); XY0 = full(U(:,1:Np)); Npc = Np; else XY0 = [pY X0]; end XY0 = [XY0 ones(Ns,1)]; % Reinsert mean Npc = size(XY0,2); % if lassoflag == 1 % fprintf('l') % [lB,lfit] = lasso(XY0,Yr(:,pn),'CV',10,'Options',opts); % keepX = find(lB(:,lfit.Index1SE)); % X = [Xr XY0(:,keepX)]; % Nc = length(keepX); % % [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up % W = spm_inv(spm_sqrtm(V)); % % %% Estimate T-value for regression of first column (seed timeseries) % [T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Nc)]'); % else if Npc >= (Ns-1) % -1 because going to add Xr below warning('Not enough dfs (scans) to estimate - just adjusting data and ignoring loss of dfs'); R = eye(Ns) - pY*pinv(pY); % Residual-forming matrix [T,df,B] = spm_ancova(W*X,speye(Ns,Ns),R*W*Yr(:,pn),[1 zeros(1,Npc)]'); % Ok to assume error and hence W unaffected by addition of pY in X? else if lNpc ~= Npc % Just to reduce time taken to print to screen fprintf(' partial for seed region %d and target region %d: %d confounds for %d scans (%d left)\n',n,pn,Npc,Ns,Ns-Npc); end lNpc = Npc; X = [Xr XY0]; %% Commented out below because ok to assume error and hence W unaffected by addition of pY in X? % [V h] = rik_reml(CY,X,Q,1,0,4); % rik_reml is just version of spm_reml with fprintf commented out to speed up % W = spm_inv(spm_sqrtm(V)); %% Estimate T-value for regression of first column (seed timeseries) [T,df,B] = spm_ancova(W*X,speye(Ns,Ns),W*Yr(:,pn),[1 zeros(1,Npc)]'); end try pZmat(n,Ir(pn)) = norminv(spm_Tcdf(T,df(2))); catch pZmat(n,Ir(pn)) = spm_invNcdf(spm_Tcdf(T,df(2))); end pBmat(n,Ir(pn)) = B(1); end end fprintf('.') end fprintf('\n') return %figure,imagesc(Zmat); colorbar %figure,imagesc(pZmat); colorbar function [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,D,t,hE,hP) % ReML estimation of [improper] covariance components from y*y' % FORMAT [C,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,D,t,hE,hP); % % YY - (m x m) sample covariance matrix Y*Y' {Y = (m x N) data matrix} % X - (m x p) design matrix % Q - {1 x q} covariance components % % N - number of samples (default 1) % D - Flag for positive-definite scheme (default 0) % t - regularisation (default 4) % hE - hyperprior (default 0) % hP - hyperprecision (default 1e-16) % % C - (m x m) estimated errors = h(1)*Q{1} + h(2)*Q{2} + ... % h - (q x 1) ReML hyperparameters h % Ph - (q x q) conditional precision of h % % F - [-ve] free energy F = log evidence = p(Y|X,Q) = ReML objective % % Fa - accuracy % Fc - complexity (F = Fa - Fc) % % Performs a Fisher-Scoring ascent on F to find ReML variance parameter % estimates. % % see also: spm_reml_sc for the equivalent scheme using log-normal % hyperpriors %__________________________________________________________________________ % % SPM ReML routines: % % spm_reml: no positivity constraints on covariance parameters % spm_reml_sc: positivity constraints on covariance parameters % spm_sp_reml: for sparse patterns (c.f., ARD) % %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner & Karl Friston % $Id: spm_reml.m 5223 2013-02-01 11:56:05Z ged $ % Modified by Rik to remove screen output and turn off warnings % check defaults %-------------------------------------------------------------------------- try, N; catch, N = 1; end % assume a single sample if not specified try, K; catch, K = 32; end % default number of iterations try, D; catch, D = 0; end % default checking try, t; catch, t = 4; end % default regularisation try, hE; catch, hE = 0; end % default hyperprior try, hP; catch, hP = 1e-16; end % default hyperprecision % catch NaNs %-------------------------------------------------------------------------- W = Q; q = find(all(isfinite(YY))); YY = YY(q,q); for i = 1:length(Q) Q{i} = Q{i}(q,q); end % dimensions %-------------------------------------------------------------------------- n = length(Q{1}); m = length(Q); % ortho-normalise X %-------------------------------------------------------------------------- if isempty(X) X = sparse(n,0); else X = spm_svd(X(q,:),0); end % initialise h and specify hyperpriors %========================================================================== h = zeros(m,1); for i = 1:m h(i,1) = any(diag(Q{i})); end hE = sparse(m,1) + hE; hP = speye(m,m)*hP; dF = Inf; D = 8*(D > 0); warning off % ReML (EM/VB) %-------------------------------------------------------------------------- for k = 1:K % compute current estimate of covariance %---------------------------------------------------------------------- C = sparse(n,n); for i = 1:m C = C + Q{i}*h(i); end % positive [semi]-definite check %---------------------------------------------------------------------- for i = 1:D if min(real(eig(full(C)))) < 0 % increase regularisation and re-evaluate C %-------------------------------------------------------------- t = t - 1; h = h - dh; dh = spm_dx(dFdhh,dFdh,{t}); h = h + dh; C = sparse(n,n); for i = 1:m C = C + Q{i}*h(i); end else break end end % E-step: conditional covariance cov(B|y) {Cq} %====================================================================== iC = spm_inv(C); iCX = iC*X; if ~isempty(X) Cq = spm_inv(X'*iCX); else Cq = sparse(0); end % M-step: ReML estimate of hyperparameters %====================================================================== % Gradient dF/dh (first derivatives) %---------------------------------------------------------------------- P = iC - iCX*Cq*iCX'; U = speye(n) - P*YY/N; for i = 1:m % dF/dh = -trace(dF/diC*iC*Q{i}*iC) %------------------------------------------------------------------ PQ{i} = P*Q{i}; dFdh(i,1) = -spm_trace(PQ{i},U)*N/2; end % Expected curvature E{dF/dhh} (second derivatives) %---------------------------------------------------------------------- for i = 1:m for j = i:m % dF/dhh = -trace{P*Q{i}*P*Q{j}} %-------------------------------------------------------------- dFdhh(i,j) = -spm_trace(PQ{i},PQ{j})*N/2; dFdhh(j,i) = dFdhh(i,j); end end % add hyperpriors %---------------------------------------------------------------------- e = h - hE; dFdh = dFdh - hP*e; dFdhh = dFdhh - hP; % Fisher scoring: update dh = -inv(ddF/dhh)*dF/dh %---------------------------------------------------------------------- dh = spm_dx(dFdhh,dFdh,{t}); h = h + dh; % predicted change in F - increase regularisation if increasing %---------------------------------------------------------------------- pF = dFdh'*dh; if pF > dF t = t - 1; else t = t + 1/4; end % revert to SPD checking, if near phase-transition %---------------------------------------------------------------------- if ~isfinite(pF) || abs(pF) > 1e6 [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,t - 2); return else dF = pF; end % Convergence (1% change in log-evidence) %====================================================================== % fprintf('%s %-23d: %10s%e [%+3.2f]\n',' ReML Iteration',k,'...',full(pF),t); % final estimate of covariance (with missing data points) %---------------------------------------------------------------------- if dF < 1e-1, break, end end % re-build predicted covariance %========================================================================== V = 0; for i = 1:m V = V + W{i}*h(i); end % check V is positive semi-definite (if not already checked) %========================================================================== if ~D if min(eig(V)) < 0 [V,h,Ph,F,Fa,Fc] = rik_reml(YY,X,Q,N,1,2,hE(1),hP(1)); return end end % log evidence = ln p(y|X,Q) = ReML objective = F = trace(R'*iC*R*YY)/2 ... %-------------------------------------------------------------------------- Ph = -dFdhh; if nargout > 3 % tr(hP*inv(Ph)) - nh + tr(pP*inv(Pp)) - np (pP = 0) %---------------------------------------------------------------------- Ft = trace(hP*inv(Ph)) - length(Ph) - length(Cq); % complexity - KL(Ph,hP) %---------------------------------------------------------------------- Fc = Ft/2 + e'*hP*e/2 + spm_logdet(Ph*inv(hP))/2 - N*spm_logdet(Cq)/2; % Accuracy - ln p(Y|h) %---------------------------------------------------------------------- Fa = Ft/2 - trace(C*P*YY*P)/2 - N*n*log(2*pi)/2 - N*spm_logdet(C)/2; % Free-energy %---------------------------------------------------------------------- F = Fa - Fc; end warning on function [C] = spm_trace(A,B) % fast trace for large matrices: C = spm_trace(A,B) = trace(A*B) % FORMAT [C] = spm_trace(A,B) % % C = spm_trace(A,B) = trace(A*B) = sum(sum(A'.*B)); %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_trace.m 4805 2012-07-26 13:16:18Z karl $ % fast trace for large matrices: C = spm_trace(A,B) = trace(A*B) %-------------------------------------------------------------------------- C = sum(sum(A'.*B));
github
MRC-CBU/riksneurotools-master
glm.m
.m
riksneurotools-master/GLM/glm.m
3,169
utf_8
727c465a37a6081510ffb063ffcde950
function [t,F,p,df,R2,cR2,B,r,aR2,iR2] = glm(y,X,c,pflag); % [t,F,p,df,R2,cR2,B] = glm(y,X,c,pflag); % % Generic function for General Linear Model (GLM) % Note: assumes error is spherical (residuals white) % Rik Henson, 2004 % % (Note requires Matlab stats toolbox, or SPM functions to be on path) % % Input: % y = n column vector of observations % X = n x p (design) matrix % c = p x e contrast matrix for T- (e=1) or F- (e>1) contrast % pflag = whether to print fit % % Output % t = T-value % F = F-value % p = p-value % df = degrees of freedom % R2 = model fit (% variance explained) % cR2 = contrast fit (% variance explained) % B = p betas (parameter estimates) if nargin<4 pflag=0; end B = pinv(X)*y; Y = X*B; r = y - Y; if size(c,2) > size(c,1) warning('Transposing c!') c = c'; end l = size(c,1); if l < size(X,2) c = [c; zeros(size(X,2)-l,size(c,2))]; warning('Padding c with zeros!') end df = length(y) - rank(X); % T and F's could be combined, but done separately for pedagogical reasons if size(c,2)==1 s = r'*r / df; t = c'*B / sqrt(s*c'*pinv(X'*X)*c); p = t2p(t,df); F = t.^2; cR2 = F2R(F,1,df); R2 = 1 - (r'*r) / (y'*y); aR2 = 1 - (r'*r/df(end)) / (y'*y/(length(y)-1)); fprintf('T(%d)=%f, p(one-tailed)=%f (R2=%3.2f; overall R2=%3.2f (adjusted R2=%3.2f))\n',df,t,p,cR2,R2,aR2); else c_0 = eye(size(X,2)) - c*pinv(c); X_0 = X*c_0; R = eye(size(X,1)) - X*pinv(X); R_0 = eye(size(X,1)) - X_0*pinv(X_0); M = R_0 - R; df = [rank(X)-rank(X_0) size(X,1)-rank(X)]; F = ((B'*X'*M*X*B)/df(1)) / ((y'*R*y)/df(2)); p = F2p(F,df(1),df(2)); t = []; cR2 = F2R(F,df(1),df(2)); R2 = 1 - (r'*r) / (y'*y); aR2 = 1 - (r'*r/df(end)) / (y'*y/(length(y)-1)); fprintf('F(%d,%d)=%f, p(two-tailed)=%f (R2=%3.2f; overall R2=%3.2f (adjusted R2=%3.2f))\n',df(1),df(2),F,p,cR2,R2,aR2); end %Below doesn't work if constant not included %R2 = 1 - (r'*r) / (y'*y); %R2 = (Y'*Y)/(y'*y) equivalent %disp(sprintf('Overall R2 = %f',R2)) %aR2 = 1 - (r'*r/df(end)) / (y'*y/(length(y)-1)); %disp(sprintf('Overall Adjusted R2 (assumes a constant in model) = %f',R2)) % Hacky way to calculate unique contribution of contrast c_0 = eye(size(X,2)) - c*pinv(c); X_0 = X*c_0; y_0 = X_0*(pinv(X_0)*y); r_0 = y - y_0; iR2 = R2 - (1 - (r_0'*r_0) / (y'*y)); if pflag figure(pflag), clf Ne = size(c,2); for e = 1:Ne subplot(1,Ne,e), hold on Xc = X*c(:,e); Yc = Xc*(c(:,e)'*B); yc = Yc+r; plot(Xc,yc,'r.') plot(Xc,Yc,'b-') end end return %%%%%%%%%%%%%%%%%% function p=t2p(t,df); % one-tailed p-value try p=tcdf(t,df); catch try p=spm_Tcdf(t,df); catch error('Need Matlab Stats toolbox (tcdf) or SPM on path') end end f=find(p>0.5); p(f)=1-p(f); return %%%%%%%%%%%%%%%%%%%% function p=F2p(F,df1,df2); % one-tailed p-value try p=1-fcdf(F,df1,df2); catch try p=1-spm_Fcdf(F,df1,df2); catch error('Need Matlab Stats toolbox (fcdf) or SPM on path') end end return %%%%%%%%%%%%%%%%%%%% function R2=F2R(F,df1,df2); R2=df1*F/(df2+df1*F); return
github
MRC-CBU/riksneurotools-master
repanova.m
.m
riksneurotools-master/GLM/repanova.m
4,310
utf_8
38052a299232e70d7a8721730a835a0e
function [efs,F,cdfs,p,eps,dfs,b,y2,sig,mse]=repanova5(d,D,fn,gg,alpha); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Version5 has return of mse added (eg for plotting Loftus error bars) % % [efs,F,cdfs,p,eps,dfs,b,y2,sig] = repanova(d,D,fn,gg,alpha); % % R.Henson, 17/3/03; [email protected] % % General N-way (OxPxQxR...) repeated measures ANOVAs (no nonrepeated factors) % % Input: % % d = data A matrix with rows = replications (eg subjects) and % columns = conditions % % D = factors A vector with as many entries as factors, each entry being % the number of levels for that factor % % Data matrix d must have as many columns (conditions) as % the product of the elements of the factor matrix D % % First factor rotates slowest; last factor fastest % % Eg, in a D=[2 3] design: factor A with 2 levels; factor B with 3: % data matrix d must be organised: % % A1B1 A1B2 A1B3 A2B1 A2B2 A2B3 % rep1 % rep2 % ... % % Output: % % efs = effect, eg [1 2] = interaction between factor 1 and factor 2 % F = F value % cdfs = corrected df's (using Greenhouse-Geisser) % p = p-value % eps = epsilon % dfs = original dfs % b = betas % y2 = cell array of means for each level in a specific ANOVA effect % sig = cell array of significant effects (uncorrected and Bonferroni corrected) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin<5 alpha=0.05; end if nargin<4 gg=1; % G-G correction end if nargin<3 % No naming of factors provided for f=1:length(D) fn{f}=sprintf('%d',f); end end Nf = length(D); % Number of factors Nd = prod(D); % Number of conditions Ne = 2^Nf - 1; % Number of effects Nr = size(d,1); % Number of replications (eg subjects) sig=cell(2,1); if size(d,2) ~= Nd error(sprintf('data has %d conditions; design only %d',size(d,2),Nd)) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sc = cell(Nf,2); % create main effect/interaction component contrasts for f = 1 : Nf sc{f,1} = ones(D(f),1); % sc{f,2} = detrend(eye(D(f)),0); sc{f,2} = orth(diff(eye(D(f)))'); % identical answer to above! end sy = cell(Nf,2); % create main effect/interaction components for means for f = 1 : Nf sy{f,1} = ones(D(f),1)/D(f); sy{f,2} = eye(D(f)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for e = 1 : Ne % Go through each effect cw = num2binvec(e,Nf)+1; c = sc{1,cw(Nf)}; % create full contrasts for f = 2 : Nf c = kron(c,sc{f,cw(Nf-f+1)}); end y = d * c; % project data to contrast sub-space cy = sy{1,cw(Nf)}; % calculate component means for f = 2 : Nf cy = kron(cy,sy{f,cw(Nf-f+1)}); end y2{e} = mean(d * cy); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nc = size(y,2); df1 = rank(c); df2 = df1*(Nr-1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % long GLM way (no GG): % % y = y(:); % X = kron(eye(nc),ones(Nr,1)); % b{e} = pinv(X)*y; % Y = X*b{e}; % R = eye(nc*Nr)- X*pinv(X); % r = y - Y; %% V = r*r'; % V = y*y'; % eps(e) = trace(R*V)^2 / (df1 * trace((R*V)*(R*V))); % %% ss = Y'*y; %% mse = (y'*y - ss)/df2; %% mss = ss/df1; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % computationally simpler way b{e} = mean(y); ss = sum(y*b{e}'); mse = (sum(diag(y'*y)) - ss)/df2; mss = ss/df1; if gg V = cov(y); % sample covariance eps(e) = trace(V)^2 / (df1*trace(V'*V));% Greenhouse-Geisser else eps(e) = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% efs{e} = Nf+1-find(cw==2); % codes which effect F(e) = mss/mse; dfs(e,:) = [df1 df2]; cdfs(e,:) = eps(e)*dfs(e,:); p(e) = 1-spm_Fcdf(F(e),cdfs(e,:)); if p(e) < alpha; sig{1}=[sig{1} e]; end if p(e) < alpha/Ne; sig{2}=[sig{2} e]; end en=fn{efs{e}(1)}; % Naming of factors for f = 2:length(efs{e}) en = [fn{efs{e}(f)} en]; end disp(sprintf('Effect %02d: %-18s F(%3.2f,%3.2f)=%4.3f,\tp=%4.3f',... e,en,cdfs(e,1),cdfs(e,2),F(e),p(e))) end disp(sprintf('\n')) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Sub-function to code all main effects/interactions function b = num2binvec(d,p) if nargin<2 p = 0; % p is left-padding with zeros option end d=abs(round(d)); if(d==0) b = 0; else b=[]; while d>0 b=[rem(d,2) b]; d=floor(d/2); end end b=[zeros(1,p-length(b)) b];
github
sergiosanchoasensio/Traffic-sign-detection-and-recognition-master
TrafficSignDetection.m
.m
Traffic-sign-detection-and-recognition-master/Code/TrafficSignDetection.m
16,035
utf_8
450099e1e5f638e9fb7600a461066695
function TrafficSignDetection(directory, pixel_method, th, filename, window_method, decision_method, str, str2) % TrafficSignDetection % Perform detection of Traffic signs on images. Detection is performed first at the pixel level % using a color segmentation. Then, using the color segmentation as a basis, the most likely window % candidates to contain a traffic sign are selected using basic features (form factor, filling factor). % Finally, a decision is taken on these windows using geometric heuristics (Hough) or template matching. % % Parameter name Value % -------------- ----- % 'directory' directory where the images to analize (.jpg) reside % 'pixel_method' Name of the color space: 'opp', 'normrgb', 'lab', 'hsv', etc. (Weeks 2-5) % 'th' Vector that holds the thresholds for the color space % 'filename' File where the output will be written % 'window_method' 'SegmentationCCL' or 'SlidingWindow' (Weeks 3-5) % 'decision_method' 'GeometricHeuristics' or 'TemplateMatching' (Weeks 4-5) % 'str' Structuring element for first morphological operation % 'str2' Structuring element for second morphological operation global CANONICAL_W; CANONICAL_W = 64; global CANONICAL_H; CANONICAL_H = 64; global SW_STRIDEX; SW_STRIDEX = 8; global SW_STRIDEY; SW_STRIDEY = 8; global SW_CANONICALW; SW_CANONICALW = 32; global SW_ASPECTRATIO; SW_ASPECTRATIO = 1; global SW_MINS; SW_MINS = 1; global SW_MAXS; SW_MAXS = 2.5; global SW_STRIDES; SW_STRIDES = 1.2; % Load models global circleTemplate; global givewayTemplate; %global stopTemplate; global rectangleTemplate; global triangleTemplate; %if strcmp(decision_method, 'TemplateMatching') load('Templates/TemplateCircles.mat'); circleTemplate = TemplateCircles; load('Templates/TemplateGiveways.mat'); givewayTemplate = TemplateGiveways; %stopTemplate = load('Templates/TemplateStops.mat'); load('Templates/TemplateRectangles.mat'); rectangleTemplate = TemplateRectangles; load('Templates/TemplateTriangles.mat'); triangleTemplate = TemplateTriangles; %end windowTP=0; windowFN=0; windowFP=0; windowDCO=0; % (Needed after Week 3) pixelTP=0; pixelFN=0; pixelFP=0; pixelTN=0; files = ListFiles(directory); tic; for i=1:size(files,1), %for i=23:23, % Read file im = imread(strcat(directory,'/',files(i).name)); % Candidate Generation (pixel) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% pixelCandidates = CandidateGenerationPixel_Color(im, pixel_method, th); % Morphological Operations %%%%%%%%%%%%%%%%%%%%%%%%%%% % pixelCandidates = imopen(imclose(pixelCandidates,str),str2); pixelCandidates = imfill(pixelCandidates,'holes'); % subplot(1,2,1); % imshow(im); % subplot(1,2,2); % imshow(pixelCandidates*255); % Candidate Generation (window)%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% windowCandidates = CandidateGenerationWindow(im, pixelCandidates, window_method, decision_method); % Accumulate pixel performance of the current image %%%%%%%%%%%%%%%%% disp(i); pixelAnnotation = imread(strcat(directory, '/mask/mask.', files(i).name(1:size(files(i).name,2)-3), 'png'))>0; %To delete every pixel which are not in the window mask = zeros(size(pixelAnnotation)); for k = 1:size(windowCandidates,1) x1 = round(windowCandidates(k).x); y1 = round(windowCandidates(k).y); x2 = floor(windowCandidates(k).x+windowCandidates(k).w); y2 = floor(windowCandidates(k).y+windowCandidates(k).h); mask(y1:y2, x1:x2) = 1; end pixelAnnotation(~mask) = 0; [localPixelTP, localPixelFP, localPixelFN, localPixelTN] = PerformanceAccumulationPixel(pixelCandidates, pixelAnnotation); pixelTP = pixelTP + localPixelTP; pixelFP = pixelFP + localPixelFP; pixelFN = pixelFN + localPixelFN; pixelTN = pixelTN + localPixelTN; %Accumulate object performance of the current image %%%%%%%%%%%%%%%% (Needed after Week 3) windowAnnotations = LoadAnnotations(strcat(directory, '/gt/gt.', files(i).name(1:size(files(i).name,2)-3), 'txt'), pixelAnnotation, 1); [localWindowTP, localWindowFN, localWindowFP, localDCO] = PerformanceAccumulationWindow(windowCandidates, windowAnnotations, 1); windowTP = windowTP + localWindowTP; windowFN = windowFN + localWindowFN; windowFP = windowFP + localWindowFP; windowDCO = windowDCO + localDCO; end time = toc; time = time/size(files,1); % Plot performance evaluation [pixelPrecision, pixelAccuracy, pixelRecall, pixelFMeasure] = PerformanceEvaluationPixel(pixelTP, pixelFP, pixelFN, pixelTN); [windowPrecision, windowAccuracy, windowRecall, windowFMeasure] = PerformanceEvaluationWindow(windowTP, windowFN, windowFP); % Save performance to file f = [pixelPrecision, pixelAccuracy, pixelRecall, pixelFMeasure, pixelTP, pixelFP, pixelFN, time]; fid=fopen(filename,'a'); fprintf(fid,'%2.5f %2.5f %2.5f %2.5f %2.0f %2.0f %2.0f %2.5f \n', f); %fclose(fid); f = [windowPrecision, windowAccuracy, windowRecall, windowFMeasure, windowTP, windowFP, windowFN, time]; %fid=fopen(filename,'a'); fprintf(fid,'%2.5f %2.5f %2.5f %2.5f %2.0f %2.0f %2.0f %2.5f \n', f); fclose(fid); % [windowPrecision, windowAccuracy] %profile report %profile off % toc end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CandidateGeneration %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pixelCandidates] = CandidateGenerationPixel_Color(im, method, ~) switch method case 'col_enh' im= double(im); xR=im(:,:,1); xG=im(:,:,2); xB=im(:,:,3); fR_1=max(0,min(xR-xG,xR-xB)./(xR+xG+xB)); fR_2=max(0,min(xB-xG,xB-xR)./(xR+xG+xB)); fR_1 = fR_1 > 0.12; fR_2 = fR_2 > 0.12; pixelCandidates = fR_1 + fR_2; case 'ihls' [In1] = normalize_segmentation(im,'red'); [In2] = normalize_segmentation(im,'blue'); pixelCandidates = logical(In1 + In2); otherwise error('Incorrect window method defined'); end end function [windowCandidates] = CandidateGenerationWindow(im, pixelCandidates, window_method, decision_method) switch window_method case 'SegmentationCCL' %1. Connected components detection %1.1 Obtain the connected components and their number of pixels. [connected_components, num] = bwlabel(pixelCandidates, 8); %Generate the bounding box bb = regionprops(connected_components, 'BoundingBox'); %5. For each bounding box... candidates = []; numberOfCandidates = 1; windowCandidates = []; for indexBoundingBoxes=1:size(bb) %5.1 Obtain the properties (for each bounding box) crop = imcrop(pixelCandidates, bb(indexBoundingBoxes).BoundingBox); %Obtain the BB values. x = bb(indexBoundingBoxes).BoundingBox(1); y = bb(indexBoundingBoxes).BoundingBox(2); temp_w = bb(indexBoundingBoxes).BoundingBox(3); temp_h = bb(indexBoundingBoxes).BoundingBox(4); temp_fillingRatio = nnz(crop)/(size(crop,1) * size(crop,2)); %Store the candidates if temp_fillingRatio >= 0.2901 && temp_fillingRatio <= 0.9866 if temp_w >= 29.75 && temp_w <= 345.76 if temp_h >= 29.46 && temp_h <= 253.39 window = imcrop(pixelCandidates, [double(x) double(y) double(temp_w) double(temp_h)]); if DecideCandidatesWindow(window, decision_method) candidates(numberOfCandidates) = indexBoundingBoxes; numberOfCandidates = numberOfCandidates + 1; windowCandidates = [windowCandidates; struct('x',double(x),'y',double(y),'w',double(temp_w),'h',double(temp_h))]; end end end end end case 'SlidingWindow' m = 91; n = 91; fun = @decideWindow; C = nlfilter(pixelCandidates, [m n], fun); windowCandidates = MergeWindows(pixelCandidates, C, decision_method); otherwise error('Incorrect window method defined'); end end function [windowCandidates] = MergeWindows(pixelCandidates, C, decision_method) s = regionprops(C,'centroid'); centroids = cat(1, s.Centroid); windowCandidates = []; % Size of the sliding window, if dynamic then we should not % hardcode it w = 91; h = 91; for i = 1:size(centroids,1) %x = centroids(i,1)-4*45; %y = centroids(i,2)-4*45; x = centroids(i,1)-45; y = centroids(i,2)-45; window = imcrop(pixelCandidates, [double(x) double(y) double(w) double(h)]); if DecideCandidatesWindow(window, decision_method) windowCandidates = [windowCandidates; struct('x',double(x),'y',double(y),'w',double(w),'h',double(h))]; end end end %B4 Task 2 function [IsCandidate] = DecideCandidatesWindow(candidate, decision_method) % %%This function decides if a window contains a traffic signal or not by % using different template comparing methods % candidate: the window, in a struct form, that needs evaluation % decision_method: the decision method we are going to use % IsCandidate: 1 if it contains a signal, 0 if not IsCandidate = 0; % PLACEHOLDER VALUES % FOR EACH TEMPLATE, THE ADECUATE THRESHOLD AND THE SIZE OF THE MATRIX global circleTemplate; global givewayTemplate; global stopTemplate; global rectangleTemplate; global triangleTemplate; %thresholds = [30000 30000 30000 30000 30000]; nTemplates = 5; switch decision_method case 'grayscale' templates = cat(3,circleTemplate,givewayTemplate,stopTemplate,rectangleTemplate,triangleTemplate); % Simple grayscale substraction % For every template: i = 1; while i < nTemplates && (IsCandidate == 0) % n and m is the size of our template testing = imresize(candidate,[size(templates(:,:,i),1) size(templates(:,:,i),2)] ); testing = templates(:,:,i) - testing; IsCandidate = (sum(sum(testing)) < 50); % < thresholds(i)); i = i + 1; end case 'chamfer' % Chamfer distance model of each set type = cat(3,triangleTemplate,circleTemplate,rectangleTemplate,givewayTemplate); candidate = imresize(candidate,[size(type,1),size(type,2)]); i = 1; %M = inf; IsCandidate = 0; while(IsCandidate == 0 && i <= size(type,3)) T = edge(type(:,:,i),'canny'); B = edge(candidate,'canny'); %MASK D = bwdist(B); M = sum(sum(T*D)); i = i + 1; IsCandidate = (M < 15000000); end case 'corr' type = cat(3,triangleTemplate,circleTemplate,rectangleTemplate,givewayTemplate); candidate = imresize(candidate,[size(type,1),size(type,2)]); i = 1; IsCandidate = 0; while(IsCandidate == 0 & i <= size(type,3)) C=corr2(double(candidate),type(:,:,i)); i = i + 1; IsCandidate = (C > 0.38); end case 'HoughTransform' IsCandidate = 0; eIm = edge(candidate, 'canny'); [H,theta,rho] = hough(eIm); maxLines = 10; P = houghpeaks(H,maxLines,'threshold',ceil(0.7*max(H(:)))); if(P == 0) IsCandidate = 0; disp('P=0') else lines = houghlines(eIm,theta,rho,P,'FillGap',5,'MinLength',3); %Shape detection if (length(P) == maxLines) %(circen(1) < 100 && circen(2) < 100) if(size(candidate)>32) %Hough Circle Transform [accum, circen] = CircularHough_Grd(255*candidate,[0.45*min(size(candidate,1),size(candidate,2)) 0.5*min(size(candidate,1),size(candidate,2))]); if(isempty(circen)) IsCandidate = 0; else IsCandidate = 1; end else IsCandidate = 1; end else tolerance = 7; squarecondition = 0; trianglecondition = 0; for index = 1:size(lines,2) %If there are a min. of three peaks with ~0? or ~90?. Obj: square. if (abs(lines(index).theta) <= tolerance) ... || (abs(abs(lines(index).theta) - 90) <= tolerance) squarecondition = squarecondition + 1; end %If there are a min. of two peaks with ~25?. Obj: triangle. if (abs(abs(lines(index).theta) - 30) <= tolerance) trianglecondition = trianglecondition + 1; end end if squarecondition > 3 IsCandidate = 1; else if trianglecondition >= 2 IsCandidate = 1; end end end end otherwise error('Incorrect decision method defined'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Performance Evaluation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function PerformanceEvaluationROC(scores, labels, thresholdRange) % PerformanceEvaluationROC % ROC Curve with precision and accuracy roc = []; for t=thresholdRange, TP=0; FP=0; for i=1:size(scores,1), if scores(i) > t % scored positive if labels(i)==1 % labeled positive TP=TP+1; else % labeled negative FP=FP+1; end else % scored negative if labels(i)==1 % labeled positive FN = FN+1; else % labeled negative TN = TN+1; end end end precision = TP / (TP+FP+FN+TN); accuracy = TP / (TP+FN+FP); roc = [roc ; precision accuracy]; end plot(roc); end
github
sergiosanchoasensio/Traffic-sign-detection-and-recognition-master
colorspace_demo.m
.m
Traffic-sign-detection-and-recognition-master/Code/colorspace/colorspace_demo.m
6,856
utf_8
f7d66bc3e0e1bf1611fbd525c617323c
function colorspace_demo(Cmd) % Demo for colorspace.m - 3D visualizations of various color spaces % Pascal Getreuer 2006 if nargin == 0 % Create a figure with a drop-down menu figure('Color',[1,1,1]); h = uicontrol('Style','popup','Position',[15,10,90,21],... 'BackgroundColor',[1,1,1],'Value',2,... 'string',{'sRGB','Y''PbPr','HSV','HSL','L*a*b*','L*u*v*','L*ch'}); set(h,'Callback',sprintf('%s(get(%.20g,''Value''))',mfilename,h)); Cmd = 2; end % Plot a figure switch Cmd case 1 [x,y,z,Tri] = makeshape('Cube'); CData = [x,y,z]; myplot((x-0.5)*0.8,(y-0.5)*0.8,(z)*0.8,Tri,CData); coloraxis('R''',5,0.5*0.8); coloraxis('G''',6,0.5*0.8); coloraxis('B''',3); case 2 [x,y,z,Tri] = makeshape('Cylinder'); CData = colorspace('rgb<-ypbpr',[z,x/2,y/2]); myplot(x,y,0.8*z,Tri,CData); coloraxis('Y''',3); coloraxis('P_b',5,0.8); coloraxis('P_r',6,0.8); case 3 [x,y,z,Tri] = makeshape('Hexacone'); CData = colorspace('rgb<-hsv',[(pi+atan2(-y,-x))*180/pi,sqrt(x.^2+y.^2),z]); myplot(x,y,z,Tri,CData); coloraxis('H',1); coloraxis('S',2); coloraxis('V',3); case 4 [x,y,z,Tri] = makeshape('Double Hexacone'); CData = colorspace('rgb<-hsl',[(pi+atan2(-y,-x))*180/pi,sqrt(x.^2+y.^2),z]); myplot(x,y,2*z,Tri,CData); coloraxis('H',1); coloraxis('S',2); coloraxis('L',4); case 5 [x,y,z,Tri] = makeshape('Blobs'); CData = colorspace('rgb<-lab',[z*100,x*100,y*100]); myplot(x,y,2*z,Tri,CData); coloraxis('L*',4); coloraxis('a*',5,2); coloraxis('b*',6,2); case 6 [x,y,z,Tri] = makeshape('Blobs'); CData = colorspace('rgb<-luv',[z*100,x*125,y*125]); myplot(x,y,2*z,Tri,CData); coloraxis('L*',4); coloraxis('u*',5,2); coloraxis('v*',6,2); case 7 [x,y,z,Tri] = makeshape('Blobs'); CData = colorspace('rgb<-lab',[z*100,x*100,y*100]); myplot(x,y,2*z,Tri,CData); coloraxis('L*',4); coloraxis('c',2); coloraxis('h',1); end axis equal; axis off; pbaspect([1,1,1]); view(70,27); rotate3d on; return; function myplot(x,y,z,Tri,CData) % Plot a triangular mesh with color data cla; CData = min(max(CData,0),1); patch('Faces',Tri,'Vertices',[x,y,z],'FaceVertexCData',CData,... 'FaceColor','interp','EdgeColor','none'); hold on; return; function coloraxis(Name,Type,h) % Draw color axes as 3D objects FontSize = 14; switch Type case 1 set(text(-0.25,-1.3,1.1,Name),'FontWeight','bold',... 'FontSize',FontSize,'Color',[0,0,0]); t = linspace(0,pi*3/2,60); x = cos(t)*1.1; y = sin(t)*1.1; set(plot3(x,y,zeros(size(x)),'k-'),'LineWidth',2.5,'Color',[1,1,1]*0.8); x = [x,-0.1,0,-0.1]; y = [y,-1.05,-1.1,-1.15]; set(plot3(x,y,ones(size(x)),'k-'),'LineWidth',2.5); case 2 set(text(0,-0.6,0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]); set(plot3([-0.05,0,0.05,0,0],[-0.9,-1,-0.9,-1,0],[0,0,0,0,0],'k-'),'LineWidth',2.5); case 3 set(text(0,0.15,1.3,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]); set(plot3([0,0,0,0,0],[-0.05,0,0.05,0,0],[1.6,1.7,1.6,1.7,0],'k-'),'LineWidth',2.5); case 4 set(text(0,0.15,2.4,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]); set(plot3([0,0,0,0,0],[-0.05,0,0.05,0,0],[2.4,2.5,2.4,2.5,0],'k-'),'LineWidth',2.5); case 5 set(text(0.6,0,h+0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]); set(plot3([0.9,1,0.9,1,-1,-0.9,-1,-0.9],[-0.05,0,0.05,0,0,-0.05,0,0.05],... zeros(1,8)+h,'k-'),'LineWidth',2.5); case 6 set(text(0,0.6,h+0.15,Name),'FontWeight','bold','FontSize',FontSize,'Color',[0,0,0]); set(plot3([-0.05,0,0.05,0,0,-0.05,0,0.05],[0.9,1,0.9,1,-1,-0.9,-1,-0.9],... zeros(1,8)+h,'k-'),'LineWidth',2.5); end return; function [x,y,z,Tri] = makeshape(Shape) % Make a 3D shape: Shape = 'Cube', 'Cylinder', 'Cone', 'Double Cone', 'Blobs' % Cube N = 12; % Vertices per edge % Cylinder, Cone, Double Cone Nth = 25; % Vertices over angles, (Nth - 1) should be a multiple of 12 Nr = 4; % Vertices over radius Nz = 8; % Vertices over z-dimension switch lower(Shape) case 'cube' [u,v] = meshgrid(linspace(0,1,N),linspace(0,1,N)); u = u(:); v = v(:); x = [u;u;u;u;zeros(N^2,1);ones(N^2,1)]; y = [v;v;zeros(N^2,1);ones(N^2,1);v;v]; z = [zeros(N^2,1);ones(N^2,1);v;v;u;u]; Tri = trigrid(N,N); Tri = [Tri;N^2+Tri;2*N^2+Tri;3*N^2+Tri;4*N^2+Tri;5*N^2+Tri]; case 'cylinder' Nth = ceil(Nth*0.75); [u,v] = meshgrid(linspace(0,pi*3/2,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); x = cos(u(:)); y = sin(u(:)); z = v(:); [u,v] = meshgrid(linspace(0,pi*3/2,Nth),linspace(0,1,Nr)); Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);Nth*Nz+Nth*Nr+trigrid(Nth,Nr)]; x = [x;v(:).*cos(u(:));v(:).*cos(u(:))]; y = [y;v(:).*sin(u(:));v(:).*sin(u(:))]; z = [z;zeros(Nth*Nr,1);ones(Nth*Nr,1)]; [u,v] = meshgrid(linspace(0,1,Nr),linspace(0,1,Nz)); Tri = [Tri;Nth*Nz+2*Nth*Nr+trigrid(Nr,Nz);Nth*Nz+2*Nth*Nr+Nr*Nz+trigrid(Nr,Nz)]; x = [x;u(:);zeros(Nr*Nz,1)]; y = [y;zeros(Nr*Nz,1);-u(:)]; z = [z;v(:);v(:)]; case 'cone' [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); x = v(:).*cos(u(:)); y = v(:).*sin(u(:)); z = v(:); [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nr)); Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);]; x = [x;v(:).*cos(u(:));]; y = [y;v(:).*sin(u(:));]; z = [z;ones(Nth*Nr,1)]; case 'double cone' Nz = floor(Nz/2)*2+1; [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); r = 1 - abs(2*v(:) - 1); x = r.*cos(u(:)); y = r.*sin(u(:)); z = v(:); case 'hexacone' [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); r = 0.92./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3))); x = v(:).*cos(u(:)).*r(:); y = v(:).*sin(u(:)).*r(:); z = v(:); [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nr)); Tri = [Tri;Nth*Nz+trigrid(Nth,Nr);]; v = 0.92*v./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3))); x = [x;v(:).*cos(u(:));]; y = [y;v(:).*sin(u(:));]; z = [z;ones(Nth*Nr,1)]; case 'double hexacone' Nz = floor(Nz/2)*2+1; [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); r = 1 - abs(2*v - 1); r = 0.92*r./max(max(abs(cos(u)),abs(cos(u - pi/3))),abs(cos(u + pi/3))); x = r(:).*cos(u(:)); y = r(:).*sin(u(:)); z = v(:); case 'blobs' Nz = 47; [u,v] = meshgrid(linspace(0,2*pi,Nth),linspace(0,1,Nz)); Tri = trigrid(Nth,Nz); r = sin(v(:)*pi*3).^2.*(1 - 0.6*abs(2*v(:) - 1)); x = r.*cos(u(:)); y = r.*sin(u(:)); z = v(:); end return; function Tri = trigrid(Nu,Nv) % Construct the connectivity data for a grid of triangular patches i = (1:(Nu-1)*Nv-1).'; i(Nv:Nv:end) = []; Tri = [i,i+1,i+Nv;i+1,i+Nv+1,i+Nv]; return;
github
sergiosanchoasensio/Traffic-sign-detection-and-recognition-master
colorspace.m
.m
Traffic-sign-detection-and-recognition-master/Code/colorspace/colorspace.m
16,178
utf_8
2ca0aee9ae4d0f5c12a7028c45ef2b8d
function varargout = colorspace(Conversion,varargin) %COLORSPACE Transform a color image between color representations. % B = COLORSPACE(S,A) transforms the color representation of image A % where S is a string specifying the conversion. The input array A % should be a real full double array of size Mx3 or MxNx3. The output B % is the same size as A. % % S tells the source and destination color spaces, S = 'dest<-src', or % alternatively, S = 'src->dest'. Supported color spaces are % % 'RGB' sRGB IEC 61966-2-1 % 'YCbCr' Luma + Chroma ("digitized" version of Y'PbPr) % 'JPEG-YCbCr' Luma + Chroma space used in JFIF JPEG % 'YDbDr' SECAM Y'DbDr Luma + Chroma % 'YPbPr' Luma (ITU-R BT.601) + Chroma % 'YUV' NTSC PAL Y'UV Luma + Chroma % 'YIQ' NTSC Y'IQ Luma + Chroma % 'HSV' or 'HSB' Hue Saturation Value/Brightness % 'HSL' or 'HLS' Hue Saturation Luminance % 'HSI' Hue Saturation Intensity % 'XYZ' CIE 1931 XYZ % 'Lab' CIE 1976 L*a*b* (CIELAB) % 'Luv' CIE L*u*v* (CIELUV) % 'LCH' CIE L*C*H* (CIELCH) % 'CAT02 LMS' CIE CAT02 LMS % % All conversions assume 2 degree observer and D65 illuminant. % % Color space names are case insensitive and spaces are ignored. When % sRGB is the source or destination, it can be omitted. For example % 'yuv<-' is short for 'yuv<-rgb'. % % For sRGB, the values should be scaled between 0 and 1. Beware that % transformations generally do not constrain colors to be "in gamut." % Particularly, transforming from another space to sRGB may obtain % R'G'B' values outside of the [0,1] range. So the result should be % clamped to [0,1] before displaying: % image(min(max(B,0),1)); % Clamp B to [0,1] and display % % sRGB (Red Green Blue) is the (ITU-R BT.709 gamma-corrected) standard % red-green-blue representation of colors used in digital imaging. The % components should be scaled between 0 and 1. The space can be % visualized geometrically as a cube. % % Y'PbPr, Y'CbCr, Y'DbDr, Y'UV, and Y'IQ are related to sRGB by linear % transformations. These spaces separate a color into a grayscale % luminance component Y and two chroma components. The valid ranges of % the components depends on the space. % % HSV (Hue Saturation Value) is related to sRGB by % H = hexagonal hue angle (0 <= H < 360), % S = C/V (0 <= S <= 1), % V = max(R',G',B') (0 <= V <= 1), % where C = max(R',G',B') - min(R',G',B'). The hue angle H is computed on % a hexagon. The space is geometrically a hexagonal cone. % % HSL (Hue Saturation Lightness) is related to sRGB by % H = hexagonal hue angle (0 <= H < 360), % S = C/(1 - |2L-1|) (0 <= S <= 1), % L = (max(R',G',B') + min(R',G',B'))/2 (0 <= L <= 1), % where H and C are the same as in HSV. Geometrically, the space is a % double hexagonal cone. % % HSI (Hue Saturation Intensity) is related to sRGB by % H = polar hue angle (0 <= H < 360), % S = 1 - min(R',G',B')/I (0 <= S <= 1), % I = (R'+G'+B')/3 (0 <= I <= 1). % Unlike HSV and HSL, the hue angle H is computed on a circle rather than % a hexagon. % % CIE XYZ is related to sRGB by inverse gamma correction followed by a % linear transform. Other CIE color spaces are defined relative to XYZ. % % CIE L*a*b*, L*u*v*, and L*C*H* are nonlinear functions of XYZ. The L* % component is designed to match closely with human perception of % lightness. The other two components describe the chroma. % % CIE CAT02 LMS is the linear transformation of XYZ using the MCAT02 % chromatic adaptation matrix. The space is designed to model the % response of the three types of cones in the human eye, where L, M, S, % correspond respectively to red ("long"), green ("medium"), and blue % ("short"). % Pascal Getreuer 2005-2010 %%% Input parsing %%% if nargin < 2, error('Not enough input arguments.'); end [SrcSpace,DestSpace] = parse(Conversion); if nargin == 2 Image = varargin{1}; elseif nargin >= 3 Image = cat(3,varargin{:}); else error('Invalid number of input arguments.'); end FlipDims = (size(Image,3) == 1); if FlipDims, Image = permute(Image,[1,3,2]); end if ~isa(Image,'double'), Image = double(Image)/255; end if size(Image,3) ~= 3, error('Invalid input size.'); end SrcT = gettransform(SrcSpace); DestT = gettransform(DestSpace); if ~ischar(SrcT) && ~ischar(DestT) % Both source and destination transforms are affine, so they % can be composed into one affine operation T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)]; Temp = zeros(size(Image)); Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); Image = Temp; elseif ~ischar(DestT) Image = rgb(Image,SrcSpace); Temp = zeros(size(Image)); Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10); Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11); Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12); Image = Temp; else Image = feval(DestT,Image,SrcSpace); end %%% Output format %%% if nargout > 1 varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)}; else if FlipDims, Image = permute(Image,[1,3,2]); end varargout = {Image}; end return; function [SrcSpace,DestSpace] = parse(Str) % Parse conversion argument if ischar(Str) Str = lower(strrep(strrep(Str,'-',''),'=','')); k = find(Str == '>'); if length(k) == 1 % Interpret the form 'src->dest' SrcSpace = Str(1:k-1); DestSpace = Str(k+1:end); else k = find(Str == '<'); if length(k) == 1 % Interpret the form 'dest<-src' DestSpace = Str(1:k-1); SrcSpace = Str(k+1:end); else error(['Invalid conversion, ''',Str,'''.']); end end SrcSpace = alias(SrcSpace); DestSpace = alias(DestSpace); else SrcSpace = 1; % No source pre-transform DestSpace = Conversion; if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end end return; function Space = alias(Space) Space = strrep(strrep(Space,'cie',''),' ',''); if isempty(Space) Space = 'rgb'; end switch Space case {'ycbcr','ycc'} Space = 'ycbcr'; case {'hsv','hsb'} Space = 'hsv'; case {'hsl','hsi','hls'} Space = 'hsl'; case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'} return; end return; function T = gettransform(Space) % Get a colorspace transform: either a matrix describing an affine transform, % or a string referring to a conversion subroutine switch Space case 'ypbpr' T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0]; case 'yuv' % sRGB to NTSC/PAL YUV % Wikipedia: http://en.wikipedia.org/wiki/YUV T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0]; case 'ydbdr' % sRGB to SECAM YDbDr % Wikipedia: http://en.wikipedia.org/wiki/YDbDr T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0]; case 'yiq' % sRGB in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591]; % Wikipedia: http://en.wikipedia.org/wiki/YIQ T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0]; case 'ycbcr' % sRGB (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr % Wikipedia: http://en.wikipedia.org/wiki/YCbCr % Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128]; case 'jpegycbcr' % Wikipedia: http://en.wikipedia.org/wiki/YCbCr T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255; case {'rgb','xyz','hsv','hsl','lab','luv','lch','cat02lms'} T = Space; otherwise error(['Unknown color space, ''',Space,'''.']); end return; function Image = rgb(Image,SrcSpace) % Convert to sRGB from 'SrcSpace' switch SrcSpace case 'rgb' return; case 'hsv' % Convert HSV to sRGB Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1)); case 'hsl' % Convert HSL to sRGB L = Image(:,:,3); Delta = Image(:,:,2).*min(L,1-L); Image = huetorgb(L-Delta,L+Delta,Image(:,:,1)); case {'xyz','lab','luv','lch','cat02lms'} % Convert to CIE XYZ Image = xyz(Image,SrcSpace); % Convert XYZ to RGB T = [3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]; R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B % Desaturate and rescale to constrain resulting RGB values to [0,1] AddWhite = -min(min(min(R,G),B),0); R = R + AddWhite; G = G + AddWhite; B = B + AddWhite; % Apply gamma correction to convert linear RGB to sRGB Image(:,:,1) = gammacorrection(R); % R' Image(:,:,2) = gammacorrection(G); % G' Image(:,:,3) = gammacorrection(B); % B' otherwise % Conversion is through an affine transform T = gettransform(SrcSpace); temp = inv(T(:,1:3)); T = [temp,-temp*T(:,4)]; R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10); G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11); B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12); Image(:,:,1) = R; Image(:,:,2) = G; Image(:,:,3) = B; end % Clip to [0,1] Image = min(max(Image,0),1); return; function Image = xyz(Image,SrcSpace) % Convert to CIE XYZ from 'SrcSpace' WhitePoint = [0.950456,1,1.088754]; switch SrcSpace case 'xyz' return; case 'luv' % Convert CIE L*uv to XYZ WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); L = Image(:,:,1); Y = (L + 16)/116; Y = invf(Y)*WhitePoint(2); U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU; V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV; Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X Image(:,:,2) = Y; % Y Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z case {'lab','lch'} Image = lab(Image,SrcSpace); % Convert CIE L*ab to XYZ fY = (Image(:,:,1) + 16)/116; fX = fY + Image(:,:,2)/500; fZ = fY - Image(:,:,3)/200; Image(:,:,1) = WhitePoint(1)*invf(fX); % X Image(:,:,2) = WhitePoint(2)*invf(fY); % Y Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z case 'cat02lms' % Convert CAT02 LMS to XYZ T = inv([0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]); L = Image(:,:,1); M = Image(:,:,2); S = Image(:,:,3); Image(:,:,1) = T(1)*L + T(4)*M + T(7)*S; % X Image(:,:,2) = T(2)*L + T(5)*M + T(8)*S; % Y Image(:,:,3) = T(3)*L + T(6)*M + T(9)*S; % Z otherwise % Convert from some gamma-corrected space % Convert to sRGB Image = rgb(Image,SrcSpace); % Undo gamma correction R = invgammacorrection(Image(:,:,1)); G = invgammacorrection(Image(:,:,2)); B = invgammacorrection(Image(:,:,3)); % Convert RGB to XYZ T = inv([3.2406, -1.5372, -0.4986; -0.9689, 1.8758, 0.0415; 0.0557, -0.2040, 1.057]); Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z end return; function Image = hsv(Image,SrcSpace) % Convert to HSV Image = rgb(Image,SrcSpace); V = max(Image,[],3); S = (V - min(Image,[],3))./(V + (V == 0)); Image(:,:,1) = rgbtohue(Image); Image(:,:,2) = S; Image(:,:,3) = V; return; function Image = hsl(Image,SrcSpace) % Convert to HSL switch SrcSpace case 'hsv' % Convert HSV to HSL MaxVal = Image(:,:,3); MinVal = (1 - Image(:,:,2)).*MaxVal; L = 0.5*(MaxVal + MinVal); temp = min(L,1-L); Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); Image(:,:,3) = L; otherwise Image = rgb(Image,SrcSpace); % Convert to sRGB % Convert sRGB to HSL MinVal = min(Image,[],3); MaxVal = max(Image,[],3); L = 0.5*(MaxVal + MinVal); temp = min(L,1-L); S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0)); Image(:,:,1) = rgbtohue(Image); Image(:,:,2) = S; Image(:,:,3) = L; end return; function Image = lab(Image,SrcSpace) % Convert to CIE L*a*b* (CIELAB) WhitePoint = [0.950456,1,1.088754]; switch SrcSpace case 'lab' return; case 'lch' % Convert CIE L*CH to CIE L*ab C = Image(:,:,2); Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a* Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b* otherwise Image = xyz(Image,SrcSpace); % Convert to XYZ % Convert XYZ to CIE L*a*b* X = Image(:,:,1)/WhitePoint(1); Y = Image(:,:,2)/WhitePoint(2); Z = Image(:,:,3)/WhitePoint(3); fX = f(X); fY = f(Y); fZ = f(Z); Image(:,:,1) = 116*fY - 16; % L* Image(:,:,2) = 500*(fX - fY); % a* Image(:,:,3) = 200*(fY - fZ); % b* end return; function Image = luv(Image,SrcSpace) % Convert to CIE L*u*v* (CIELUV) WhitePoint = [0.950456,1,1.088754]; WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3)); Image = xyz(Image,SrcSpace); % Convert to XYZ Denom = Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3); U = (4*Image(:,:,1))./(Denom + (Denom == 0)); V = (9*Image(:,:,2))./(Denom + (Denom == 0)); Y = Image(:,:,2)/WhitePoint(2); L = 116*f(Y) - 16; Image(:,:,1) = L; % L* Image(:,:,2) = 13*L.*(U - WhitePointU); % u* Image(:,:,3) = 13*L.*(V - WhitePointV); % v* return; function Image = lch(Image,SrcSpace) % Convert to CIE L*ch Image = lab(Image,SrcSpace); % Convert to CIE L*ab H = atan2(Image(:,:,3),Image(:,:,2)); H = H*180/pi + 360*(H < 0); Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C Image(:,:,3) = H; % H return; function Image = cat02lms(Image,SrcSpace) % Convert to CAT02 LMS Image = xyz(Image,SrcSpace); T = [0.7328, 0.4296, -0.1624;-0.7036, 1.6975, 0.0061; 0.0030, 0.0136, 0.9834]; X = Image(:,:,1); Y = Image(:,:,2); Z = Image(:,:,3); Image(:,:,1) = T(1)*X + T(4)*Y + T(7)*Z; % L Image(:,:,2) = T(2)*X + T(5)*Y + T(8)*Z; % M Image(:,:,3) = T(3)*X + T(6)*Y + T(9)*Z; % S return; function Image = huetorgb(m0,m2,H) % Convert HSV or HSL hue to RGB N = size(H); H = min(max(H(:),0),360)/60; m0 = m0(:); m2 = m2(:); F = H - round(H/2)*2; M = [m0, m0 + (m2-m0).*abs(F), m2]; Num = length(m0); j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num; k = floor(H) + 1; Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]); return; function H = rgbtohue(Image) % Convert RGB to HSV or HSL hue [M,i] = sort(Image,3); i = i(:,:,3); Delta = M(:,:,3) - M(:,:,1); Delta = Delta + (Delta == 0); R = Image(:,:,1); G = Image(:,:,2); B = Image(:,:,3); H = zeros(size(R)); k = (i == 1); H(k) = (G(k) - B(k))./Delta(k); k = (i == 2); H(k) = 2 + (B(k) - R(k))./Delta(k); k = (i == 3); H(k) = 4 + (R(k) - G(k))./Delta(k); H = 60*H + 360*(H < 0); H(Delta == 0) = nan; return; function Rp = gammacorrection(R) Rp = zeros(size(R)); i = (R <= 0.0031306684425005883); Rp(i) = 12.92*R(i); Rp(~i) = real(1.055*R(~i).^0.416666666666666667 - 0.055); return; function R = invgammacorrection(Rp) R = zeros(size(Rp)); i = (Rp <= 0.0404482362771076); R(i) = Rp(i)/12.92; R(~i) = real(((Rp(~i) + 0.055)/1.055).^2.4); return; function fY = f(Y) fY = real(Y.^(1/3)); i = (Y < 0.008856); fY(i) = Y(i)*(841/108) + (4/29); return; function Y = invf(fY) Y = fY.^3; i = (Y < 0.008856); Y(i) = (fY(i) - 4/29)*(108/841); return;
github
rrahuldev/ExportMDF-master
expMDF.m
.m
ExportMDF-master/expMDF.m
9,217
utf_8
488f876b54f99d8b5630ac6220d7aee9
% Write data to MDA dat file % inputs: % 1- Data in table format % 2 - filename to write to *.dat % % usage: expMDF(dataTable, fileoutname) % Author : Rahul Rajampeta % Date: April 15, 2016 function expMDF(dataTable, fileoutname) %% create the fid to write fid = fopen(fileoutname,'W'); %% pass the table data varNames = getVariableNames(dataTable); varUnits = getTableUnits(dataTable); numChannels = length(varNames); numSamples = height(dataTable); rateSample = 0; % required for virtual signal only. %% Define locations for each block linkID = 0; % DO NOT CHANGE THIS linkHD = 64; % DO NOT CHANGE THIS linkCC = 300; blocksize_cc = 63; % for linear format of data 63 bytes padd_cc = 2; linkCN = linkCC + numChannels*(blocksize_cc+padd_cc); blocksize_cn = 228; % constant padd_cn = 2; linkCG = linkCN + numChannels*(blocksize_cn+padd_cn); linkDG = linkCG + 50; % 26+padding linkDT = linkDG + 50; %28 + padding % NOTE: dump empty characters untill linkDT otherwise fseek wont move to % desired position to write to fwrite(fid, repmat(char(0),1,linkDT), 'char'); %% write ID block writeIDBlock(fid, linkID); %% write HD block writeHDBlock(fid, linkHD, linkDG); %% write DG block - assume only one DG writeDGBlock(fid, linkDG, linkCG, linkDT); %% write CG block - assume only one CG writeCGBlock(fid, linkCG, linkCN, numChannels, numSamples); %% write CC/CN blocks for vars = 1 : numChannels writeCCBlock(fid, linkCC, varUnits{vars}); nextCN = linkCN+blocksize_cn+padd_cn; writeCNBlock(fid, linkCN, linkCC, nextCN, varNames{vars}, vars, rateSample, vars == numChannels); linkCC = linkCC+blocksize_cc+padd_cc; linkCN = linkCN+blocksize_cn+padd_cn; end %% and write DTblock writeDTBlock(fid, linkDT, dataTable); fclose(fid); end %% ID block def % dont change this function writeIDBlock(fid, offset) fseek(fid,offset,'bof'); fwrite(fid,'MDF 3.00 TGT 15.0', 'char'); fwrite(fid,0,'uint16'); fwrite(fid,0,'uint16'); fwrite(fid,300,'uint16'); fwrite(fid,0,'uint16'); fwrite(fid,repmat(char(0),1,28),'char'); fwrite(fid,0,'uint16'); fwrite(fid,0,'uint16'); % ftell(fid) end %% HD block def function writeHDBlock(fid, offset, linkDG) blocksize = 164; fseek(fid,offset,'bof'); % file pointer always to 64 for HD fwrite(fid,char('HD'),'char'); fwrite(fid,blocksize,'uint16'); fwrite(fid,linkDG,'uint32'); % pointer to DG block fwrite(fid,0,'uint32'); % pointer to TX fwrite(fid,0,'uint32'); %pointer to PR fwrite(fid,1,'uint16'); % number of DG BLOCKS (assume only one to write to) fwrite(fid,datestr(now,'dd:mm:yyyy'),'char'); % datestring fwrite(fid,datestr(now,'HH:MM:SS'),'char'); % timestring username = getenv('USERNAME'); fwrite(fid,username(1:min(length(username),31)), 'char'); % author fseek(fid,32-length(username),0); % fill the rest 32bytes with null fwrite(fid,repmat(char(' '),1,32),'char'); %organisation name fwrite(fid,repmat(char(' '),1,32),'char'); % project name fwrite(fid,repmat(char(' '),1,32),'char'); % vehicle/dyno name end %% DG block def function writeDGBlock(fid, offset, linkCG, linkDT) %assume only one DG block to write blocksize = 28; fseek(fid,offset,'bof'); fwrite(fid,char('DG'),'2*char'); fwrite(fid,blocksize,'uint16'); %block size fwrite(fid,0,'uint32'); %skip next DG fwrite(fid,linkCG,'uint32'); % CG link fwrite(fid,0,'uint32'); % skip trigger block TR fwrite(fid,linkDT,'uint32'); % Data DR link fwrite(fid,1,'uint16'); % assume only one CG block fwrite(fid,0,'uint16'); % assume zero recordIDs fwrite(fid,0,'uint32'); %reserved if blocksize ~= (ftell(fid)-offset) disp(['blocksize error DG']); end end %% CG block def function writeCGBlock(fid, offset, linkCN, numChannels, numSamples) %assume only one CG block to write blocksize = 26; fseek(fid,offset,'bof'); fwrite(fid,char('CG'),'2*char'); fwrite(fid,blocksize,'uint16'); %block size fwrite(fid,0,'uint32'); %skip next CG fwrite(fid,linkCN,'uint32'); %link to CN block fwrite(fid,0,'uint32'); %skip TX block fwrite(fid,2,'uint16'); %recordID fwrite(fid,uint16(numChannels),'uint16'); % number of channels fwrite(fid,uint16(numChannels*4),'uint16'); % record size (number of channels*(single)=32bits=4bytes) fwrite(fid,uint32(numSamples),'uint32'); %number of samples if blocksize ~= (ftell(fid)-offset) disp(['blocksize error CG']); end end %% CN block def function writeCNBlock(fid, offset, linkCC, nextLinkCN, signalName, numVar, rateSample, lastVar) if lastVar nextLinkCN = 0; end blocksize = 228; % calculate start offset with byte offset % if start bit is more than 16 bytes, use additional byte offset start_bit_raw = 32*(numVar-1); if (start_bit_raw <= 2^16-1) start_offset = start_bit_raw; add_byte_offset = 0; else start_offset = mod(start_bit_raw, 8); add_byte_offset = floor(start_bit_raw/8); end fseek(fid,offset,'bof'); fwrite(fid,'CN','char'); fwrite(fid,blocksize,'uint16'); %block size fwrite(fid,nextLinkCN,'uint32'); % link to nextCN fwrite(fid,linkCC,'uint32'); % link to CC block fwrite(fid,0,'uint32'); % link to CE block fwrite(fid,0,'uint32'); % link to CD block fwrite(fid,0,'uint32'); % link to TX block if strcmp(signalName,'time') fwrite(fid,1,'uint16'); %channel type else fwrite(fid,0,'uint16'); end fwrite(fid,signalName(1:min(length(signalName),31)), 'char'); fseek(fid,32-length(signalName),0); % fill the rest 32bytes with null fwrite(fid,'simulink output data','char'); fseek(fid,128-length('simulink output data'),0); % fill the rest 128bytes with null fwrite(fid,start_offset,'uint16'); %start offset fwrite(fid,32,'uint16'); %num of bits fwrite(fid,2,'uint16'); % single format (4bytes) fwrite(fid,0,'uint16'); % value range valid fwrite(fid,0,'double'); % min signal value fwrite(fid,0,'double'); % max signal value fwrite(fid,rateSample,'double'); % sampling rate fwrite(fid,0,'uint32'); %skip TX block fwrite(fid,0,'uint32'); %skip TX block fwrite(fid,add_byte_offset,'uint16'); % additional byte offset end %% CC block def function writeCCBlock(fid, offset, units) % units modification - limit to 20 with trailing zeros units = units(1:min(19,length(units))); units = [units repmat(char(0),1,20-length(units))]; blocksize = 62; fseek(fid,offset,'bof'); fwrite(fid,'CC','char'); fwrite(fid,blocksize,'uint16'); %block size fwrite(fid,0,'uint16'); % value range valid fwrite(fid,0,'double'); % min signal value fwrite(fid,0,'double'); % max signal value fwrite(fid,units,'char'); % units of the signal fwrite(fid,0,'uint16'); % conversion type - linear fwrite(fid,2,'uint16'); % number of parameters fwrite(fid,0,'double'); % P1 fwrite(fid,1,'double'); % P2 end %% Data block - write row-wise function writeDTBlock(fid, offset, dataTable) fseek(fid,offset,'bof'); % for row = 1:height(dataTable) % fwrite(fid,dataTable{row,:},'single'); % end dataTableRow = reshape(dataTable{:,:}', 1, []); fwrite(fid,dataTableRow, 'single'); end %% Fix variable names function varnames = getVariableNames(dataTable) % variable names should conform to % 1 - no space allowed : replace with __ % 2 - length should be less than 31 chars % 3 - unique name for each variables varnames = dataTable.Properties.VariableNames; % check if space exists in names varnames = strrep(varnames, ' ','_'); % check more than 31 chars names flg_longnames = cellfun(@(x) length(x)>31, varnames, 'UniformOutput', false); flg_longnames = [flg_longnames{:}]'; % convert cell to logical array % then truncate in between; use rolling 31 chars that produce unique names if any(flg_longnames) newvarnames = varnames; longnames = varnames(flg_longnames); shift_idx=[0:1:14 -1:-1:-14]; i=1; while ((length(unique(newvarnames)) ~= length(newvarnames) || i==1) && i<= length(shift_idx)) idx = shift_idx(i); newlongnames = cellfun(@(x) [x(1:15-idx) '_' x(end-14-idx:end)], longnames, 'UniformOutput', false); newvarnames(flg_longnames) = newlongnames; i=i+1; end if (length(unique(newvarnames)) ~= length(newvarnames) && i > length(shift_idx)) error('Try to minimize the signal names to less than 31 chars'); else varnames = newvarnames; end end % convert ls/rs to brackets varnames = strrep(varnames, '_ls_','['); varnames = strrep(varnames, '_rs_',']'); end %% DataTable units function units = getTableUnits(dataTable) units = dataTable.Properties.VariableUnits; % if no units are set to either of the column if isempty(units) % set empty units to first column, it forces empty units to all columns dataTable.Properties.VariableUnits{1} = ''; units = dataTable.Properties.VariableUnits; end end
github
rrahuldev/ExportMDF-master
mat2dat.m
.m
ExportMDF-master/mat2dat.m
10,624
utf_8
7fe982ffaccd4856933b094bdb62e07d
function mat2dat(varargin) % The script is invoked two ways % 1: with no arguments to the script, in which case, the user selects the % one or more mat files to convert to dat file format. The output is the % same name as matfile but appended with "_expMDF.dat" % % 2: inline with other scripts or model where the syntax below is followed. % usage: MAT2DAT(logsout, 'test_data.dat') % params: % logsout: Simulink.SimulationData.Dataset type data stored via simulation output % 'test_data.dat' : filename to convert data to dat % returns: % 'test_data.dat': data converted to MDF format % simulation model call; assume logsout variable in the workspace % Author: Rahul Rajampeta % Updated: April 11, 2019 disp(' '); %% check matlab version : currently supports 8.2 and higher if verLessThan('matlab', '8.2') disp(repmat(char('-'), 1, 90)); disp(' Currently, this script supports only version 8.2 (R2013b) and higher '); disp(repmat(char('-'), 1, 90)); disp(' '); return; end %% check invoke method of the script switch nargin case 0 % Select mat file with variables stored as timeseries % UI for file selection [FileName,PathName,~] = uigetfile(fullfile(pwd,'*.mat'), 'Select the MAT file(s). Use Ctrl key for selecting multiple files','MultiSelect','on'); % check one or multiple files selected if isa(FileName, 'char') % only one file selected % convert to cell format FileName = {FileName}; elseif ~isa(FileName, 'cell') % no file selected - end the function call return end % load each file and create dat file for each for f = 1: length(FileName) disp('');disp(['Loading file -- "', FileName{f},'"']); raw = load(strcat(PathName,FileName{f})); writeDatFile(raw, FileName{f}, PathName); end case 2 % usage: mat2dat(logsout, 'test_data.dat') % params: % logsout: Simulink.SimulationData.Dataset type data stored via simulation output % 'test_data.dat' : filename to convert data to dat % returns: % 'test_data.dat': data converted to MDF format % simulation model call; assume logsout variable in the workspace dataStream = varargin{1}; filename=varargin{2}; if isa(dataStream, 'Simulink.SimulationData.Dataset') rawTSData = classSimDataset(dataStream); writeDatFile(rawTSData, filename, strcat(pwd,'\')); else disp('ERROR: Pass Simulation dataset values only') end end end function writeDatFile(rawStructure, FileName, PathName) %% pass raw structure to preprocessing dataStruct = classStruct(rawStructure); try dataTable = struct2table(dataStruct); catch Error disp(' ') disp(' *** ERROR IN MAT FILE *** '); disp(Error.message); disp(' --> Check MAT file, all signals must have same length'); return end %% Writing to a file if strcmpi(FileName(end-2:end), 'dat') fileoutname = FileName; else fileoutname = strcat(FileName(1:end-4),'_expMDF.dat'); end disp(' ');disp(['Writing data to dat file -- "' fileoutname '"']) ; fileoutname = strcat(PathName,fileoutname); expMDF(dataTable, fileoutname); disp(' '); disp(['Formatted data written to ',fileoutname]); disp(repmat(char('-'), 1, 50)); disp(' '); end %% converts timeseries to structure function dout = classStruct(din) dout =struct; names = fieldnames(din); for n = 1:length(names) data_inside = eval(strcat('din.',names{n})); if isa(data_inside, 'timeseries') if ~isfield(dout,'time') dout.time = single(data_inside.Time); end varout = strcat('dout.',names{n}); eval([ varout '= single(data_inside.Data);']); elseif isstruct(data_inside) d = classStruct(data_inside); name_d = fieldnames(d); for nd = 1:length(name_d) varout = strcat('dout.',name_d{nd}); varval = eval(strcat('d.',name_d{nd})); eval([ varout '= varval;']); end elseif isa(data_inside, 'Simulink.SimulationData.Dataset') dset = classSimDataset(data_inside); d = classStruct(dset); name_d = fieldnames(d); for nd = 1:length(name_d) varout = strcat('dout.',name_d{nd}); varval = eval(strcat('d.',name_d{nd})); eval([ varout '= varval;']); end elseif isfloat(data_inside) if ~isfield(dout,'time') dout.time = single([0:1:length(data_inside)-1]'); end varout = strcat('dout.',names{n}); eval([ varout '= single(data_inside);']); end end end %% converts Simulation Dataset to structure-timeseries function allSignals = classSimDataset(dataStream) % todo check if data is fixed step or variable step % todo check isnan or isinf % for fixed or variable step, timestamp should be the same % 1: extract all the signals from logsout allSignals = struct; for var = 1:numElements(dataStream) dataSignal = dataStream.getElement(var); % check if signal value type is timeseries (i.e. signals or mux) if isobject(dataSignal.Values) allSignals = UpdateSignalsList(allSignals, dataSignal); elseif isstruct(dataSignal.Values) % it must be a bus type signal fnames = fieldnames(dataSignal.Values); tempSignal = dataSignal; for i=1:length(fnames) eval(['tempSignal.Values = dataSignal.Values.' fnames{i} ';']); tempSignal.Name = [dataSignal.Name '_' tempSignal.Values.Name]; tempSignal.Values.Name = tempSignal.Name; allSignals = UpdateSignalsList(allSignals, tempSignal); end else % unknown type % todo end end % 2: get the common timestamp for all the signals commonTime = []; signalNames = fieldnames(allSignals); for i=1:length(signalNames) tempTS = eval(['allSignals.' signalNames{i}]); if tempTS.TimeInfo.Length > length(commonTime) commonTime = tempTS.Time; end end % first element the common timestamp is more than 2s, then set warning if isempty(commonTime(1) > 2) warning('No Uniform TimeVector Found: Try logging atleast one signal without the enable/tigger/function subsystem'); end % 3: fix the non-uniform signals helptext = true; promptinput = true; for i=1:length(signalNames) tempTS = eval(['allSignals.' signalNames{i}]); if (tempTS.TimeInfo.Length ~= length(commonTime)) % display one time help text if (helptext) helptext = false; fprintf('\n'); disp('---------------------------------------------------------------------------'); fprintf('Some signals are enable/function/trigger subsystem signals and have missing values,\nchoose one of the option below for respective signals - \n'); fprintf('\t "z" - fill with zeros (default)\n') fprintf('\t "h" - hold last sample value \n') fprintf('\t "i" - interpolate in between\n') fprintf('\t "za" - fill with zeros and use this option for rest of the signals\n') fprintf('\t "ha" - hold last sample values and use this option for rest of the signals\n') fprintf('\t "ia" - interpolate in between and use this option for rest of the signals\n') disp('---------------------------------------------------------------------------'); fprintf('\n'); end % prompt for fill type, default zero if (promptinput) commandwindow; reply = input([tempTS.Name ' - z/h/i/za/ha/ia [z]:'],'s'); % any other input default to zero if (isempty(reply) ||... isempty(cell2mat(strfind({'z','h','i','za','ha','ia'}, lower(reply))))) reply = 'z'; end % use same option for rest of the signals if length(reply)>1 promptinput = false; end end % signal processing [~, idx] = intersect(commonTime, tempTS.Time, 'stable'); newData = zeros(size(commonTime)); if strcmpi(reply(1),'z') % fill missing values with zeros newData(idx) = tempTS.Data; if ~promptinput fprintf([tempTS.Name ': zero fill\n']); end elseif strcmpi(reply(1),'h') % hold last samples newData(idx) = tempTS.Data - [0;tempTS.Data(1:end-1)]; newData = cumsum(newData); if ~promptinput fprintf([tempTS.Name ': hold last value\n']); end elseif strcmpi(reply(1),'i') % interpolate missing values if (tempTS.TimeInfo.Length > 2) newData = interp1(tempTS.Time, tempTS.Data, commonTime, 'linear','extrap'); if ~promptinput fprintf([tempTS.Name ': interpolate in between\n']); end else fprintf('\n'); fprintf(['"' tempTS.Name '" - signal has less than 3 samples to interpolate, defaulting to zero fill\n']); newData(idx) = tempTS.Data; end end newTS = timeseries(newData, commonTime, 'name', tempTS.Name); eval(['allSignals.' tempTS.Name ' = newTS;']); end end end function allSignals = UpdateSignalsList(allSignals, varSignal) % check vectors vs signal if (size(varSignal.Values.Data, 2) == 1) % only signal % fix time to round off to 5 digits varSignal.Values.Time = round(varSignal.Values.Time*1e5)/1e5; eval(['allSignals.' varSignal.Name ' = varSignal.Values;']); else % vector tempTS = varSignal.Values; % fix time to round off to 5 digits tempTS.Time = round(tempTS.Time*1e5)/1e5; for i = 1:size(varSignal.Values.Data, 2) tempTS.Data = varSignal.Values.Data(:,i); tempTS.Name = [varSignal.Values.Name '_ls_' num2str(i-1) '_rs_']; eval(['allSignals.' tempTS.Name ' = tempTS;']); end end end
github
jdonley/CoherenceBasedSourceCounter-master
tightPlots.m
.m
CoherenceBasedSourceCounter-master/tightPlots.m
7,369
utf_8
c971688a6827a46fd28cfc0c4b759ec9
% Copyright (c) 2015, Theodoros Michelis % Copyright (c) 2016, Pekka Kumpulainen % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. function ha = tightPlots(Nh, Nw, w, AR, gap, marg_h, marg_w, units) % Theodoros Michelis, 15 February 2015 % TUDelft, Aerospace Engineering, Aerodynamics % [email protected] % % ------------------------------------------------------------------------- % D E S C R I P T I O N: % tightPlots is a function that allows making single plots or subplots with % controlled size and margins. The desired (page) width, aspect ratio and % margins must be input, with which the appropriate height is calculated. % % This workflow allows for all figures to maintain font formatting when % they are inserted into a document/publication. Adjust the width to match % the document page width and fix the font size. Narrow plots can then be % created by setting wide side margins. % % The function additionally creates a bounding box equal to the figure size % on the screen. As a result, what is seen on the monitor can be printed in % both raster (.png) and vector (.eps, .pdf) formats with the same result. % % tightPlots has been influenced by the "tight_subplot" function of % Pekka Kumpulainen, hence, parts of the code and parameter names were kept % the same. % % Thanks for using tightPlots!!! % % I N P U T: % ha = tightPlots(Nh, Nw, w, AR, gap, marg_h, marg_w, units) % Nh: Number of axes in the vertical direction % Nw: Number of axes in the horizontal direction % w: Figure width in appropriate units (see units) % AR: [w h] Axis aspect ratio % gap: [gap] Gap between axes in appropriate units % or [gap_h gap_w] for different gaps in height and width % marg_h: [mh] Bottom and top margins in appropriate units % or [lower upper] for different lower and upper margins % marg_w: [mw] Left and right margind in appropriate units % or [left right] for different left and right margins % units: Centimeters, inches, points or pixels. The function is not % intended to work with normalised units. % % I M P O R T A N T: % All dimensions are converted into 'points' within the function. This is % particularly necessary when the input unit is 'pixels', which cannot be % defined on paper! It is also necessary for versions of MATLAB 2014b and % above as the rendering settings have been changed. Thus, when printing in % raster formats, the resolution is controlled through the dpi setting % while saving (see examples further down). % % S A V I N G F I G U R E: % In order to save the figure use the print command as shown in the % examples below. The '-loose' option ensures that the figure bounding box % is not clipped while exporting to a vector format. For MATLAB versions of % 2014b and above, do not forget to set the renderer to '-painters' as the % default has been switched to '-opengl'. % % E X A M P L E 1: % ha = tightPlots(2, 2, 15, [2 1], [0.4 0.4], [0.6 0.7], [0.8 0.3], 'centimeters'); % f = [1 5 10 15]; x = 0:0.05:10; % for i = 1:length(f) % y = sin(f(i) * x); % axes(ha(i)); plot(x, y) % end % set(ha(1:4), 'fontname', 'Times', 'fontsize', 10) % set(ha(1:2), 'xticklabel', ''); % set([ha(2) ha(4)], 'yticklabel', ''); % axes(ha(1)); title('Title 1'); % axes(ha(2)); title('Title 2'); % % print(gcf, 'Example1.png', '-dpng', '-r200', '-opengl'); % print(gcf, 'Example1.eps', '-depsc2', '-painters', '-loose'); % print(gcf, 'Example1.pdf', '-dpdf', '-painters', '-loose'); % % E X A M P L E 2: % ha = tightPlots(1, 2, 15, [1 1], 0.25, 0.25, 0.25, 'centimeters'); % f = [1 5]; x = 0:0.05:10; % for i = 1:length(f) % y = sin(f(i) * x); % axes(ha(i)); plot(x, y) % end % set(ha(1:2), 'XtickLabel', '', 'YtickLabel', '') % % print(gcf, 'Example2.png', '-dpng', '-r200', '-opengl'); % print(gcf, 'Example2.eps', '-depsc2', '-painters', '-loose'); % print(gcf, 'Example2.pdf', '-dpdf', '-painters', '-loose'); % ------------------------------------------------------------------------- % Default values if no input if nargin<3; w = 15; end if nargin<4; AR = [2 1]; end if nargin<5 || isempty(gap); gap = 0.8; end if nargin<6 || isempty(marg_h); marg_h = [ 0.8 0.4 ]; end if nargin<7 || isempty(marg_w); marg_w = [ 0.8 0.4 ]; end if nargin<8; units = 'centimeters'; end if numel(gap)==1; gap = [gap gap]; end if numel(marg_w)==1; marg_w = [marg_w marg_w]; end if numel(marg_h)==1; marg_h = [marg_h marg_h]; end % Ensure appropriate unit input if strcmp(units, 'centimeters') + strcmp(units, 'inch') + ... strcmp(units, 'points') + strcmp(units, 'pixels') == 0; error('Units must be centimeters ''inch'' ''points'' or ''pixels'''); end % Unit conversion to points if strcmp(units, 'centimeters') == 1; con = 72/2.54; elseif strcmp(units, 'inch') == 1 con = 72; elseif strcmp(units, 'pixels') == 1 con = 0.75; else con = 1; end units = 'points'; w = w * con; gap = gap * con; marg_h = marg_h * con; marg_w = marg_w * con; % Calculation of axis width and height axw = (w-sum(marg_w)-(Nw-1)*gap(2))/Nw; axh = AR(2)/AR(1)*axw; % Calculation of figure height h = Nh*axh + (Nh-1)*gap(1) + sum(marg_h); % Obtain screen dimensions to place figure in the centre set(0, 'units', units); screensize = get(0, 'screensize'); figSize = [ screensize(3)/2 - w/2 screensize(4)/2 - h/2 w h]; % Set the same figure dimensions on screen and paper. set(gcf, 'Units', units, 'Resize', 'off') set(gcf, 'Position', figSize) set(gcf, 'PaperUnits', units, 'PaperSize', [w h]) set(gcf, 'PaperPositionMode', 'manual', 'PaperPosition', [0 0 w h]) % Build axes in figure space py = h-marg_h(2)-axh; ha = zeros(Nh*Nw,1); ii = 0; for ih = 1:Nh px = marg_w(1); for ix = 1:Nw ii = ii+1; ha(ii) = axes; set(gca, 'Units', units, 'Position', [px py axw axh]) set(gca, 'XTickLabel', '', 'YTickLabel', '') px = px+axw+gap(2); end py = py-axh-gap(1); end end
github
jdonley/CoherenceBasedSourceCounter-master
ConcatTIMITtalkers.m
.m
CoherenceBasedSourceCounter-master/ConcatTIMITtalkers.m
1,980
utf_8
ce8fcd183ce3c36ac796127ee7cfc666
function ConcatTIMITtalkers( TIMITdir, OutDir ) %CONCATTIMITTALKERS Concatenates all the talkers from the TIMIT corpus into individual speech files % % Syntax: CONCATTIMITTALKERS( TIMITDIR, OUTDIR ) % % Inputs: % TIMITdir - The directory of the TIMIT corpus % OutDir - The output directory to save the concatenated speech files % % Example: % ConcatTIMITtalkers('C:\TIMIT_90\', '.\') % % See also: getAllFiles, audioread, audiowrite % Author: Jacob Donley % University of Wollongong % Email: [email protected] % Copyright: Jacob Donley 2017 % Date: 21 April 2017 % Version: 1.0 (21 April 2017) % % Original Source URL: https://github.com/JacobD10/SoundZone_Tools % TIMIT corpus URL: https://catalog.ldc.upenn.edu/ldc93s1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AudioExt = '.wav'; % Get all files in the TIMIT corpus AllFiles = getAllFiles( TIMITdir ); % Limit the list to only the WAV files and sort them WAVfiles = sort( AllFiles( contains(lower(AllFiles), AudioExt) ) ); % Reduce to just the unique talker directories TalkerDirs = unique(cellfun(@fileparts,WAVfiles,'un',0)); % Create the output directories if they don't exist OutDirs = strrep(TalkerDirs, TIMITdir, [fileparts(OutDir) filesep]); cellfun(@newDir,cellfun(@fileparts,OutDirs,'un',0),'un',0); % Partition the speech into the separate talkers PartDirs = cellfun(@(tds) WAVfiles(contains(WAVfiles,tds)),TalkerDirs,'un',0); % Concatenate all the speech files [Y, FS] = cellfun(@ReadCatAudio, PartDirs, 'un', 0); % Write all of the concatenated speech files to disk arrayfun(@(i) audiowrite([OutDirs{i} AudioExt], Y{i}, FS{i}), 1:numel(Y)); end function [y, Fs] = ReadCatAudio( filenames ) [Y, FS] = cellfun(@audioread,filenames,'un',0); if ~isequal(FS{:}),error('Different sampling frequencies detected.');end Y_=cellfun(@transpose,Y,'un',0); y = [Y_{:}]; Fs = FS{1}; end function newDir(dir) narginchk(1,1); if ~exist(dir,'dir'), mkdir(dir); end end
github
jdonley/CoherenceBasedSourceCounter-master
getAllFiles.m
.m
CoherenceBasedSourceCounter-master/getAllFiles.m
2,166
utf_8
095e332c0376d673b760c33621f51f0a
function fileList = getAllFiles(dirPath) %GETALLFILES Retrieves a list of all files within a directory % % Syntax: fileList = getAllFiles(dirName) % % Inputs: % dirPath - The relative or full path of the directory to recursivley % search. % % Outputs: % fileList - A cell array list of the full path for each file found. % % Example: % searchPath = [matlabroot filesep 'examples']; % files = getAllFiles(searchPath); % % % Author: Jacob Donley % University of Wollongong % Email: [email protected] % Date: 1 September 2017 % Version: 1.0 (1 September 2017) % Version: 0.1 (22 January 2015) % % Original Source URL: https://github.com/JacobD10/SoundZone_Tools %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Just incase this function tries to recursively call within a class folder we % should create a function handle for this function to use inf = dbstack('-completenames'); funcName = inf.name; funcPath = inf.file; classDirs = getClassDirs(funcPath); thisFuncHandle = str2func([classDirs funcName]); % Find the files dirData = dir(dirPath); % Get the data for the current directory dirIndex = [dirData.isdir]; % Find the index for directories fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files if ~isempty(fileList) fileList = cellfun(@(x) fullfile(dirPath,x),... % Prepend path to files fileList,'UniformOutput',false); end subDirs = {dirData(dirIndex).name}; % Get a list of the subdirectories validIndex = ~ismember(subDirs,{'.','..'}); % Find index of subdirectories that are not '.' or '..' for iDir = find(validIndex) % Loop over valid subdirectories nextDir = fullfile(dirPath,subDirs{iDir}); % Get the subdirectory path fileList = [fileList; thisFuncHandle(nextDir)]; % Recursively call getAllFiles end end function classDirs = getClassDirs(FullPath) classDirs = ''; classes = strfind(FullPath,'+'); for c = 1:length(classes) clas = FullPath(classes(c):end); stp = strfind(clas,filesep); classDirs = [classDirs clas(2:stp(1)-1) '.']; end end
github
jdonley/CoherenceBasedSourceCounter-master
getReceivedSignals.m
.m
CoherenceBasedSourceCounter-master/getReceivedSignals.m
9,673
utf_8
43b664b560e6a36f06fe1f1229d536f4
function [MicSigs, Fs, SrcLocs, NodeLocs] = ... getReceivedSignals( ... Nsrcs, Nnodes, ... RoomSz, TableSz, SeatSz, TableLoc, ... InterSrcDist, IntraNodeDist, ... SynthParams ) %GETRECEIVEDSIGNALS Synthesises received signals at microphones in a meeting scenario % % Syntax: [MicSigs, Fs, SrcLocs, NodeLocs] = ... % getReceivedSignals( ... % Nsrcs, Nnodes, ... % RoomSz, TableSz, SeatSz, TableLoc, ... % InterSrcDist, IntraNodeDist, ... % SynthParams ) % % Inputs: % Nsrcs - Number of speech sources (talkers) % Nnodes - Number of dual microphone nodes % RoomSz - Room dimensions [x, y, z] in metres % TableSz - Size of the meeting table [x, y, z] in metres % SeatSz - Seating area of the talkers [x, y, z] in metres % TableLoc - Centre location of the table [x, y, z] in metres % InterSrcDist - Minimum distance between talkers in metres % IntraNodeDist - Distance between microphones of a node in metres % SynthParams - The structure of synthesis parameters: % |-> .SpeechDir - Directory to read speech samples from. % | (default: 'Speech_Files\') % |-> .c - Sound velocity (metres/ssecond). % | (default: 343) % |-> .res - Resolution in samples per metre. % | (default: 100) % |-> .SNR - Signal to noise ration (for awgn function). % | (default: 40) % |-> .ReverbTime - Reverberation time in seconds. % | (default: 0.2) % |-> .RIRlength - RIR length in seconds. % | (default: 1.0) % |-> .ForceNodeLoc - Forces node location (do not define for % | randomised location). % | (default: <randomised location>) % '-> .Verbose - False suppresses output to command window. % (true or false, default: true) % % Outputs: % MicSigs - The synthesised micrphone signals % Fs - Sampling frequency of MicSigs % SrcLocs - The locations of the talkers % NodeLocs - The location of the nodes % % Example: % Nsources = 4; % Number of sources % Nnodes = 1; % Number of nodes % L = [4 7 3]; % Room dimensions [x y z] (m) % T = [1 3 0]; % Table Size [x y z] (m) % S = T + [0.5 0.5 0]*2; % Seating Area [x y z] (m) % Tloc = L/2; % Table Location [x y z] (m) % InterSrcDist = 0.5; % Minimum distance between talkers (metres) % IntraNodeDist = 0.1; % Distance between microhpones (metres) % [x_2ch, fs] = getReceivedSignals( ... % Nsources, Nnodes, ... % L, T, S, Tloc, ... % InterSrcDist, IntraNodeDist ); % % Reference: % This function makes use of the Room Impulse Response Generator by % Emanuel A.P. Habets: https://www.audiolabs-erlangen.de/fau/professor/habets/software/rir-generator % Note: When SynthParams.Verbose is false the copyright notice is not % printed to the command window. The copyright notice for the included % rir_generator C++ code is: % Room Impulse Response Generator (Version 2.1.20141124) by Emanuel Habets % Copyright (C) 2003-2014 E.A.P. Habets, The Netherlands. % % See also: cbsc, rir_generator, getAllFiles % Author: Jacob Donley % University of Wollongong % Email: [email protected] % Copyright: Jacob Donley 2017 % Date: 8 September 2017 % Version: 1.1 (8 September 2017) % Version: 1.0 (1 September 2017) % Version: 0.1 (21 April 2017) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 9 SynthParams = struct; end SynthParams = setSPDefaults(SynthParams); %% First run attempt rir_generator compilation from current directory compileRIRGenerator; %% rng('shuffle'); Nmics = 2; res = SynthParams.res; IntraNodeDists = repmat(IntraNodeDist,Nnodes,1); NodeAngleRand = rand(Nnodes,1)*2*pi; AvailableNodePos = zeros(RoomSz(1)*res,RoomSz(2)*res); AvailableSrcPos = zeros(RoomSz(1)*res,RoomSz(2)*res); xvec = round((TableLoc(1)-RoomSz(1)/2)*res+1:(TableLoc(1)+RoomSz(1)/2)*res); yvec = round((TableLoc(2)-RoomSz(2)/2)*res+1:(TableLoc(2)+RoomSz(2)/2)*res); Txvec = round((TableLoc(1)-TableSz(1)/2)*res+1:(TableLoc(1)+TableSz(1)/2)*res); Tyvec = round((TableLoc(2)-TableSz(2)/2)*res+1:(TableLoc(2)+TableSz(2)/2)*res); Sxvec = round((TableLoc(1)-SeatSz(1)/2)*res+1:(TableLoc(1)+SeatSz(1)/2)*res); Syvec = round((TableLoc(2)-SeatSz(2)/2)*res+1:(TableLoc(2)+SeatSz(2)/2)*res); [xx,yy]=meshgrid(xvec/res,yvec/res); [Txx,Tyy]=meshgrid(Txvec/res,Tyvec/res); AvailableNodePos( Txvec, Tyvec) = 1; AvailableSrcPos ( Sxvec, Syvec) = 1; AvailableSrcPos ( Txvec, Tyvec) = 0; ChosenTInd = randi(sum(AvailableNodePos(:)),Nnodes,1); ChosenTXLoc = Txx(ChosenTInd); ChosenTYLoc = Tyy(ChosenTInd); ChosenSXLoc=[];ChosenSYLoc=[]; for s = 1:Nsrcs % ChosenSInd = randi(sum(AvailableSrcPos(:)), Nsrcs,1); ChosenSInd = randi(sum(AvailableSrcPos(:)), 1,1); xx_=xx.'.*AvailableSrcPos;xx_=xx_(xx_~=0); yy_=yy.'.*AvailableSrcPos;yy_=yy_(yy_~=0); ChosenSXLoc(s) = xx_(ChosenSInd); ChosenSYLoc(s) = yy_(ChosenSInd); msk = (xx.'-ChosenSXLoc(s)).^2 + (yy.'-ChosenSYLoc(s)).^2 > InterSrcDist^2; AvailableSrcPos = AvailableSrcPos .* msk; end % Source Locations SrcLocs = [ChosenSXLoc.', ChosenSYLoc.', repmat(TableLoc(3),Nsrcs,1)]; % Node Locations NodeLocs = [ChosenTXLoc, ChosenTYLoc, repmat(TableLoc(3),Nnodes,1)]; if isfield(SynthParams, 'ForceNodeLoc') && ~isempty(SynthParams.ForceNodeLoc) NodeLocs = SynthParams.ForceNodeLoc; end % Channel Locations [xOffset,yOffset] = pol2cart([NodeAngleRand NodeAngleRand], [-1*IntraNodeDists 1*IntraNodeDists]/2 ); ChannelLocs = NodeLocs(reshape([1:Nnodes; 1:Nnodes],1,[]),:) + ... [reshape(xOffset.',[],1),reshape(yOffset.',[],1),zeros(Nnodes*2,1)]; %% Prepare source signals files = getAllFiles( SynthParams.SpeechDir ); files(randperm(numel(files),numel(files)-Nsrcs))=[]; SrcSigs=[]; SrcTimePos=0; for file = 1:numel(files) [s, Fs] = audioread( files{file} ); SrcTimePos(file+1) = numel(s)+SrcTimePos(file); SrcSigs = [SrcSigs, ... circshift([ s.'; ... repmat(zeros(1,size(s,1)),numel(files)-1,1);],file-1) ]; end SrcSigs=SrcSigs.'; %% slen = size(SrcSigs,1)+(SynthParams.RIRlength * Fs)-1; MicSigs=zeros(slen,Nmics,Nnodes); for node=1:Nnodes for src = 1:Nsrcs rirARGS = { ... SynthParams.c, ... Fs, ... {ChannelLocs(node*2-1,:), ChannelLocs(node*2,:)}, ... SrcLocs(src,:), ... RoomSz, ... SynthParams.ReverbTime, ... SynthParams.RIRlength * Fs}; for mic = 1:Nmics if SynthParams.Verbose MicSigs(:,mic,node) = MicSigs(:,mic,node) ... + fconv( ... SrcSigs(:,src), ... rir_generator( ... rirARGS{1:2}, rirARGS{3}{mic}, rirARGS{4:end}) ); else evalc( [... 'MicSigs(:,mic,node) = MicSigs(:,mic,node)' ... '+ fconv(' ... 'SrcSigs(:,src),' ... 'rir_generator(' ... 'rirARGS{1:2}, rirARGS{3}{mic}, rirARGS{4:end}) )' ... ] ); end end end for mic = 1:Nmics MicSigs(:,mic,node) = awgn( MicSigs(:,mic,node), SynthParams.SNR, 'measured' ); end end end %-------------------------------------------------------------------------- function SP = setSPDefaults(SP) % Set the default Synthesis Parameters (SP) if ~isfield(SP,'SpeechDir') SP.SpeechDir = 'Speech_Files\'; % Directory to read speech samples from end if ~isfield(SP,'c') SP.c = 343; % Sound velocity (m/s) end if ~isfield(SP,'res') SP.res = 100; % Samples per metre end if ~isfield(SP,'SNR') SP.SNR = 40; % AWGN at <SNR>dB end if ~isfield(SP,'ReverbTime') SP.ReverbTime = 0.2; % seconds end if ~isfield(SP,'RIRlength') SP.RIRlength = 1.0; % seconds end if ~isfield(SP,'Verbose') SP.Verbose = true; % true or false end end %-------------------------------------------------------------------------- function [y]=fconv(x, h) %FCONV Fast Parallelised Convolution % [y] = FCONV(x, h) convolves x and h in the frequency domain % % x = input vector % h = input vector % % See also CONV % % Source URL: https://github.com/JacobD10/SoundZone_Tools %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% x=x(:); h=h(:); Ly=size(x,1)+size(h,1)-1; % Ly2=pow2(nextpow2(Ly)); % Find smallest power of 2 that is > Ly if isa(x, 'gpuArray') Ly = gpuArray(Ly); Ly2 = gpuArray(Ly2); end X=fft(x, Ly2); % Fast Fourier transform H=fft(h, Ly2); % Fast Fourier transform Y=X.*H; % y=real(ifft(Y, Ly2)); % Inverse fast Fourier transform y=y(1:1:Ly,:); % Take just the first N elements end %-------------------------------------------------------------------------- function compileRIRGenerator if exist('rir_generator') ~= 3 ... % If MEX file doesn't exist && exist('rir_generator.cpp', 'file') == 2 ... % and if C++ source exists && ~isempty(mex.getCompilerConfigurations('C++')) % and if C++ compiler exists mex -setup C++ mex rir_generator.cpp end end
github
nurahmadi/BAKS-master
BAKS.m
.m
BAKS-master/BAKS.m
1,200
utf_8
46a40d3e76aaf2aa453b81a1e6f43b77
% Bayesian Adaptive Kernel Smoother (BAKS) % BAKS is a method for estimating firing rate from spike train data that uses kernel smoothing technique % with adaptive bandwidth determined using a Bayesian approach % ---------------INPUT--------------- % - SpikeTimes : spike event times [nSpikes x 1] % - Time : time at which the firing rate is estimated [nTime x 1] % - a : shape parameter (alpha) % - b : scale paramter (beta) % ---------------INPUT--------------- % - h : adaptive bandwidth [nTime x 1] % - FiringRate : estimated firing rate [nTime x 1] % More information, please refer to "Estimation of neuronal firing rate using Bayesian adaptive kernel smoother (BAKS)" function [FiringRate h] = BAKS(SpikeTimes,Time,a,b) N = length(SpikeTimes); sumnum = 0; sumdenum = 0; for i=1:N numerator = (((Time-SpikeTimes(i)).^2)./2 + 1./b).^(-a); denumerator = (((Time-SpikeTimes(i)).^2)./2 + 1./b).^(-a-0.5); sumnum = sumnum + numerator; sumdenum = sumdenum + denumerator; end h = (gamma(a)/gamma(a+0.5)).*(sumnum./sumdenum); FiringRate = zeros(length(Time),1); for j=1:N K = (1./(sqrt(2.*pi).*h)).*exp(-((Time-SpikeTimes(j)).^2)./(2.*h.^2)); FiringRate = FiringRate + K; end
github
Kinpzz/deeplab-v2-master
classification_demo.m
.m
deeplab-v2-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to you Matlab search PATH to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
Kinpzz/deeplab-v2-master
MyVOCevalseg.m
.m
deeplab-v2-master/matlab/my_script/MyVOCevalseg.m
4,625
utf_8
128c24319d520c2576168d1cf17e068f
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = MyVOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; num_missing_img = 0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err num_missing_img = num_missing_img + 1; %fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end if (num_missing_img > 0) fprintf(1, 'WARNING: There are %d missing results!\n', num_missing_img); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end if ~strcmp(clname, 'void') class_count = class_count + 1; fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); real_class_count = 0; for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: denom = (gtj+resj-gtjresj); if denom == 0 denom = 1; end accuracies(j)=100*gtjresj/denom; clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; if ~strcmp(clname, 'void') real_class_count = real_class_count + 1; else if denom ~= 1 fprintf(1, 'WARNING: this void class has denom = %d\n', denom); end end if ~strcmp(clname, 'void') fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end end %accuracies = accuracies(1:end); %avacc = mean(accuracies); avacc = sum(accuracies) / real_class_count; fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
Kinpzz/deeplab-v2-master
MyVOCevalsegBoundary.m
.m
deeplab-v2-master/matlab/my_script/MyVOCevalsegBoundary.m
4,415
utf_8
1b648714e61bafba7c08a8ce5824b105
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts, overall_acc, avg_class_acc] = MyVOCevalsegBoundary(VOCopts, id, w) % get structural element st_w = 2*w + 1; se = strel('square', st_w); % image test set fn = sprintf(VOCopts.seg.imgsetpath,VOCopts.testset); fid = fopen(fn, 'r'); gtids = textscan(fid, '%s'); gtids = gtids{1}; fclose(fid); %[gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); try [resim,map] = imread(resfile); catch err fprintf(1, 'Fail to read %s\n', resfile); continue; end resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end % dilate gt binary_gt = gtim == 255; dilate_gt = imdilate(binary_gt, se); target_gt = dilate_gt & (gtim~=255); %pixel locations to include in computation locs = target_gt; %locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Pixel Accuracy overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); % Class Accuracy class_acc = zeros(1, num); class_count = 0; fprintf('Accuracy for each class (pixel accuracy)\n'); for i = 1 : num denom = sum(confcounts(i, :)); if (denom == 0) denom = 1; else class_count = class_count + 1; end class_acc(i) = 100 * confcounts(i, i) / denom; if i == 1 clname = 'background'; else clname = VOCopts.classes{i-1}; end fprintf(' %14s: %6.3f%%\n', clname, class_acc(i)); end fprintf('-------------------------\n'); avg_class_acc = sum(class_acc) / class_count; fprintf('Mean Class Accuracy: %6.3f%%\n', avg_class_acc); % Pixel IOU accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
OneDirection9/MOT_with_Pose-master
crop_img.m
.m
MOT_with_Pose-master/tools/crop_img.m
1,660
utf_8
5775e63c5f8434d89c164026f1054b5f
function [ ] = crop_img( expidx ) %CROP_IMG Summary of this function goes here % Detailed explanation goes here p = bbox_exp_params(expidx); train_annolist_file = p.trainGT; test_annolist_file = p.testGT; croped_det_dirs = p.cropedDetections; matDetectionsDir = p.matDetectionsDir; vidDir = p.vidDir; crop(train_annolist_file, matDetectionsDir, vidDir, croped_det_dirs) crop(test_annolist_file, matDetectionsDir, vidDir, croped_det_dirs) end function [] = crop(annolist_file, detections_dir, vidDir, save_dir) load(annolist_file, 'annolist'); num_videos = size(annolist, 1); for vidx = 1:num_videos fprintf('%s. Cropping detections for %d/%d.\n', annolist_file, vidx, num_videos); vinfo = annolist(vidx, :); vname = vinfo.name; video_dir = fullfile(vidDir, vname); frames = dir([video_dir, '/*.jpg']); mat_detection = fullfile(detections_dir, vname); load(mat_detection, 'detections'); save_det_dir = fullfile(save_dir, vname); if(exist(save_det_dir)) rmdir(save_det_dir, 's'); end mkdir(save_det_dir); num_det = size(detections.index, 1); for didx = 1:num_det fidx = detections.frameIndex(didx); fr_name = frames(fidx).name; fr_file = fullfile(video_dir, fr_name); fr_img = imread(fr_file); bbox = detections.unPos(didx, :); % x, y, w, h fr_img = imcrop(fr_img, bbox); save_file = fullfile(save_det_dir, [int2str(didx) '.jpg']); imwrite(fr_img, save_file); end end end
github
OneDirection9/MOT_with_Pose-master
convert_kpt2challenge.m
.m
MOT_with_Pose-master/tools/convert_kpt2challenge.m
2,904
utf_8
bab8c2c51e43a092eedd7e3405d50435
function [ ] = convert_kpt2challenge( multicut_dir, anno_dir, save_dir, expidx ) %CONVERT_KTP2CHALLENGE Summary of this function goes here % Detailed explanation goes here clear; clc; if(nargin < 4) multicut_dir = './data/tmp/'; anno_dir = './data/source_annotations/val/'; save_dir = './data/evaluate_result/'; mkdir_when_missing(save_dir); expidx = 6; end annolists = dir([anno_dir '/*.mat']); num_videos = size(annolists, 1); for vidx = 1:num_videos file_name = annolists(vidx).name; fprintf('Processing %s (%d/%d).\n', file_name, vidx, num_videos); anno_file = fullfile(anno_dir, file_name); pred_name = ['prediction_' num2str(expidx) '_' file_name]; pred_file = fullfile(multicut_dir, pred_name); assert(exist(pred_file, 'file') == 2, 'Prediction file: %s does not exists.', pred_file); score_name = ['prediction_score_' num2str(expidx) '_' file_name]; score_file = fullfile(multicut_dir, score_name); assert(exist(score_file, 'file') == 2, 'Score file: %s does not exists.', score_file); load(anno_file, 'annolist'); load(pred_file, 'people_out'); load(score_file, 'score_out'); save_file = fullfile(save_dir, file_name); num_frames = size(annolist, 2); num_det_people = size(people_out, 1); assert(num_det_people <= 100, 'Track id of %s larger than 100', pred_file); pred = struct(); for fidx = 1:num_frames pred(fidx).image.name = annolist(fidx).image.name; pred(fidx).imgnum = fidx; annorect = struct(); pcount = 1; for pid = 1:num_det_people kpts = people_out{pid, fidx}; scores = score_out{pid, fidx}; if(isempty(kpts)) continue; end is_nan = isnan(kpts); is_valid = sum(is_nan, 2) == 0; if(sum(is_valid, 1) == 0) continue; end annorect(pcount).track_id = pid - 1; num_kpts = size(kpts, 1); kcount = 1; points = struct(); for kid = 1:num_kpts point = kpts(kid, :); score = scores(kid, 1); if sum(isnan(point), 2) == size(point, 2) continue; end points(kcount).x = point(1); points(kcount).y = point(2); points(kcount).id = kid - 1; points(kcount).score = score; kcount = kcount + 1; end annorect(pcount).annopoints.point = points; pcount = pcount + 1; end pred(fidx).annorect = annorect; end annolist = pred; save(save_file, 'annolist'); end end function [ ] = mkdir_when_missing(dir) if(exist(dir, 'dir') == 7) return; end mkdir(dir); end
github
OneDirection9/MOT_with_Pose-master
crop_proposals.m
.m
MOT_with_Pose-master/tools/crop_proposals.m
1,622
utf_8
9a228af33fcf1c4b6494d399fbf30902
function [ ] = crop_proposals( expidx ) %CROP_PROPOSALS Summary of this function goes here % Detailed explanation goes here p = bbox_exp_params(expidx); train_annolist_file = p.trainGT; test_annolist_file = p.testGT; croped_pro_dir = p.cropedProposals; proposals_dir = p.detPreposals; vidDir = p.vidDir; dirs = dir(proposals_dir); num_videos = size(dirs, 1); for idx = 3:num_videos % skip ./ and ../ vname = dirs(idx).name; p_dir = fullfile(proposals_dir, vname); v_dir = fullfile(vidDir, vname); proposals_per_frame = dir([p_dir, '/*.txt']); num_frames = size(proposals_per_frame, 1); for fidx = 1:num_frames fprintf('Processing videos %d/%d. Frames: %d/%d\n', idx-2, num_videos-2, fidx, num_frames); f_full_name = proposals_per_frame(fidx).name; f_full_path = fullfile(p_dir, f_full_name); [~, f_name, ~] = fileparts(f_full_path); save_dir = fullfile(croped_pro_dir, vname, f_name); if(exist(save_dir, 'dir')) rmdir(save_dir, 's'); end mkdir(save_dir); [~, xs, ys, ws, hs, ~] = textread(f_full_path, '%s%f%f%f%f%f'); f_v_file = fullfile(v_dir, [f_name '.jpg']); crop(xs, ys, ws, hs, save_dir, f_v_file); end end end function [] = crop(xs, ys, ws, hs, save_dir, f_v_file) num_box_per_frame = size(xs, 1); for idx = 1:num_box_per_frame save_file = fullfile(save_dir, [num2str(idx) '.jpg']); fr_img = imread(f_v_file); p_img = imcrop(fr_img, [xs(idx), ys(idx), ws(idx), hs(idx)]); imwrite(p_img, save_file); end end
github
OneDirection9/MOT_with_Pose-master
regress_box_kpt_split.m
.m
MOT_with_Pose-master/tools/regress_box_kpt_split.m
1,012
utf_8
f85b0da9518550b6bb4bdaee69dbac7b
function [ box_matrix ] = regress_box_kpt_split( people ) %REGRESS_BOX_KPT_SPLIT Summary of this function goes here % Detailed explanation goes here if nargin < 1 load('/home/sensetime/warmer/PoseTrack/challenge/data/prediction_6_001735_mpii_relpath_5sec_testsub_1', 'people'); end box_matrix = []; if(isempty(people)) return; end box_matrix = cellfun(@regress_box_according_kpt, people, 'UniformOutput', false); end function [ box ] = regress_box_according_kpt( kpts ) box = []; if(isempty(kpts)) return; end is_nan = isnan(kpts); is_valid = sum(is_nan, 2) == 0; valid_kpts = kpts(is_valid, :); box = calculate_box( valid_kpts ); end function [ box ] = calculate_box( points ) box = struct(); xs = points(:, 1); ys = points(:, 2); % calculate x, y, w, h minx = min(xs); miny = min(ys); maxx = max(xs); maxy = max(ys); box.x = minx; box.y = miny; box.w = maxx - minx; box.h = maxy - miny; end
github
OneDirection9/MOT_with_Pose-master
bbox_tracking.m
.m
MOT_with_Pose-master/lib/bbox_tracking.m
12,792
utf_8
eafa2b4fa883ac6de5c201e1f98c031e
function bbox_tracking( expidx,firstidx,nVideos,bRecompute,bVis ) %PT_TRACK_JOINT Summary of this function goes here % Detailed explanation goes here fprintf('bbox_tracking()\n'); if (ischar(expidx)) expidx = str2num(expidx); end if (ischar(firstidx)) firstidx = str2num(firstidx); end if (nargin < 2) firstidx = 1; end if (nargin < 3) nVideos = 1; elseif ischar(nVideos) nVideos = str2num(nVideos); end if (nargin < 4) bRecompute = false; end if (nargin < 5) bVis = false; end fprintf('expidx: %d\n',expidx); fprintf('firstidx: %d\n',firstidx); fprintf('nVideos: %d\n',nVideos); p = bbox_exp_params(expidx); load(p.testGT,'annolist'); ptMulticutDir = p.ptMulticutDir; mkdir_if_missing(ptMulticutDir); fprintf('multicutDir: %s\n',ptMulticutDir); visDir = fullfile(ptMulticutDir, 'vis'); mkdir_if_missing(visDir); ptDetectionDir = p.matDetectionsDir; mkdir_if_missing(ptDetectionDir); fprintf('detectionDir: %s\n',ptDetectionDir); num_videos = length(annolist); lastidx = firstidx + nVideos - 1; if (lastidx > num_videos) lastidx = num_videos; end if (firstidx > lastidx) return; end % computation parameters % stride = p.stride; % half_stride = stride/2; % locref_scale_mul = p.locref_scale; % nextreg = isfield(p, 'nextreg') && p.nextreg; unLab_cls = 'uint64'; max_sizet_val = intmax(unLab_cls); ptPairwiseDir = p.ptPairwiseDir; cidx = p.cidx; % pad_orig = p.([video_set 'Pad']); fprintf('Loading temporal model from %s\n', ptPairwiseDir); usedCidx = p.usedCidx; modelName = [ptPairwiseDir '/temporal_model_with_dist_cidx_' num2str(usedCidx)]; temporal_model = struct; m = load(modelName,'temporal_model'); temporal_model.diff = struct; temporal_model.diff.log_reg = m.temporal_model.log_reg; temporal_model.diff.training_opts = m.temporal_model.training_opts; stagewise = false; if isfield(p, 'cidxs_full') cidxs_full = p.cidxs_full; else cidxs_full = p.cidxs; end if stagewise num_stages = length(p.cidxs_stages); else num_stages = 1; end if isfield(p, 'dets_per_part_per_stage') dets_per_part = p.dets_per_part_per_stage; elseif isfield(p, 'dets_per_part') dets_per_part = p.dets_per_part; if stagewise dets_per_part = repmat(dets_per_part, num_stages); end end use_graph_subset = isfield(p, 'graph_subset'); if use_graph_subset load(p.graph_subset); end % pairwise = load_pairwise_data(p); if isfield(p, 'nms_dist') nms_dist = p.nms_dist; else nms_dist = 1.5; end % hist_pairwise = isfield(p, 'histogram_pairwise') && p.histogram_pairwise; % pwIdxsAllrel1 = build_pairwise_pairs(cidxs_full); fprintf('recompute %d\n', bRecompute); idxStart = 1; for vIdx = firstidx:lastidx fprintf('vididx: %d\n',vIdx); ann = annolist(vIdx); vid_name = ann.name; vid_dir = fullfile(p.vidDir, vid_name); num_frames = ann.num_frames; fn = dir([vid_dir,'/*.jpg']); frame_pairs = bbox_build_frame_pairs(num_frames, p.maxFrameDist); corres_dir = fullfile(p.correspondences, vid_name); flows_dir = fullfile(p.ptFlowDir, vid_name); reid_file = fullfile(p.reid, vid_name); detPerFrame = zeros(num_frames,1); detections = []; cidxs = cidxs_full; % fname = [ptMulticutDir '/' vid_name '_cidx_' num2str(cidxs(1)) '_' num2str(cidxs(end))]; detFname = [p.matDetectionsDir '/' vid_name]; predFname = [ptMulticutDir '/prediction_' num2str(expidx) '_' vid_name '.mat']; [pathstr,~,~] = fileparts(predFname); mkdir_if_missing(pathstr); if(exist(predFname, 'file')) fprintf('Prediction already exist at: %s\n', predFname); % bbox_vis_people(expidx, vIdx); % continue; end if(exist([detFname,'.mat'], 'file') && ~bRecompute) load(detFname, 'detections'); else fprintf('Need detections first.\n'); assert(false); end temporalWindows = bbox_generate_frame_windows(num_frames, p.temporalWinSize); for w = 1:size(temporalWindows, 1) stIdx = temporalWindows(w, 1); endIdx = temporalWindows(w, 2); idxs = ismember(detections.frameIndex, stIdx:endIdx) > 0; wDetections = MultiScaleDetections.slice(detections, idxs); wDetections.unLab = zeros(size(wDetections.unProb,1),2,unLab_cls); wDetections.unLab(:,:) = max_sizet_val; origin_detections = copy_detections(wDetections); if(w > 1) fprintf('Window %d/%d: Previous: %d \t New: %d\n', w, size(temporalWindows, 1), size(prev_dets.unProb,1), size(wDetections.unProb,1)); wDetections = MultiScaleDetections.merge(prev_dets, wDetections); origin_detections = MultiScaleDetections.merge(pre_origin_detections, origin_detections); end pre_origin_detections = origin_detections; origin_index = pre_origin_detections.index; wDetections.index = [1:size(wDetections.unProb,1)]'; fprintf('Number of Detections: %d\n', size(wDetections.unProb,1)); pwProbTemporal = []; fprintf('Computing temporal pairwise probabilities. Part = %d\n',cidx); pwProb = bbox_compute_temporal_pairwise_probabilities(p, wDetections, temporal_model, cidx, fn, corres_dir, flows_dir, origin_index, reid_file); pwProbTemporal = [pwProbTemporal;pwProb]; % compute spatial probability. fprintf('Computing spatial pairwise probabilities. Part = %d\n', cidx); pwProbSpatial = cell(num_frames,1); spatial_det_rel = cell(num_frames,1); for fIdx = 1:endIdx bbox_idxs = wDetections.frameIndex == fIdx; fDetections = MultiScaleDetections.slice(wDetections, bbox_idxs); if (size(fDetections.unProb,1) == 0) continue; end num_dets = size(fDetections.unPos, 1); spatial_det_rel{fIdx} = bbox_build_frame_pairs(num_dets, num_dets); spatial_pairs = spatial_det_rel{fIdx}; num_pairs = size(spatial_pairs, 1); detPairIdx = [fDetections.index(spatial_pairs(:, 1)), fDetections.index(spatial_pairs(:, 2))]; pwProbSpatial{fIdx,1} = ones(num_pairs, 1) * fIdx; pwProbSpatial{fIdx,1} = cat(2, pwProbSpatial{fIdx, 1}, detPairIdx ); pwProbSpatial{fIdx,1} = cat(2, pwProbSpatial{fIdx, 1}, zeros(num_pairs, 1)); % part class 1 pwProbSpatial{fIdx,1} = cat(2, pwProbSpatial{fIdx, 1}, zeros(num_pairs, 1)); % part class 2 pwProbSpatial{fIdx,1} = cat(2, pwProbSpatial{fIdx, 1}, zeros(num_pairs, 1)); % probility end pwProbSpatial = cell2mat(pwProbSpatial); % prepare problem for solver numDetections = size(wDetections.unProb, 1); pwProbSolverTemp = pwProbTemporal(:,3:6); pwProbSolverTemp(:,1:2) = pwProbSolverTemp(:,1:2) - min(wDetections.index); % idxs = pwProbSolverTemp(:,3) < 0.6; pwProbSolverTemp(:,3) = pwProbSolverTemp(:,3); pwProbSolverSpat = pwProbSpatial(:, 2:6); pwProbSolverSpat(:,1:2) = pwProbSolverSpat(:,1:2) - min(wDetections.index); problemFname = [ptMulticutDir '/pt-problem-' vid_name '-' num2str(stIdx) '-' num2str(endIdx) '-exp-' num2str(expidx) '.h5']; solutionFname = [ptMulticutDir '/pt-solution-' vid_name '-' num2str(stIdx) '-' num2str(endIdx) '-exp-' num2str(expidx) '.h5']; [pathstr,~,~] = fileparts(problemFname); mkdir_if_missing(pathstr); [pathstr,~,~] = fileparts(solutionFname); mkdir_if_missing(pathstr); fprintf('save problem\n'); % write problem dataName = 'detections-info'; write_mode = 'overwrite'; marray_save(problemFname, dataName, numDetections, write_mode); dataName = 'part-class-probabilities'; write_mode = 'append'; marray_save(problemFname, dataName, cat(2, wDetections.partClass, wDetections.unProb), write_mode); dataName = 'join-probabilities-temporal'; write_mode = 'append'; marray_save(problemFname, dataName, pwProbSolverTemp, write_mode); % dataName = 'join-probabilities-spatial'; % write_mode = 'append'; % marray_save(problemFname, dataName, pwProbSolverSpat, write_mode); dataName = 'coordinates-vertices'; marray_save(problemFname, dataName, cat(2, wDetections.frameIndex, wDetections.unPos), write_mode); singMultSwitch = 'm'; if (isfield(p,'single_people_solver') && p.single_people_solver) singMultSwitch = 's'; end solver = p.ptSolver; time_limit = p.time_limit; cmd = [solver ' ' problemFname ' ' solutionFname ' ' singMultSwitch ' ' num2str(time_limit)]; if(size(temporalWindows, 1) > 1 && w > 1) initSolutionFname = fullfile(ptMulticutDir, ['pt-init-solution-' vid_name '-' num2str(stIdx) '-' num2str(endIdx) '-exp-' num2str(expidx) '.h5']); dataName = 'detection-parts-and-clusters'; marray_save(initSolutionFname, dataName, wDetections.unLab, 'overwrite'); cmd = [cmd ' ' initSolutionFname]; end fprintf('calling pt-solver: %s\n', cmd); [~,hostname] = unix('echo $HOSTNAME'); fprintf('hostname: %s',hostname); pre_cmd = ['export GRB_LICENSE_FILE=' p.gurobi_license_file]; tic setenv('LD_LIBRARY_PATH', ''); s = unix([pre_cmd '; ' cmd]); toc if (s > 0) error('solver error'); end assert(s == 0); % clean up unix(['rm ' problemFname]); % load solution dataName = 'part-tracks'; unLab = marray_load(solutionFname, dataName); % TODO: prune Detections. out_dets = copy_detections(wDetections); % [unLab, idxs] = pruneDetections(unLab, wDetections, cidxs, 0); % out_dets = MultiScaleDetections.slice(out_dets, idxs); out_dets.unLab = unLab; prev_dets = copy_detections(out_dets); % people = bbox_compute_final_posetrack_predictions( out_dets ); people = out_dets; people.origin_index = origin_index; save(predFname, 'people'); end % visualise predictions % bbox_vis_people(expidx, vIdx); end fprintf('done\n'); if (isdeployed) close all; end end function [outClusters] = pruneClusters(clusters, frameIndexes, labels, minLen) outClusters = []; for c = 1:length(clusters) cl = clusters(c); idxs = labels == cl; frameLen = length(unique(frameIndexes(idxs))); if(frameLen > minLen) outClusters = [outClusters;cl]; end end end function [unLab_new, idxs] = pruneDetections(unLab, detections, cidxs, minLen) clusters = unique(unLab(:, 2)); clusters = pruneClusters(clusters, detections.frameIndex, unLab(:,2), minLen); idxs = []; stIdx = min(detections.frameIndex); endIdx = max(detections.frameIndex); for fIdx = stIdx:endIdx %get the detections in current frame and suppress those with status 0 cfIdxs = find(bitand(detections.frameIndex == fIdx, logical(unLab(:,1)))); for j = 1:length(clusters) cl = clusters(j); cDets = unLab(cfIdxs, 2) == cl; labels = detections.partClass(cfIdxs); for k = 1:length(cidxs) cidx = cidxs(k); bundle = find(cDets & labels == cidx); if isempty(bundle) continue; end probs = detections.unProb(cfIdxs(bundle)); [~, I] = max(probs); idxs = [idxs; cfIdxs(bundle(I))]; end end end idxs = sort(idxs); unLab_new = unLab(idxs, :); for j = 1:length(clusters) cl = clusters(j); I = unLab_new == cl; unLab_new(I) = j-1; end %idxs end function dets = copy_detections(dets_src) dets = struct(); dets.unPos = dets_src.unPos; % dets.unPos_sm = dets_src.unPos_sm; dets.unProb = dets_src.unProb; % dets.locationRefine = dets_src.locationRefine; % dets.nextReg = dets_src.nextReg; % dets.unProbNoThresh = dets_src.unProbNoThresh; if isfield(dets_src, 'unLab') dets.unLab = dets_src.unLab; end if isfield(dets_src, 'scale') dets.scale = dets_src.scale; end if isfield(dets_src, 'frameIndex') dets.frameIndex = dets_src.frameIndex; end if isfield(dets_src, 'index') dets.index = dets_src.index; end if isfield(dets_src, 'partClass') dets.partClass = dets_src.partClass; end end
github
OneDirection9/MOT_with_Pose-master
convert_txt_with_keypoints.m
.m
MOT_with_Pose-master/lib/convert_txt_with_keypoints.m
2,596
utf_8
9bbacc470ac470c95a61499b74f670f4
function [ ] = convert_txt_with_keypoints(p) % convert txt files under source_dir to mat and saved in save_dir. % if nargin < 1 keypoints_dir = './data/keypoints_txt/'; save_keypoint_dir = './data/keypoints/'; save_map_dir = './data/cross_map/'; testGT = './data/annolist/test/annolist'; score_thresh = 0; end load(testGT, 'annolist'); % % empty save_dir % if exist(save_dir, 'dir') % fprintf('`%s` already exists, delete.\n', save_dir); % rmdir(save_dir, 's'); % end mkdir_if_missing(save_keypoint_dir); mkdir_if_missing(save_map_dir); num_videos = size(annolist, 1); for i = 1:num_videos vinfo = annolist(i, :); vname = vinfo.name; num_frames = vinfo.num_frames; file_name = [ vname '.txt' ]; full_file = fullfile(keypoints_dir, file_name); assert(exist(full_file, 'file') ~= 0); fprintf('Converting detection txt `%s` to mat. %d/%d\n', vname, i, num_videos); [box_idxs, frame_idxs, xs, ys, scores] = textread(full_file, '%f%f%f%f%f'); % convert `full_file` to mat. % fields: unPos, unProb, frameIndex, index, scale, partClass. detections = struct(); [valid_indexs, classes] = generate_valid_index(scores, score_thresh); num_keypoints = sum(valid_indexs); detections.unPos = [xs(valid_indexs == 1), ys(valid_indexs == 1)]; scores = min(1 - 1e-15, scores); scores = max(1e-15, scores); detections.unProb = scores(valid_indexs == 1); detections.frameIndex = frame_idxs(valid_indexs == 1); detections.cand = [1:num_keypoints]'; detections.scale = ones(num_keypoints, 1); detections.partClass = classes; % save as the mat. file_name = deblank(file_name); splits = regexp(file_name, '\.', 'split'); % 000001.txt_result.txt => [000001, txt_result, txt] save_name = splits{1}; full_save = fullfile(save_keypoint_dir, save_name); save(full_save, 'detections'); cross_map = struct(); cross_map = [1:num_keypoints]'; cross_map = [cross_map, box_idxs(valid_indexs == 1)]; full_map_save = fullfile(save_map_dir, save_name); save(full_map_save, 'cross_map'); end fprintf('Convert keypoints .txt to .mat, done.\n'); end function [ valid_idxs, classes ] = generate_valid_index( scores, score_thresh ) num_keypoints = size(scores, 1); valid_idxs = ones(num_keypoints, 1); classes = []; for id = 1:num_keypoints cid = rem(id - 1, 15) + 1; if scores(id) < score_thresh valid_idxs(id) = 0; continue; end classes = [classes; cid]; end end
github
OneDirection9/MOT_with_Pose-master
convert_txt2mat.m
.m
MOT_with_Pose-master/lib/convert_txt2mat.m
4,576
utf_8
23f68edd3b17fc7a6a7a38885d6a1b51
function [ ] = convert_txt2mat(p, IOU_thresh) % convert txt files under source_dir to mat and saved in save_dir. % if nargin < 2 IOU_thresh = 0.3; end source_dir = p.txtDetectionsDir; save_dir = p.matDetectionsDir; testGT = p.testGT; load(testGT, 'annolist'); % % empty save_dir % if exist(save_dir, 'dir') % fprintf('`%s` already exists, delete.\n', save_dir); % rmdir(save_dir, 's'); % end mkdir_if_missing(save_dir); num_videos = size(annolist, 1); for i = 1:num_videos vinfo = annolist(i, :); vname = vinfo.name; num_frames = vinfo.num_frames; file_name = [ vname '.txt' ]; full_file = fullfile(source_dir, file_name); assert(exist(full_file, 'file') ~= 0); fprintf('Converting detection txt `%s` to mat. %d/%d\n', vname, i, num_videos); [names, xs, ys, ws, hs, scores] = textread(full_file, '%f%f%f%f%f%f'); if false && ~isempty(vinfo.ignore_regions) num_det = size(names, 1); not_ignore = ones(1, num_det); % 1: not ignore. % read for img size. img_size = vinfo.img_size; % calculate pair. [q1, q2] = meshgrid(1:img_size(1), 1:img_size(2)); idxsAllrel = [ q1(:) q2(:)]; for fidx = 1:num_frames ignore_regions = vinfo.ignore_regions{fidx}; if isempty(ignore_regions) continue; end % full_name = sprintf('%05d', fidx); % frame_file = fullfile(vid_dir, [full_name '.jpg']); % img = imread(frame_file); % imshow(img); frame_mask = generateFrameMask(img_size(1:2), ignore_regions, idxsAllrel); % calculate sub matrix for each detection det_idxs = find(names == fidx); det_xs = xs(det_idxs); det_ys = ys(det_idxs); det_ws = ws(det_idxs); det_hs = hs(det_idxs); minxs = max(1, floor(det_xs)); minys = max(1, floor(det_ys)); maxxs = max(1, floor(det_xs + det_ws)); maxys = max(1, floor(det_ys + det_hs)); num_dets = size(det_idxs, 1); for id = 1:num_dets sub_matrix = frame_mask(minys(id):maxys(id), minxs(id):maxxs(id)); num_pixels = sum(sum(sub_matrix)); iou = num_pixels / (det_ws(id) * det_hs(id)); if iou > IOU_thresh not_ignore(det_idxs(id)) = 0; end end end names = names(not_ignore == 1); xs = xs(not_ignore == 1); ys = ys(not_ignore == 1); ws = ws(not_ignore == 1); hs = hs(not_ignore == 1); scores = scores(not_ignore == 1); end % convert `full_file` to mat. % fields: unPos, unProb, frameIndex, index, scale, partClass. detections = struct(); detections.unPos = [xs, ys, ws, hs]; scores = min(1 - 1e-15, scores); scores = max(1e-15, scores); detections.unProb = scores; detections.frameIndex = names; detections.index = [1:size(names,1)]'; detections.cand = [1:size(names,1)]'; detections.scale = ones(size(names,1), 1); detections.partClass = zeros(size(names,1), 1); % save as the mat. file_name = deblank(file_name); splits = regexp(file_name, '\.', 'split'); % 000001.txt_result.txt => [000001, txt_result, txt] save_name = splits{1}; full_save = fullfile(save_dir, save_name); save(full_save, 'detections'); end fprintf('Convert detection .txt to .mat, done.\n'); end function [ frame_mask ] = generateFrameMask(img_size, ignore_regions, idxsAllrel) all_points = []; num_ignore = size(ignore_regions, 2); for ig_idx = 1:num_ignore if isfield(ignore_regions(ig_idx), 'point') num_points = length(ignore_regions(ig_idx).point); ir_points = get_points(ignore_regions(ig_idx), num_points); idx = ~isnan(ir_points(:,1)); ir_points = ir_points(idx,:); all_points = [all_points; ir_points; NaN, NaN]; end end ins = inpolygon(idxsAllrel(:,2), idxsAllrel(:, 1), all_points(:, 1), all_points(:, 2)); frame_mask = reshape_C(ins, [img_size, 1]); end function points = get_points(annopoints, num_points) points = NaN(num_points, 2); if(isfield(annopoints, 'point')) ids = [annopoints.point.id]+1; x = [annopoints.point.x]'; y = [annopoints.point.y]'; points(ids,:) = [x, y]; end end
github
OneDirection9/MOT_with_Pose-master
convert_pred2challenge.m
.m
MOT_with_Pose-master/lib/convert_pred2challenge.m
4,559
utf_8
79f5bce15af086a26b951c295fc35bcc
function [ ] = convert_pred2challenge( pred_dir, gt_dir, save_dir, expidx ) %CONVERT_PRED2CHALLENGE Summary of this function goes here % Detailed explanation goes here clear; clc; if nargin < 1 % pred_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/mot-multicut/'; pred_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/prune_tmp'; gt_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/source_annotations/val/'; save_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/predictions/'; mkdir_if_missing(save_dir); cross_map_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/cross_map'; keypoints_dir = '/home/sensetime/warmer/PoseTrack/challenge/data/keypoints'; score_thresh = 0.02; expidx = 2; end if isnumeric(expidx) expidx = num2str(expidx); end prefix = ['prediction_' expidx '_']; anno_GT = dir([gt_dir '/*.mat']); num_videos = size(anno_GT, 1); for vidx = 1:num_videos file_name = anno_GT(vidx).name; fprintf('Converting prediction for %s to challenge %d/%d.\n', file_name, vidx, num_videos); gt_file = fullfile(gt_dir, file_name); pred_file = fullfile(pred_dir, [prefix file_name]); assert( exist(pred_file, 'file') == 2, 'Prediction for %s does not exists.', file_name ); keypoints_file = fullfile(keypoints_dir, file_name); assert(exist(keypoints_file, 'file') == 2, 'Keypoints for %s does not exists.', file_name); cross_map_file = fullfile(cross_map_dir, file_name); assert(exist(cross_map_file, 'file') == 2, 'Cross map file for %s does not exists.', file_name); save_file = fullfile(save_dir, file_name); load(pred_file, 'people'); load(gt_file, 'annolist'); load(keypoints_file, 'detections'); load(cross_map_file, 'cross_map'); num_frames = size(annolist, 2); valid_idxs = people.unLab(:, 1) == 1; valid_track_ids = people.unLab(valid_idxs, 2); uni_track_ids = unique(valid_track_ids); pred = struct(); for fidx = 1:num_frames pred(fidx).image.name = annolist(fidx).image.name; pred(fidx).imgnum = fidx; annorect = struct(); wpeople = slice(people, fidx); unlab = wpeople.unLab; num_clusters = size(unlab, 1); count = 1; for cid = 1:num_clusters if(unlab(cid, 1) == 0) continue; end box_id = wpeople.origin_index(cid); origin_track_id = unlab(cid, 2); id = find(uni_track_ids == origin_track_id) - 1; % start from 0 annorect(count).track_id = id; annorect(count).box_id = box_id; annorect(count).box_pos = wpeople.unPos(cid, :); annorect(count).box_score = wpeople.unProb(cid, :); key_idxs = cross_map(:, 2) == box_id; key = cross_map(key_idxs, :); points = generate_points(detections, key, fidx, score_thresh); if(isempty(points)) continue; end annorect(count).annopoints.point = points; count = count + 1; end pred(fidx).annorect = annorect; end annolist = pred; save(save_file, 'annolist'); end end function [ wpeople ] = slice( people, fidx ) cur_frame_index = people.frameIndex == fidx; wpeople.unPos = people.unPos(cur_frame_index, :); wpeople.unProb = people.unProb(cur_frame_index, :); wpeople.unLab = people.unLab(cur_frame_index, :); wpeople.frameIndex = people.frameIndex(cur_frame_index, :); wpeople.index = people.index(cur_frame_index, :); wpeople.origin_index = people.origin_index(cur_frame_index, :); end function [ points ] = generate_points(detections, key_idxs, fidx, score_thresh) points = []; frame_idxs = detections.frameIndex(key_idxs(:, 1), :); frame_id = unique(frame_idxs); assert(size(frame_id, 1) == 1, 'keypoints not in the same frame.'); assert(frame_id == fidx, 'frame id not match.'); pos = detections.unPos(key_idxs(:, 1), :); probs =detections.unProb(key_idxs(:, 1), :); k_id = 0; count = 1; num_kpts = size(pos, 1); for kid = 1:num_kpts prob = probs(kid, :); if(prob < score_thresh) continue; end points(count).x = pos(kid, 1); points(count).y = pos(kid, 2); points(count).id = k_id; points(count).score = prob; count = count + 1; k_id = k_id + 1; end end
github
OneDirection9/MOT_with_Pose-master
generate_gttxt.m
.m
MOT_with_Pose-master/lib/generate_gttxt.m
4,386
utf_8
acf5c5b5550af414f769140ef17ab842
function [] = generate_gttxt( annolist_file, save_dir, usage, IOU_thresh ) if nargin < 4 IOU_thresh = 0.3; end load(annolist_file); % if exist(save_dir, 'dir') % rmdir(save_dir, 's'); % end mkdir_if_missing(save_dir); num_videos = size(annolist, 1); for vidx = 1:num_videos fprintf('Generating gt.txt. `%s: %s`. Videos: %d/%d\n', usage, annolist(vidx).name, vidx, num_videos); % video information. vinfo = annolist(vidx,:); vname = vinfo.name; num_frames = vinfo.num_frames; num_persons = vinfo.num_persons; fbbox = vinfo.bbox; % generate img1 , det. mkdir_if_missing(fullfile(save_dir, vname, 'det')); mkdir_if_missing(fullfile(save_dir, vname, 'img1')); % save in the gt/gt.txt save_result_dir = fullfile(save_dir, vname, 'gt'); mkdir_if_missing(save_result_dir); save_file = fullfile(save_result_dir, 'gt.txt'); fsave = fopen(save_file, 'w'); % read for img size. img_size = vinfo.img_size; % calculate pair. [q1, q2] = meshgrid(1:img_size(1), 1:img_size(2)); idxsAllrel = [ q1(:) q2(:)]; frame_mask = []; for fidx = 1:num_frames if isfield(vinfo, 'ignore_regions') && ~isempty(vinfo.ignore_regions) ignore_regions = vinfo.ignore_regions{fidx}; if ~isempty(ignore_regions) frame_mask = generateFrameMask(img_size(1:2), ignore_regions, idxsAllrel); end end for pidx = 1:num_persons % fprintf('Generating gt.txt. `%s: %s`. person/frame: %d/%d\n', usage, annolist(vidx).name, pidx, fidx); % skip empty entry pbox = fbbox{pidx, fidx}; if(isempty(pbox)) continue; end if ~isempty(frame_mask) x = max(1, floor(pbox.x)); y = max(1, floor(pbox.y)); w = floor(pbox.w); h = floor(pbox.h); maxy = min(img_size(1), y + h); maxx = min(img_size(1), x + w); sub_matrix = frame_mask(y : maxy, x : maxx); num_pixels = sum(sum(sub_matrix)); iou = num_pixels / (w * h); if iou > IOU_thresh continue; end end % frameid, objid, x, y, w, h, flag, X, Y, Z fprintf(fsave, [num2str(fidx), ',']); % frame id fprintf(fsave, [num2str(pidx), ',']); % object id fprintf(fsave, [num2str(pbox.x), ',']); % x fprintf(fsave, [num2str(pbox.y), ',']); % y fprintf(fsave, [num2str(pbox.w), ',']); % w fprintf(fsave, [num2str(pbox.h), ',']); % h fprintf(fsave, [num2str(1), ',']); % flag: 1(evaluate), 0(not evaluate) fprintf(fsave, [num2str(1), ',']); % X fprintf(fsave, [num2str(1), ',']); % Y fprintf(fsave, [num2str(1), ',']); % Z fprintf(fsave, '\n'); end end fclose(fsave); end fprintf('Generate gt.txt done.\n'); end function [ frame_mask ] = generateFrameMask(img_size, ignore_regions, idxsAllrel) all_points = []; num_ignore = size(ignore_regions, 2); for ig_idx = 1:num_ignore if isfield(ignore_regions(ig_idx), 'point') num_points = length(ignore_regions(ig_idx).point); ir_points = get_points(ignore_regions(ig_idx), num_points); idx = ~isnan(ir_points(:,1)); ir_points = ir_points(idx,:); all_points = [all_points; ir_points; NaN, NaN]; end end ins = inpolygon(idxsAllrel(:,2), idxsAllrel(:, 1), all_points(:, 1), all_points(:, 2)); frame_mask = reshape_C(ins, [img_size, 1]); end function points = get_points(annopoints, num_points) points = NaN(num_points, 2); if(isfield(annopoints, 'point')) ids = [annopoints.point.id]+1; x = [annopoints.point.x]'; y = [annopoints.point.y]'; points(ids,:) = [x, y]; end end
github
OneDirection9/MOT_with_Pose-master
convert_prediction2txt.m
.m
MOT_with_Pose-master/lib/convert_prediction2txt.m
3,445
utf_8
66c87f27d8cb6106e6d0dedb8e7e0842
function [ ] = convert_prediction2txt( expidx, save_dir, annolist_test, prediction_dir, pruneThresh, curSaveDir ) %GENERATE_MOT_DET Summary of this function goes here % Detailed explanation goes here if(nargin<5) pruneThresh = 5; end load(annolist_test, 'annolist'); num_videos = size(annolist, 1); mkdir_if_missing(curSaveDir); for vidx = 1:num_videos fprintf('Converting prediction to txt: `%s`. Videos: %d/%d\n', annolist(vidx,:).name, vidx, num_videos); % video name vinfo = annolist(vidx, :); vname = vinfo.name; num_frames = vinfo.num_frames; save_file = fullfile(save_dir, [vname '.txt']); fsave = fopen(save_file, 'w'); prediction_save_file = fullfile(curSaveDir, ['/prediction_' num2str(expidx) '_' vname]); % prediction result. pred_file = fullfile(prediction_dir, ['/prediction_' num2str(expidx) '_' vname]); load(pred_file, 'people'); unLab = people.unLab; clusters = unique(unLab(:, 2)); num_cluster = size(clusters, 1); for cidx = 1:num_cluster % cluster number cluster = clusters(cidx); % index for detections belong to cluster indexs = people.index(unLab(:,2) == cluster); num_ = size(indexs, 1); if(num_ <= pruneThresh) people.unLab(indexs, 1) = 0; continue; end cpeople = MultiScaleDetections.slice(people, indexs); people = MergeWithinFrame(people, cpeople, num_frames); frame_indexs = people.frameIndex(indexs); for i = 1:num_ index = indexs(i); isValid = people.unLab(index, 1); if isValid == 0 continue; end frame_index = frame_indexs(i); if vinfo.is_labeled(frame_index) == 0 continue; end bbox = people.unPos(index, :); fidx = people.frameIndex(index, :); fprintf(fsave, [num2str(fidx), ',']); % frame index fprintf(fsave, [num2str(cluster), ',']); % object id fprintf(fsave, [num2str(bbox(1)), ',']); % x fprintf(fsave, [num2str(bbox(2)), ',']); % y fprintf(fsave, [num2str(bbox(3)), ',']); % w fprintf(fsave, [num2str(bbox(4)), ',']); % h fprintf(fsave, [num2str(-1), ',']); % flag fprintf(fsave, [num2str(-1), ',']); % X fprintf(fsave, [num2str(-1), ',']); % Y fprintf(fsave, [num2str(-1), ',']); % Z fprintf(fsave, '\n'); end end save(prediction_save_file, 'people'); end end function [ people ] = MergeWithinFrame(people, cpeople, num_frames) for fidx = 1:num_frames idxs = find(cpeople.frameIndex == fidx); num_dets = size(idxs, 1); if num_dets > 1 indexs = cpeople.index(idxs); people.unLab(indexs, 1) = 0; probs = cpeople.unProb(idxs); [~, max_idx] = max(probs); idd = idxs(max_idx); index = cpeople.index(idd); people.unLab(index, 1) = 1; end end end
github
OneDirection9/MOT_with_Pose-master
regress_bbox_gt.m
.m
MOT_with_Pose-master/lib/regress_bbox_gt.m
5,491
utf_8
2283bb4ba62c750d328979656b4b0868
function [ ] = regress_bbox_gt( annolist_file, videos_dir, save_dir, scale, isSave, isShow, useIncludeUnvisiable ) %CALCULATE_BBOX_GT Summary of this function goes here % Detailed explanation goes here fprintf('Calculating ground truth for `%s`\n', annolist_file); load(annolist_file, 'annolist'); [file_path, file_name, ~] = fileparts(annolist_file); if isSave if exist(save_dir, 'dir') rmdir(save_dir, 's'); end mkdir(save_dir); end num_videos = size(annolist, 1); for vidx = 1:num_videos fprintf('Regressing bbox: %s(%d/%d).\n', annolist(vidx, :).name, vidx, num_videos); % video information vinfo = annolist(vidx, :); vname = vinfo.name; num_frames = vinfo.num_frames; num_persons = vinfo.num_persons; video_dir = fullfile(videos_dir, vname); fimages = dir([video_dir,'/*.jpg']); if isSave video_save_dir = fullfile(save_dir, vname); if exist(video_save_dir, 'dir') rmdir(video_save_dir, 's'); end mkdir_if_missing(video_save_dir); end % add field: bbox. vinfo.bbox = cell( num_persons, num_frames); for fidx = 1:num_frames empty = 0; for pidx = 1:num_persons if isempty(vinfo.annopoints{pidx, fidx}) empty = empty + 1; end end if empty == num_persons continue; end % fprintf('Regressing bbox: %s(%d/%d). Frames: %d/%d\n', annolist(vidx, :).name, vidx, num_videos, fidx, num_frames); image_name = fimages(fidx).name; fimage = fullfile(video_dir, image_name); img = imread(fimage); img_size = size(img); if ~isfield(annolist(vidx), 'img_size') || isempty(annolist(vidx).img_size) annolist(vidx).img_size = img_size(1:2); else is_matches = annolist(vidx).img_size == img_size(1:2); assert(sum(is_matches) == 2, 'Size of images in same video is not same.\n'); end if(isShow) figure(1), imshow(img); hold on; end [by, bx, ~] = size(img); for pidx = 1:num_persons % fprintf('Regressing bbox: %s(%d/%d). Frames: %d/%d Persons: %d/%d\n', annolist(vidx, :).name, vidx, num_videos, fidx, num_frames, pidx, num_persons); fp_info = vinfo.annopoints{pidx, fidx}; % the pidx-th person in the fidx-th frames. if(isempty(fp_info)) continue; end if(~isfield(fp_info, 'point')) continue; end bbox_gt = calculate_bbox(fp_info, scale, bx, by, useIncludeUnvisiable); vinfo.bbox{pidx, fidx} = bbox_gt; if(isempty(bbox_gt)) continue; end if(isShow) rectangle('Position', [bbox_gt.x, bbox_gt.y, bbox_gt.w, bbox_gt.h], 'EdgeColor', 'r', 'LineWidth', 3); end end % save figures. if(isSave) save_name = fullfile(video_save_dir, image_name); % print(gcf, '-r300', '-djpeg', save_name); frame = getframe; im = frame2im(frame); imwrite(im, save_name, 'jpg'); end if(isShow) pause(0.001); end end if(isShow) close all; end annolist(vidx).bbox = vinfo.bbox; end % save in the mat. save(annolist_file, 'annolist'); end function [ bbox ] = calculate_bbox( annopoint, scale, bx, by, useIncludeUnvisiable ) points = annopoint.point; bbox = struct(); if(useIncludeUnvisiable) visible_idx = [1:size(points, 2)]; else visible_idx = find(cellfun(@(x)isequal(x,1), {points.is_visible})); end if(isempty(visible_idx)) bbox = []; return end xs = [points(visible_idx).x]; ys = [points(visible_idx).y]; % calculate x, y, w, h minx = min(xs); miny = min(ys); maxx = max(xs); maxy = max(ys); w = maxx - minx; h = maxy - miny; % calculate coordinate of center. half_w = w/2; half_h = h/2; x_center = minx + half_w; y_center = miny + half_h; half_w_s = half_w * scale; half_h_s = half_h * scale; top_left_x = x_center - half_w_s; top_left_y = y_center - half_h_s; bottom_right_x = x_center + half_w_s; bottom_right_y = y_center + half_h_s; [top_left_x, top_left_y] = constraintNotOutBoundary(top_left_x, top_left_y, bx, by); [bottom_right_x, bottom_right_y] = constraintNotOutBoundary(bottom_right_x, bottom_right_y, bx, by); bbox.x = top_left_x; bbox.y = top_left_y; bbox.w = bottom_right_x - top_left_x; bbox.h = bottom_right_y - top_left_y; end function [x, y] = constraintNotOutBoundary( x, y, bx, by) if(x < 0) x = 0; elseif(x > bx) x = bx; end if(y < 0) y = 0; elseif(y > by) y = by; end end
github
OneDirection9/MOT_with_Pose-master
evaluateTracking.m
.m
MOT_with_Pose-master/devkit/evaluateTracking.m
8,672
utf_8
2fe649d71269eeff6f69054aaee0e771
function allMets=evaluateTracking( seqmap, resDir, dataDir, vidDir, isShowFP ) %% evaluate CLEAR MOT and other metrics % concatenate ALL sequences and evaluate as one! % % SETUP: % % define directories for tracking results... % resDir = fullfile('res','data',filesep); % ... and the actual sequences % dataDir = fullfile('..','data','2DMOT2015','train',filesep); % % addpath(genpath('.')); % read sequence map % seqmapFile=fullfile('seqmaps',seqmap); seqmapFile = seqmap; allSeq = parseSequences(seqmapFile); fprintf('Sequences: \n'); disp(allSeq') % concat gtInfo gtInfo=[]; gtInfo.X=[]; allFgt=zeros(1,length(allSeq)); % Find out the length of each sequence % and concatenate ground truth gtInfoSingle=[]; seqCnt=0; for s=allSeq seqCnt=seqCnt+1; seqName = char(s); seqFolder= [dataDir,seqName,filesep]; assert(isdir(seqFolder),'Sequence folder %s missing',seqFolder); gtFile = fullfile(dataDir,seqName,'gt','gt.txt'); gtI = convertTXTToStruct(gtFile,seqFolder); [Fgt,Ngt] = size(gtInfo.X); [FgtI,NgtI] = size(gtI.Xi); newFgt = Fgt+1:Fgt+FgtI; newNgt = Ngt+1:Ngt+NgtI; gtInfo.Xi(newFgt,newNgt) = gtI.Xi; gtInfo.Yi(newFgt,newNgt) = gtI.Yi; gtInfo.W(newFgt,newNgt) = gtI.W; gtInfo.H(newFgt,newNgt) = gtI.H; gtInfoSingle(seqCnt).wc=0; % fill in world coordinates if they exist if isfield(gtI,'Xgp') && isfield(gtI,'Ygp') gtInfo.Xgp(newFgt,newNgt) = gtI.Xgp; gtInfo.Ygp(newFgt,newNgt) = gtI.Ygp; gtInfoSingle(seqCnt).wc=1; end % check if bounding boxes available in solution imCoord=1; if all(gtI.Xi(find(gtI.Xi(:)))==-1) imCoord=0; end gtInfo.X=gtInfo.Xi;gtInfo.Y=gtInfo.Yi; if ~imCoord gtInfo.X=gtInfo.Xgp;gtInfo.Y=gtInfo.Ygp; end allFgt(seqCnt) = FgtI; gtInfoSingle(seqCnt).gtInfo=gtI; end gtInfo.frameNums=1:size(gtInfo.Xi,1); allMets=[]; mcnt=1; fprintf('Evaluating ... \n'); clear stInfo stInfo.Xi=[]; evalMethod=1; % flags for entire benchmark % if one seq missing, evaluation impossible eval2D=1; eval3D=1; seqCnt=0; % iterate over each sequence for s=allSeq seqCnt=seqCnt+1; seqName = char(s); fprintf('\t%d... %s\n',seqCnt, seqName); % if a result is missing, we cannot evaluate this tracker resFile = fullfile(resDir,[seqName '.txt']); if ~exist(resFile,'file') fprintf('WARNING: result for %s not available!\n',seqName); eval2D=0; eval3D=0; continue; end % if MOT16, preprocess (clean) if ~isempty(strfind(seqName,'MOT16')) resFile = preprocessResult(resFile, seqName, dataDir); end stI = convertTXTToStruct(resFile); % stI.Xi(find(stI.Xi(:)))=-1; % check if bounding boxes available in solution imCoord=1; if all(stI.Xi(find(stI.Xi(:)))==-1) imCoord=0; end worldCoordST=0; % state if isfield(stI,'Xgp') && isfield(stI,'Ygp') worldCoordST=1; end [FI,NI] = size(stI.Xi); % if stateInfo shorter, pad with zeros % GT and result must be equal length if FI<allFgt(seqCnt) missingFrames = FI+1:allFgt(seqCnt); stI.Xi(missingFrames,:)=0; stI.Yi(missingFrames,:)=0; stI.W(missingFrames,:)=0; stI.H(missingFrames,:)=0; stI.X(missingFrames,:)=0; stI.Y(missingFrames,:)=0; if worldCoordST stI.Xgp(missingFrames,:)=0; stI.Ygp(missingFrames,:)=0; end [FI,NI] = size(stI.Xi); % if stateInfo longer, crop elseif FI>allFgt(seqCnt) stI.Xi=stI.Xi(1:allFgt(seqCnt),:); stI.Yi=stI.Yi(1:allFgt(seqCnt),:); stI.W=stI.W(1:allFgt(seqCnt),:); stI.H=stI.H(1:allFgt(seqCnt),:); stI.X=stI.X(1:allFgt(seqCnt),:); stI.Y=stI.Y(1:allFgt(seqCnt),:); if worldCoordST stI.Xgp=stI.Xgp(1:allFgt(seqCnt),:); stI.Ygp=stI.Ygp(1:allFgt(seqCnt),:); end [FI,NI] = size(stI.Xi); end % get result for one sequence only [mets, mInf, additionalInfo ]=CLEAR_MOT_HUN(gtInfoSingle(seqCnt).gtInfo,stI); allMets(mcnt).mets2d(seqCnt).name=seqName; allMets(mcnt).mets2d(seqCnt).m=mets; allMets(mcnt).mets3d(seqCnt).name=seqName; allMets(mcnt).mets3d(seqCnt).m=zeros(1,length(mets)); if imCoord fprintf('*** 2D (Bounding Box overlap) ***\n'); printMetrics(mets); fprintf('\n'); else fprintf('*** Bounding boxes not available ***\n\n'); eval2D=0; end % draw false positives. if(isShowFP) drawFP(gtInfoSingle(seqCnt).gtInfo, stI, additionalInfo.allfalsepos, vidDir, seqName); end % if world coordinates available, evaluate in 3D if gtInfoSingle(seqCnt).wc && worldCoordST evopt.eval3d=1;evopt.td=1; [mets, mInf]=CLEAR_MOT_HUN(gtInfoSingle(seqCnt).gtInfo,stI,evopt); allMets(mcnt).mets3d(seqCnt).m=mets; fprintf('*** 3D (in world coordinates) ***\n'); printMetrics(mets); fprintf('\n'); else eval3D=0; end [F,N] = size(stInfo.Xi); newF = F+1:F+FI; newN = N+1:N+NI; % concat result stInfo.Xi(newF,newN) = stI.Xi; stInfo.Yi(newF,newN) = stI.Yi; stInfo.W(newF,newN) = stI.W; stInfo.H(newF,newN) = stI.H; if isfield(stI,'Xgp') && isfield(stI,'Ygp') stInfo.Xgp(newF,newN) = stI.Xgp;stInfo.Ygp(newF,newN) = stI.Ygp; end stInfo.X=stInfo.Xi;stInfo.Y=stInfo.Yi; if ~imCoord stInfo.X=stInfo.Xgp;stInfo.Y=stInfo.Ygp; end end stInfo.frameNums=1:size(stInfo.Xi,1); if eval2D fprintf('\n'); fprintf(' ********************* Your Benchmark Results (2D) ***********************\n'); [m2d, mInf]=CLEAR_MOT_HUN(gtInfo,stInfo); allMets.bmark2d=m2d; evalFile = fullfile(resDir, 'eval2D.txt'); printMetrics(m2d); dlmwrite(evalFile,m2d); detailFile = fullfile(resDir, 'detail2D.txt'); fsave = fopen(detailFile, 'w'); dlmwrite(detailFile, m2d); for midx = 1:14 fprintf(fsave, [num2str(m2d(midx)), '\t']); end fprintf(fsave, '\n'); num_videos = size(allMets.mets2d, 2); fprintf(fsave, 'Name\tRcll\tPrcn\tFAR\tGT\tMT\tPT\tML\tFP\tFN\tIDs\tFM\tMOTA\tMOTP\tMOTAL\n'); for vidx = 1:num_videos res = allMets.mets2d(vidx); fprintf(fsave, [res.name, '\t']); for midx = 1:14 fprintf(fsave, [num2str(res.m(midx)), '\t']); end fprintf(fsave, '\n'); end fclose(fsave); end if eval3D fprintf('\n'); fprintf(' ********************* Your Benchmark Results (3D) ***********************\n'); evopt.eval3d=1;evopt.td=1; [m3d, mInf]=CLEAR_MOT_HUN(gtInfo,stInfo,evopt); allMets.bmark3d=m3d; evalFile = fullfile(resDir, 'eval3D.txt'); printMetrics(m3d); dlmwrite(evalFile,m3d); end if ~eval2D && ~eval3D fprintf('ERROR: results cannot be evaluated\n'); end end function [] = drawFP(gtinfo, stI, allfalsepos, vidDir, seqName) colors = {'r','g','b','c','m','y'}; lineWidth = 3; video_dir = fullfile(vidDir, seqName); fn = dir([video_dir, '/*.jpg']); num_frames = size(allfalsepos, 1); for fidx = 1 : num_frames fr_fn = fullfile(video_dir, fn(fidx).name); img = imread(fr_fn); figure(1), imshow(img); hold on; num_person = size(gtinfo.X,2); for pidx = 1:num_person color = colors{mod(pidx, length(colors))+1}; xi = gtinfo.Xi(fidx, pidx); yi = gtinfo.Yi(fidx, pidx); w = gtinfo.W(fidx, pidx); h = gtinfo.H(fidx, pidx); x = xi - w/2; y = yi - h; pos = [x, y, w, h]; rectangle('Position', pos, 'EdgeColor', color, 'LineWidth', lineWidth); text(pos(1)+5, pos(2)+15, num2str(pidx), 'FontSize', 20); end falsepos = find(allfalsepos(fidx, :) ~= 0); if(isempty(falsepos)) continue; end for falidx = falsepos color = colors{mod(falidx, length(colors))+1}; xi = stI.Xi(fidx, falidx); yi = stI.Yi(fidx, falidx); w = stI.W(fidx, falidx); h = stI.H(fidx, falidx); x = xi - w/2; y = yi - h; pos = [x, y, w, h]; rectangle('Position', pos, 'EdgeColor', color, 'LineWidth', lineWidth); text(pos(1)+5, pos(2)+15, 'fp', 'FontSize', 20); end pause(); end close all; end
github
OneDirection9/MOT_with_Pose-master
CLEAR_MOT_HUN.m
.m
MOT_with_Pose-master/devkit/utils/CLEAR_MOT_HUN.m
11,304
utf_8
d5f4e2fadb052f0e4c42157ed3daccba
function [metrics metricsInfo additionalInfo ]=CLEAR_MOT_HUN(gtInfo,stateInfo,options) % compute CLEAR MOT and other metrics % % metrics contains the following % [1] recall - recall = percentage of detected targets % [2] precision - precision = percentage of correctly detected targets % [3] FAR - number of false alarms per frame % [4] GT - number of ground truth trajectories % [5-7] MT, PT, ML - number of mostly tracked, partially tracked and mostly lost trajectories % [8] falsepositives- number of false positives (FP) % [9] missed - number of missed targets (FN) % [10] idswitches - number of id switches (IDs) % [11] FRA - number of fragmentations % [12] MOTA - Multi-object tracking accuracy in [0,100] % [13] MOTP - Multi-object tracking precision in [0,100] (3D) / [td,100] (2D) % [14] MOTAL - Multi-object tracking accuracy in [0,100] with log10(idswitches) % % % (C) Anton Milan, 2012-2014 % default options: 2D if nargin<3 options.eval3d=0; % only bounding box overlap options.td=.5; % threshold 50% end if ~isfield(options,'td') if options.eval3d options.td=1000; else options.td=0.5; end end td=options.td; % if X,Y not existent, assume 2D if ~isfield(gtInfo,'X'), gtInfo.X=gtInfo.Xi; end if ~isfield(gtInfo,'Y'), gtInfo.Y=gtInfo.Yi; end if ~isfield(stateInfo,'X'), stateInfo.X=stateInfo.Xi; end if ~isfield(stateInfo,'Y'), stateInfo.Y=stateInfo.Yi; end gtInd=~~gtInfo.X; stInd=~~stateInfo.X; [Fgt, Ngt]=size(gtInfo.X); [F, N]=size(stateInfo.X); % if stateInfo shorter, pad with zeros if F<Fgt missingFrames = F+1:Fgt; stateInfo.Xi(missingFrames,:)=0; stateInfo.Yi(missingFrames,:)=0; stateInfo.W(missingFrames,:)=0; stateInfo.H(missingFrames,:)=0; end metricsInfo.names.long = {'Recall','Precision','False Alarm Rate', ... 'GT Tracks','Mostly Tracked','Partially Tracked','Mostly Lost', ... 'False Positives', 'False Negatives', 'ID Switches', 'Fragmentations', ... 'MOTA','MOTP', 'MOTA Log'}; metricsInfo.names.short = {'Rcll','Prcn','FAR', ... 'GT','MT','PT','ML', ... 'FP', 'FN', 'IDs', 'FM', ... 'MOTA','MOTP', 'MOTAL'}; metricsInfo.widths.long = [6 9 16 9 14 17 11 15 15 11 14 5 5 8]; metricsInfo.widths.short = [5 5 5 3 3 3 3 4 4 3 3 5 5 5]; metricsInfo.format.long = {'.1f','.1f','.2f', ... 'i','i','i','i', ... 'i','i','i','i', ... '.1f','.1f','.1f'}; metricsInfo.format.short=metricsInfo.format.long; metrics=zeros(1,14); metrics(9)=numel(find(gtInd)); % False Negatives (missed) metrics(7)=Ngt; % Mostly Lost metrics(4)=Ngt; % GT Trajectories additionalInfo=[]; % nothing to be done, if state is empty if ~N, return; end % global opt % if options.eval3d && opt.mex % [MOTA MOTP ma fpa mmea idsw missed falsepositives idswitches at afp MT PT ML rc pc faf FM MOTAL alld]= ... % CLEAR_MOT_mex(gtInfo.Xgp', gtInfo.Ygp', stateInfo.Xgp', stateInfo.Ygp',options.td); % % % cd /home/aanton/diss/utils % % [MOTA MOTP ma fpa mmea idsw missed falsepositives idswitches at afp MT PT ML rc pc faf FM MOTAL alld]= ... % % CLEAR_MOT(gtInfo.Xgp, gtInfo.Ygp, stateInfo.Xgp, stateInfo.Ygp,options.td); % % cd /home/aanton/visinf/projects/ongoing/contracking % metrics=[rc*100, pc*100, faf, Ngt, MT, PT, ML, falsepositives, missed, idswitches, FM, MOTA*100, MOTP*100, MOTAL*100]; % metrics % global gsi % gsi=stateInfo; % pause % return; % end % mapping M=zeros(F,Ngt); mme=zeros(1,F); % ID Switchtes (mismatches) c=zeros(1,F); % matches found fp=zeros(1,F); % false positives m=zeros(1,F); % misses = false negatives g=zeros(1,F); d=zeros(F,Ngt); % all distances; ious=Inf*ones(F,Ngt); % all overlaps matched=@matched2d; if options.eval3d, matched=@matched3d; end alltracked=zeros(F,Ngt); allfalsepos=zeros(F,N); allfalseneg=zeros(F,N); for t=1:F g(t)=numel(find(gtInd(t,:))); % mapping for current frame if t>1 mappings=find(M(t-1,:)); for map=mappings if gtInd(t,map) && stInd(t,M(t-1,map)) && matched(gtInfo,stateInfo,t,map,M(t-1,map),td) M(t,map)=M(t-1,map); end end end GTsNotMapped=find(~M(t,:) & gtInd(t,:)); EsNotMapped=setdiff(find(stInd(t,:)),M(t,:)); % reshape to ensure horizontal vector in empty case EsNotMapped=reshape(EsNotMapped,1,length(EsNotMapped)); GTsNotMapped=reshape(GTsNotMapped,1,length(GTsNotMapped)); if options.eval3d alldist=Inf*ones(Ngt,N); mindist=0; for o=GTsNotMapped GT=[gtInfo.Xgp(t,o) gtInfo.Ygp(t,o)]; for e=EsNotMapped E=[stateInfo.Xgp(t,e) stateInfo.Ygp(t,e)]; alldist(o,e)=norm(GT-E); end end tmpai=alldist; tmpai(tmpai>td)=Inf; [Mtch,Cst]=Hungarian(tmpai); [u,v]=find(Mtch); for mmm=1:length(u) M(t,u(mmm))=v(mmm); end % while mindist < td && numel(GTsNotMapped)>0 && numel(EsNotMapped)>0 % for o=GTsNotMapped % GT=[gtInfo.Xgp(t,o) gtInfo.Ygp(t,o)]; % for e=EsNotMapped % E=[stateInfo.Xgp(t,e) stateInfo.Ygp(t,e)]; % alldist(o,e)=norm(GT-E); % end % end % % [mindist cind]=min(alldist(:)); % % if mindist <= td % [u v]=ind2sub(size(alldist),cind); % M(t,u)=v; % alldist(:,v)=Inf; % GTsNotMapped=find(~M(t,:) & gtInd(t,:)); % EsNotMapped=setdiff(find(stInd(t,:)),M(t,:)); % end % end else allisects=zeros(Ngt,N); maxisect=Inf; for o=GTsNotMapped GT=[gtInfo.X(t,o)-gtInfo.W(t,o)/2 ... gtInfo.Y(t,o)-gtInfo.H(t,o) ... gtInfo.W(t,o) gtInfo.H(t,o) ]; for e=EsNotMapped E=[stateInfo.Xi(t,e)-stateInfo.W(t,e)/2 ... stateInfo.Yi(t,e)-stateInfo.H(t,e) ... stateInfo.W(t,e) stateInfo.H(t,e) ]; allisects(o,e)=boxiou(GT(1),GT(2),GT(3),GT(4),E(1),E(2),E(3),E(4)); end end tmpai=allisects; tmpai=1-tmpai; tmpai(tmpai>td)=Inf; [Mtch,Cst]=Hungarian(tmpai); [u,v]=find(Mtch); M=M; for mmm=1:length(u) M(t,u(mmm))=v(mmm); end % GTsNotMapped=find(~M(t,:) & gtInd(t,:)); % EsNotMapped=setdiff(find(stInd(t,:)),M(t,:)); % while maxisect > td && numel(GTsNotMapped)>0 && numel(EsNotMapped)>0 % % for o=GTsNotMapped % GT=[gtInfo.X(t,o)-gtInfo.W(t,o)/2 ... % gtInfo.Y(t,o)-gtInfo.H(t,o) ... % gtInfo.W(t,o) gtInfo.H(t,o) ]; % for e=EsNotMapped % E=[stateInfo.Xi(t,e)-stateInfo.W(t,e)/2 ... % stateInfo.Yi(t,e)-stateInfo.H(t,e) ... % stateInfo.W(t,e) stateInfo.H(t,e) ]; % allisects(o,e)=boxiou(GT(1),GT(2),GT(3),GT(4),E(1),E(2),E(3),E(4)); % end % end % % [maxisect, cind]=max(allisects(:)); % % if maxisect >= td % [u, v]=ind2sub(size(allisects),cind); % M(t,u)=v; % allisects(:,v)=0; % GTsNotMapped=find(~M(t,:) & gtInd(t,:)); % EsNotMapped=setdiff(find(stInd(t,:)),M(t,:)); % end % % end end curtracked=find(M(t,:)); alltrackers=find(stInd(t,:)); mappedtrackers=intersect(M(t,find(M(t,:))),alltrackers); falsepositives=setdiff(alltrackers,mappedtrackers); alltracked(t,:)=M(t,:); % allfalsepos(t,1:length(falsepositives))=falsepositives; allfalsepos(t,falsepositives)=falsepositives; %% mismatch errors if t>1 for ct=curtracked lastnotempty=find(M(1:t-1,ct),1,'last'); if gtInd(t-1,ct) && ~isempty(lastnotempty) && M(t,ct)~=M(lastnotempty,ct) mme(t)=mme(t)+1; end end end c(t)=numel(curtracked); for ct=curtracked eid=M(t,ct); if options.eval3d d(t,ct)=norm([gtInfo.Xgp(t,ct) gtInfo.Ygp(t,ct)] - ... [stateInfo.Xgp(t,eid) stateInfo.Ygp(t,eid)]); else gtLeft=gtInfo.X(t,ct)-gtInfo.W(t,ct)/2; gtTop=gtInfo.Y(t,ct)-gtInfo.H(t,ct); gtWidth=gtInfo.W(t,ct); gtHeight=gtInfo.H(t,ct); stLeft=stateInfo.Xi(t,eid)-stateInfo.W(t,eid)/2; stTop=stateInfo.Yi(t,eid)-stateInfo.H(t,eid); stWidth=stateInfo.W(t,eid); stHeight=stateInfo.H(t,eid); ious(t,ct)=boxiou(gtLeft,gtTop,gtWidth,gtHeight,stLeft,stTop,stWidth,stHeight); end end fp(t)=numel(find(stInd(t,:)))-c(t); m(t)=g(t)-c(t); end missed=sum(m); falsepositives=sum(fp); idswitches=sum(mme); if options.eval3d MOTP=(1-sum(sum(d))/sum(c)/td) * 100; % avg distance to [0,100] else MOTP=sum(ious(ious>=td & ious<Inf))/sum(c) * 100; % avg ol end MOTAL=(1-((sum(m)+sum(fp)+log10(sum(mme)+1))/sum(g)))*100; MOTA=(1-((sum(m)+sum(fp)+(sum(mme)))/sum(g)))*100; recall=sum(c)/sum(g)*100; precision=sum(c)/(sum(fp)+sum(c))*100; FAR=sum(fp)/Fgt; %% MT PT ML MTstatsa=zeros(1,Ngt); for i=1:Ngt gtframes=find(gtInd(:,i)); gtlength=length(gtframes); gttotallength=numel(find(gtInd(:,i))); trlengtha=numel(find(alltracked(gtframes,i)>0)); if gtlength/gttotallength >= 0.8 && trlengtha/gttotallength < 0.2 MTstatsa(i)=3; elseif t>=find(gtInd(:,i),1,'last') && trlengtha/gttotallength <= 0.8 MTstatsa(i)=2; elseif trlengtha/gttotallength >= 0.8 MTstatsa(i)=1; end end % MTstatsa MT=numel(find(MTstatsa==1));PT=numel(find(MTstatsa==2));ML=numel(find(MTstatsa==3)); %% fragments fr=zeros(1,Ngt); for i=1:Ngt b=alltracked(find(alltracked(:,i),1,'first'):find(alltracked(:,i),1,'last'),i); b(~~b)=1; fr(i)=numel(find(diff(b)==-1)); end FRA=sum(fr); assert(Ngt==MT+PT+ML,'Hmm... Not all tracks classified correctly.'); metrics=[recall, precision, FAR, Ngt, MT, PT, ML, falsepositives, missed, idswitches, FRA, MOTA, MOTP, MOTAL]; additionalInfo.alltracked=alltracked; additionalInfo.allfalsepos=allfalsepos; end function ret=matched2d(gtInfo,stateInfo,t,map,mID,td) gtLeft=gtInfo.X(t,map)-gtInfo.W(t,map)/2; gtTop=gtInfo.Y(t,map)-gtInfo.H(t,map); gtWidth=gtInfo.W(t,map); gtHeight=gtInfo.H(t,map); stLeft=stateInfo.Xi(t,mID)-stateInfo.W(t,mID)/2; stTop=stateInfo.Yi(t,mID)-stateInfo.H(t,mID); stWidth=stateInfo.W(t,mID); stHeight=stateInfo.H(t,mID); ret = boxiou(gtLeft,gtTop,gtWidth,gtHeight,stLeft,stTop,stWidth,stHeight) >= td; end function ret=matched3d(gtInfo,stateInfo,t,map,mID,td) Xgt=gtInfo.Xgp(t,map); Ygt=gtInfo.Ygp(t,map); X=stateInfo.Xgp(t,mID); Y=stateInfo.Ygp(t,mID); ret=norm([Xgt Ygt]-[X Y])<=td; end
github
OneDirection9/MOT_with_Pose-master
Hungarian.m
.m
MOT_with_Pose-master/devkit/utils/Hungarian.m
9,328
utf_8
51e60bc9f1f362bfdc0b4f6d67c44e80
function [Matching,Cost] = Hungarian(Perf) % % [MATCHING,COST] = Hungarian_New(WEIGHTS) % % A function for finding a minimum edge weight matching given a MxN Edge % weight matrix WEIGHTS using the Hungarian Algorithm. % % An edge weight of Inf indicates that the pair of vertices given by its % position have no adjacent edge. % % MATCHING return a MxN matrix with ones in the place of the matchings and % zeros elsewhere. % % COST returns the cost of the minimum matching % Written by: Alex Melin 30 June 2006 % Initialize Variables Matching = zeros(size(Perf)); % Condense the Performance Matrix by removing any unconnected vertices to % increase the speed of the algorithm % Find the number in each column that are connected num_y = sum(~isinf(Perf),1); % Find the number in each row that are connected num_x = sum(~isinf(Perf),2); % Find the columns(vertices) and rows(vertices) that are isolated x_con = find(num_x~=0); y_con = find(num_y~=0); % Assemble Condensed Performance Matrix P_size = max(length(x_con),length(y_con)); P_cond = zeros(P_size); P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con); if isempty(P_cond) Cost = 0; return end % Ensure that a perfect matching exists % Calculate a form of the Edge Matrix Edge = P_cond; Edge(P_cond~=Inf) = 0; % Find the deficiency(CNUM) in the Edge Matrix cnum = min_line_cover(Edge); % Project additional vertices and edges so that a perfect matching % exists Pmax = max(max(P_cond(P_cond~=Inf))); P_size = length(P_cond)+cnum; P_cond = ones(P_size)*Pmax; P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con); %************************************************* % MAIN PROGRAM: CONTROLS WHICH STEP IS EXECUTED %************************************************* exit_flag = 1; stepnum = 1; while exit_flag switch stepnum case 1 [P_cond,stepnum] = step1(P_cond); case 2 [r_cov,c_cov,M,stepnum] = step2(P_cond); case 3 [c_cov,stepnum] = step3(M,P_size); case 4 [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M); case 5 [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov); case 6 [P_cond,stepnum] = step6(P_cond,r_cov,c_cov); case 7 exit_flag = 0; end end % Remove all the virtual satellites and targets and uncondense the % Matching to the size of the original performance matrix. Matching(x_con,y_con) = M(1:length(x_con),1:length(y_con)); Cost = sum(sum(Perf(Matching==1))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Find the smallest number of zeros in each row % and subtract that minimum from its row %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [P_cond,stepnum] = step1(P_cond) P_size = length(P_cond); % Loop throught each row for ii = 1:P_size rmin = min(P_cond(ii,:)); P_cond(ii,:) = P_cond(ii,:)-rmin; end stepnum = 2; %************************************************************************** % STEP 2: Find a zero in P_cond. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** function [r_cov,c_cov,M,stepnum] = step2(P_cond) % Define variables P_size = length(P_cond); r_cov = zeros(P_size,1); % A vector that shows if a row is covered c_cov = zeros(P_size,1); % A vector that shows if a column is covered M = zeros(P_size); % A mask that shows if a position is starred or primed for ii = 1:P_size for jj = 1:P_size if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0 M(ii,jj) = 1; r_cov(ii) = 1; c_cov(jj) = 1; end end end % Re-initialize the cover vectors r_cov = zeros(P_size,1); % A vector that shows if a row is covered c_cov = zeros(P_size,1); % A vector that shows if a column is covered stepnum = 3; %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** function [c_cov,stepnum] = step3(M,P_size) c_cov = sum(M,1); if sum(c_cov) == P_size stepnum = 7; else stepnum = 4; end %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** function [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M) P_size = length(P_cond); zflag = 1; while zflag % Find the first uncovered zero row = 0; col = 0; exit_flag = 1; ii = 1; jj = 1; while exit_flag if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0 row = ii; col = jj; exit_flag = 0; end jj = jj + 1; if jj > P_size; jj = 1; ii = ii+1; end if ii > P_size; exit_flag = 0; end end % If there are no uncovered zeros go to step 6 if row == 0 stepnum = 6; zflag = 0; Z_r = 0; Z_c = 0; else % Prime the uncovered zero M(row,col) = 2; % If there is a starred zero in that row % Cover the row and uncover the column containing the zero if sum(find(M(row,:)==1)) ~= 0 r_cov(row) = 1; zcol = find(M(row,:)==1); c_cov(zcol) = 0; else stepnum = 5; zflag = 0; Z_r = row; Z_c = col; end end end %************************************************************************** % STEP 5: Construct a series of alternating primed and starred zeros as % follows. Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** function [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov) zflag = 1; ii = 1; while zflag % Find the index number of the starred zero in the column rindex = find(M(:,Z_c(ii))==1); if rindex > 0 % Save the starred zero ii = ii+1; % Save the row of the starred zero Z_r(ii,1) = rindex; % The column of the starred zero is the same as the column of the % primed zero Z_c(ii,1) = Z_c(ii-1); else zflag = 0; end % Continue if there is a starred zero in the column of the primed zero if zflag == 1; % Find the column of the primed zero in the last starred zeros row cindex = find(M(Z_r(ii),:)==2); ii = ii+1; Z_r(ii,1) = Z_r(ii-1); Z_c(ii,1) = cindex; end end % UNSTAR all the starred zeros in the path and STAR all primed zeros for ii = 1:length(Z_r) if M(Z_r(ii),Z_c(ii)) == 1 M(Z_r(ii),Z_c(ii)) = 0; else M(Z_r(ii),Z_c(ii)) = 1; end end % Clear the covers r_cov = r_cov.*0; c_cov = c_cov.*0; % Remove all the primes M(M==2) = 0; stepnum = 3; % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** function [P_cond,stepnum] = step6(P_cond,r_cov,c_cov) a = find(r_cov == 0); b = find(c_cov == 0); minval = min(min(P_cond(a,b))); P_cond(find(r_cov == 1),:) = P_cond(find(r_cov == 1),:) + minval; P_cond(:,find(c_cov == 0)) = P_cond(:,find(c_cov == 0)) - minval; stepnum = 4; function cnum = min_line_cover(Edge) % Step 2 [r_cov,c_cov,M,stepnum] = step2(Edge); % Step 3 [c_cov,stepnum] = step3(M,length(Edge)); % Step 4 [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(Edge,r_cov,c_cov,M); % Calculate the deficiency cnum = length(Edge)-sum(r_cov)-sum(c_cov);
github
OneDirection9/MOT_with_Pose-master
IniConfig.m
.m
MOT_with_Pose-master/devkit/utils/external/iniconfig/IniConfig.m
59,579
UNKNOWN
bc446e2c4372f0e2377ce83ed57afaef
classdef IniConfig < handle %IniConfig - The class for working with configurations of settings and INI-files. % This class allows you to create configurations of settings, and to manage them. % The structure of the storage settings is similar to the structure of % the storage the settings in the INI-file format. % The class allows you to import settings from the INI-file and to export % the settings in INI-file. % Can be used for reading/writing data in the INI-file and managing % settings of application. % % % Using: % ini = IniConfig() % % Public Properties: % Enter this command to get the properties: % >> properties IniConfig % % Public Methods: % Enter this command to get the methods: % >> methods IniConfig % % Enter this command to get more info of method: % >> help IniConfig/methodname % % % Config Syntax: % % ; some comments % % [Section1] ; allowed the comment to section % ; comment on the section % key1 = value_1 ; allowed a comment to an individual parameter % key2 = value_2 % % [Section2] % key1 = value_1.1, value_1.2 ; array data % key2 = value_2 % ... % % Note: % * There may be spaces in the names of sections and keys % * Keys should not be repeated in the section (will read the last) % * Sections should not be repeated in the config (will read the last) % % Supported data types: % * numeric scalars and vectors % * strings % % % Example: % ini = IniConfig(); % ini.ReadFile('example.ini') % ini.ToString() % % Example: % ini = IniConfig(); % ini.ReadFile('example.ini') % sections = ini.GetSections() % [keys, count_keys] = ini.GetKeys(sections{1}) % values = ini.GetValues(sections{1}, keys) % new_values(:) = {rand()}; % ini.SetValues(sections{1}, keys, new_values, '%.3f') % ini.WriteFile('example1.ini') % % Example: % ini = IniConfig(); % ini.AddSections({'Some Section 1', 'Some Section 2'}) % ini.AddKeys('Some Section 1', {'some_key1', 'some_key2'}, {'hello!', [10, 20]}) % ini.AddKeys('Some Section 2', 'some_key3', true) % ini.AddKeys('Some Section 2', 'some_key1') % ini.WriteFile('example2.ini') % % Example: % ini = IniConfig(); % ini.AddSections('Some Section 1') % ini.AddKeys('Some Section 1', 'some_key1', 'hello!') % ini.AddKeys('Some Section 1', {'some_key2', 'some_key3'}, {[10, 20], [false, true]}) % ini.WriteFile('example31.ini') % ini.RemoveKeys('Some Section 1', {'some_key1', 'some_key3'}) % ini.RenameKeys('Some Section 1', 'some_key2', 'renamed_some_key2') % ini.RenameSections('Some Section 1', 'Renamed Section 1') % ini.WriteFile('example32.ini') % % % See also: % textscan, containers.Map % % % Author: Iroln <[email protected]> % Version: 1.2 % First release: 25.07.09 % Last revision: 21.03.10 % Copyright: (c) 2009-2010 Evgeny Prilepin aka Iroln % % Bug reports, questions, etc. can be sent to the e-mail given above. % properties (GetAccess = 'public', SetAccess = 'private') comment_style = ';' % style of comments count_sections = 0 % number of sections count_all_keys = 0 % number of all keys end properties (GetAccess = 'private', SetAccess = 'private') config_data_array = {} indicies_of_sections indicies_of_empty_strings count_strings = 0 count_empty_strings = 0 is_created_configuration = false end %====================================================================== methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Public Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %------------------------------------------------------------------ function obj = IniConfig() %IniConfig - constructor % To Create new object with empty default configuration. % % Using: % obj = IniConfig() % % Input: % none % % Output: % obj - an instance of class IniConfig % ------------------------------------------------------------- obj.CreateIni(); end %------------------------------------------------------------------ function CreateIni(obj) %CreateIni - create new empty configuration % % Using: % CreateIni() % % Input: % none % % Output: % none % ------------------------------------------------------------- obj.config_data_array = cell(2,3); obj.config_data_array(:,:) = {''}; obj.updateCountStrings(); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); obj.is_created_configuration = true; end %------------------------------------------------------------------ function status = ReadFile(obj, file_name, comment_style) %ReadFile - to read in the object the config data from a INI file % % Using: % status = ReadFile(file_name, comment_style) % % Input: % file_name - INI file name % comment_style - style of comments in INI file % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- narginchk(2, 3); CheckIsString(file_name); if (nargin == 3) obj.comment_style = ValidateCommentStyle(comment_style); end % Get data from file [file_data, status] = GetDataFromFile(file_name); if (status) obj.count_strings = size(file_data, 1); obj.config_data_array = ... ParseConfigData(file_data, obj.comment_style); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); obj.updateCountKeysInfo(); obj.is_created_configuration = true; end end %------------------------------------------------------------------ function status = IsSections(obj, section_names) %IsSections - determine whether there is a sections % % Using: % status = IsSections(section_names) % % Input: % section_names - name of section(s) % % Output: % status - 1 (true) - yes, 0 (false) - no % ------------------------------------------------------------- error(nargchk(2, 2, nargin)); section_names = DataToCell(section_names); section_names = cellfun(@(x) obj.validateSectionName(x), ... section_names, 'UniformOutput', false); status = cellfun(@(x) obj.isSection(x), ... section_names, 'UniformOutput', true); end %------------------------------------------------------------------ function [section_names, count_sect] = GetSections(obj) %GetSections - get names of all sections % % Using: % section_names = GetSections() % [names_sect, count_sect] = GetSections() % % Input: % none % % Output: % section_names - cell array with the names of sections % count_sect - number of sections in configuration % ------------------------------------------------------------- narginchk(1, 1); section_names = obj.config_data_array(obj.indicies_of_sections, 1); % section_names = strrep(section_names, '[', ''); % section_names = strrep(section_names, ']', ''); count_sect = obj.count_sections; end %------------------------------------------------------------------ function status = AddSections(obj, section_names) %AddSections - add sections to end configuration % % Using: % status = AddSections(section_names) % % Input: % section_names - name of section % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(2, 2, nargin)); section_names = DataToCell(section_names); section_names = cellfun(@(x) obj.validateSectionName(x), ... section_names, 'UniformOutput', false); status = cellfun(@(x) obj.addSection(x), ... section_names, 'UniformOutput', true); end %------------------------------------------------------------------ function status = InsertSections(obj, positions, section_names) %InsertSections - insert sections to given positions % % Using: % status = InsertSections(positions, section_names) % % Input % positions - positions of sections % section_names - names of sections % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(3, 3, nargin)); positions = DataToCell(positions); section_names = DataToCell(section_names); CheckEqualNumberElems(positions, section_names); section_names = cellfun(@(x) obj.validateSectionName(x), ... section_names, 'UniformOutput', false); status = cellfun(@(x, y) obj.insertSection(x, y), ... positions, section_names, 'UniformOutput', true); end %------------------------------------------------------------------ function status = RemoveSections(obj, section_names) %RemoveSections - remove given section % % Using: % status = RemoveSections(section_names) % % Input: % section_names - names of sections % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(2, 2, nargin)); section_names = DataToCell(section_names); status = cellfun(@(x) obj.removeSection(x), ... section_names, 'UniformOutput', true); end %------------------------------------------------------------------ function status = RenameSections(obj, old_section_names, new_section_names) %RenameSections - rename given sections % % Using: % status = RenameSections(old_section_names, new_section_names) % % Input: % old_section_names - old names of sections % new_section_names - new names of sections % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(3, 3, nargin)); old_section_names = DataToCell(old_section_names); new_section_names = DataToCell(new_section_names); CheckEqualNumberElems(old_section_names, new_section_names); status = cellfun(@(x, y) obj.renameSection(x, y), ... old_section_names, new_section_names, 'UniformOutput', true); end %------------------------------------------------------------------ function status = IsKeys(obj, section_name, key_names) %IsKeys - determine whether there is a keys in a given section % % Using: % status = IsKeys(section_name, key_names) % % Input: % key_names - name of keys % % Output: % status - 1 (true) - yes, 0 (false) - no % ------------------------------------------------------------- error(nargchk(3, 3, nargin)); key_names = DataToCell(key_names); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, numel(key_names)); status = cellfun(@(x, y) obj.isKey(x, y), ... section_names, key_names, 'UniformOutput', 1); end %------------------------------------------------------------------ function [key_names, count_keys] = GetKeys(obj, section_name) %GetKeys - get names of all keys from given section % % Using: % key_names = GetKeys(section_name) % [key_names, count_keys] = GetKeys(section_name) % % Input: % section_name - name of section % % Output: % key_names - cell array with the names of keys % count_keys - number of keys in given section % ------------------------------------------------------------- error(nargchk(2, 2, nargin)); section_name = obj.validateSectionName(section_name); [key_names, count_keys] = obj.getKeys(section_name); end %------------------------------------------------------------------ function [status, tf_set_values] = ... AddKeys(obj, section_name, key_names, key_values, value_formats) %AddKeys - add keys in a end given section % % Using: % status = AddKeys(section_name, key_names) % status = AddKeys(section_name, key_names, key_values) % status = AddKeys(section_name, key_names, key_values, value_formats) % [status, tf_set_values] = AddKeys(...) % % Input: % section_name -- name of section % key_names -- names of keys % key_values -- values of keys (optional) % value_formats -- % % Output: % status -- 1 (true): Success, status - 0 (false): Failed % tf_set_values -- 1 (true): Success, status - 0 (false): Failed % ------------------------------------------------------------- error(nargchk(3, 5, nargin)); key_names = DataToCell(key_names); num_of_keys = numel(key_names); if (nargin < 5) value_formats = PadDataToCell('', num_of_keys); end if (nargin < 4) key_values = PadDataToCell('', num_of_keys); end key_values = DataToCell(key_values); value_formats = DataToCell(value_formats); CheckEqualNumberElems(key_names, key_values); CheckEqualNumberElems(key_values, value_formats); key_values = ValidateValues(key_values); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, num_of_keys); [status, tf_set_values] = cellfun(@(a, b, c, d) obj.addKey(a, b, c, d), ... section_names, key_names, key_values, value_formats, 'UniformOutput', 1); end %------------------------------------------------------------------ function [status, tf_set_values] = InsertKeys(obj, ... section_name, key_positions, key_names, key_values, value_formats) %InsertKeys - insert keys into the specified positions in a given section % % Using: % status = InsertKeys(section_name, key_positions, key_names) % status = InsertKeys(section_name, key_positions, key_names, key_values) % status = InsertKeys(section_name, key_positions, key_names, key_values, value_formats) % [status, tf_set_values] = InsertKeys(...) % % Input: % section_name -- name of section % key_positions -- positions of keys in section % key_names -- names of keys % key_values -- values of keys (optional) % value_formats -- % % Output: % status - 1 (true): Success, status - 0 (false): Failed % tf_set_values - 1 (true): Success, status - 0 (false): Failed % ------------------------------------------------------------- error(nargchk(4, 6, nargin)); key_positions = DataToCell(key_positions); key_names = DataToCell(key_names); num_of_keys = numel(key_names); CheckEqualNumberElems(key_positions, key_names); if (nargin < 6) value_formats = PadDataToCell('', num_of_keys); end if (nargin < 5) key_values = PadDataToCell('', num_of_keys); end key_values = DataToCell(key_values); value_formats = DataToCell(value_formats); CheckEqualNumberElems(key_names, key_values); CheckEqualNumberElems(key_values, value_formats); key_values = ValidateValues(key_values); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, num_of_keys); [status, tf_set_values] = ... cellfun(@(a, b, c, d, e) obj.insertKey(a, b, c, d, e), ... section_names, key_positions, key_names, ... key_values, value_formats, 'UniformOutput', true); end %------------------------------------------------------------------ function status = RemoveKeys(obj, section_name, key_names) %RemoveKeys - remove the keys from a given section % % Using: % status = RemoveKeys(section_name, key_names) % % Input: % section_name - name of section % key_names - names of keys % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(3, 3, nargin)); key_names = DataToCell(key_names); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, numel(key_names)); status = cellfun(@(a, b) obj.removeKey(a, b), ... section_names, key_names, 'UniformOutput', true); end %------------------------------------------------------------------ function status = RenameKeys(obj, section_name, old_key_names, new_key_names) %RenameKeys - rename the keys in a given section % % Using: % status = RenameKeys(section_name, old_key_names, new_key_names) % % Input: % section_name - name of section % old_key_names - old names of keys % new_key_names - new names of keys % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(4, 4, nargin)); old_key_names = DataToCell(old_key_names); new_key_names = DataToCell(new_key_names); CheckEqualNumberElems(old_key_names, new_key_names); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, numel(old_key_names)); status = cellfun(@(a, b, c) obj.renameKey(a, b, c), ... section_names, old_key_names, ... new_key_names, 'UniformOutput', true); end %------------------------------------------------------------------ function [values, status] = GetValues(obj, section_name, key_names, default_values) %GetValues - get values of keys from given section % % Using: % values = GetValues(section_name, key_names) % values = GetValues(section_name, key_names, default_values) % % Input: % section_name -- name of given section % key_names -- names of given keys % default_values -- values of keys that are returned by default % % Output: % values -- cell array with the values of keys % status -- 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- narginchk(2, 4); % if (nargin < 2) % % get all values % sections = obj.GetSections(); % % values = {}; % status = []; % for i = 1:numel(sections) % [vals, tf] = obj.GetValues(sections{i}); % values = cat(1, values, vals); % status = cat(1, status, tf); % end % return; % end section_name = obj.validateSectionName(section_name); if (nargin < 3) % get all values from given section key_names = obj.getKeys(section_name); if isempty(key_names) values = {}; status = false; return; end end if iscell(key_names) is_cell = true; else is_cell = false; end key_names = DataToCell(key_names); if (nargin < 4) default_values = PadDataToCell([], numel(key_names)); end default_values = DataToCell(default_values); default_values = ValidateValues(default_values); CheckEqualNumberElems(key_names, default_values); section_names = PadDataToCell(section_name, numel(key_names)); [values, status] = cellfun(@(x, y, z) obj.getValue(x, y, z), ... section_names, key_names, default_values, 'UniformOutput', false); if (~is_cell) values = values{1}; end status = cell2mat(status); end %------------------------------------------------------------------ function status = SetValues(obj, section_name, key_names, key_values, value_formats) %SetValues - set values for given keys from given section % % Using: % status = SetValues(section_name, key_names, key_values) % status = SetValues(section_name, key_names, key_values, value_formats) % % Input: % section_name -- name of given section (must be string) % key_names -- names of given keys (must be cell array of strings or string) % key_values -- values of keys (must be cell array or one value) % value_formats -- % % Output: % status -- 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(4, 5, nargin)); key_names = DataToCell(key_names); num_of_keys = numel(key_names); if (nargin < 5) value_formats = PadDataToCell('', num_of_keys); end key_values = DataToCell(key_values); value_formats = DataToCell(value_formats); CheckEqualNumberElems(key_names, key_values); CheckEqualNumberElems(key_values, value_formats); key_values = ValidateValues(key_values); section_name = obj.validateSectionName(section_name); section_names = PadDataToCell(section_name, num_of_keys); status = cellfun(@(a, b, c, d) obj.setValue(a, b, c, d), ... section_names, key_names, key_values, value_formats, 'UniformOutput', true); end %------------------------------------------------------------------ function varargout = ToString(obj, section_name) %ToString - export configuration to string or display % % Using: % ToString() % ToString(section_name) % str = ToString(...) % % Input: % section_name - name of sections for export (optional) % % Output: % str - string with full or section configuration (optional) % ------------------------------------------------------------- %FIXME: ��������, ����� ������� ���� ����� �� ���������, �� ������� ������� error(nargchk(1, 2, nargin)); if (nargin < 2) is_full_export = true; else section_name = obj.validateSectionName(section_name); is_full_export = false; end if is_full_export count_str = obj.count_strings; indicies = 1:count_str; else first_index = getSectionIndex(obj, section_name); key_indicies = obj.getKeysIndexes(section_name); if isempty(key_indicies) last_index = first_index; else last_index = key_indicies(end); end indicies = first_index:last_index; end indicies_of_sect = obj.indicies_of_sections; config_data = obj.config_data_array; str = ''; conf_str = sprintf('\n'); for k = indicies if isempty(config_data{k,1}) if isempty(config_data{k,3}) str = sprintf('\n'); else comment_str = config_data{k,3}; str = sprintf('%s\n', comment_str); end elseif ~isempty(indicies_of_sect(indicies_of_sect == k)) if is_full_export if isempty(config_data{k,3}) section_str = config_data{k,1}; str = sprintf('%s\n', section_str); else section_str = config_data{k,1}; comment_str = config_data{k,3}; str = sprintf('%s %s\n', ... section_str, comment_str); end end elseif ~isempty(config_data{k,1}) && ... isempty(indicies_of_sect(indicies_of_sect == k)) if isempty(config_data{k,3}) key_str = config_data{k,1}; val_str = config_data{k,2}; str = sprintf('%s=%s\n', key_str, val_str); else key_str = config_data{k,1}; val_str = config_data{k,2}; comment_str = config_data{k,3}; str = sprintf('%s=%s %s\n', ... key_str, val_str, comment_str); end end conf_str = sprintf('%s%s', conf_str, str); end if (nargout == 0) fprintf(1, '%s\n', conf_str); elseif (nargout == 1) varargout{1} = conf_str(2:end); else error('Too many output arguments.') end end %------------------------------------------------------------------ function status = WriteFile(obj, file_name) %WriteFile - write to the configuration INI file on disk % % Using: % status = WriteFile(file_name) % % Input: % file_name - name of output INI file % % Output: % status - 1 (true) - success, 0 (false) - failed % ------------------------------------------------------------- error(nargchk(2, 2, nargin)); CheckIsString(file_name); fid = fopen(file_name, 'w'); if (fid ~= -1) str = obj.ToString(); fprintf(fid, '%s', str); fclose(fid); status = true; else status = false; return; end end end % public methods %---------------------------------------------------------------------- %====================================================================== methods (Access = 'private') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Private Methods %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %------------------------------------------------------------------ function num = nameToNumSection(obj, section_name) %nameToNumSection - get number of section section_names = obj.GetSections(); int_ind = find(strcmp(section_names, section_name)); if ~isempty(int_ind) % If the section is not unique, then choose the latest num = int_ind(end); else num = []; end end %------------------------------------------------------------------ function sect_index = getSectionIndex(obj, section_name) %getSectionIndex - get index of section in config data num = obj.nameToNumSection(section_name); sect_index = obj.indicies_of_sections(num); end %------------------------------------------------------------------ function [key_indicies, count_keys] = getKeysIndexes(obj, section_name) %getKeysIndexes - get keys indices from given section sect_num = obj.nameToNumSection(section_name); if isempty(sect_num) key_indicies = []; count_keys = 0; return; elseif (sect_num == obj.count_sections) key_indicies = ... obj.indicies_of_sections(sect_num)+1:obj.count_strings; else key_indicies = ... obj.indicies_of_sections(sect_num)+1:obj.indicies_of_sections(sect_num+1)-1; end indicies_of_empty = obj.indicies_of_empty_strings; empty_indicies = ismember(key_indicies, indicies_of_empty); % empty_indicies = cellfun('isempty', ... % obj.config_data_array(key_indicies, 1)); key_indicies(empty_indicies) = []; key_indicies = key_indicies(:); count_keys = length(key_indicies); end %------------------------------------------------------------------ function ind = getKeyIndex(obj, section_name, key_name) %getKeyIndex - get key index key_names = obj.getKeys(section_name); key_indicies = obj.getKeysIndexes(section_name); int_ind = strcmp(key_names, key_name); ind = key_indicies(int_ind); end %------------------------------------------------------------------ function updateSectionsInfo(obj) %updateSectionsInfo - update info about sections keys_data = obj.config_data_array(:,1); sect_indicies_cell = regexp(keys_data, '^\[.*\]$'); obj.indicies_of_sections = ... find(~cellfun('isempty', sect_indicies_cell)); obj.count_sections = length(obj.indicies_of_sections); end %------------------------------------------------------------------ function updateCountKeysInfo(obj) %UpdateCountKeys - update full number of keys obj.count_all_keys = ... obj.count_strings - obj.count_sections - obj.count_empty_strings; end %------------------------------------------------------------------ function updateEmptyStringsInfo(obj) %updateEmptyStringsInfo - update info about empty strings keys_data = obj.config_data_array(:,1); indicies_of_empty_cell = strcmp('', keys_data); obj.indicies_of_empty_strings = find(indicies_of_empty_cell); obj.count_empty_strings = length(obj.indicies_of_empty_strings); end %------------------------------------------------------------------ function updateCountStrings(obj) %updateCountStrings - update full number of sections obj.count_strings = size(obj.config_data_array, 1); end %------------------------------------------------------------------ function status = isUniqueKeyName(obj, section_name, key_name) %isUniqueKeyName - check whether the name of the key unique keys = obj.getKeys(section_name); status = ~any(strcmp(key_name, keys)); end %------------------------------------------------------------------ function status = isUniqueSectionName(obj, section_name) %isUniqueKeyName - check whether the name of the section a unique sections = obj.GetSections(); status = ~any(strcmp(section_name, sections)); end %------------------------------------------------------------------ function status = isSection(obj, section_name) %isSection - determine whether there is a section % section_names = obj.GetSections(); data = obj.config_data_array(:, 1); int_ind = find(strcmp(data, section_name), 1); if ~isempty(int_ind) status = true; else status = false; end end %------------------------------------------------------------------ function section_name = validateSectionName(obj, section_name) %validateSectionName - check the name of the section CheckIsString(section_name); section_name = section_name(:)'; section_name = strtrim(section_name); if ~isempty(section_name) sect_indicies_cell = ... regexp(section_name, '^\[.*\]$', 'once'); indicies_cell_comment = ... regexp(section_name, obj.comment_style, 'once'); if ~isempty(indicies_cell_comment) section_name = []; return; end if isempty(sect_indicies_cell) section_name = ['[', section_name, ']']; end else section_name = []; end end %------------------------------------------------------------------ function status = addSection(obj, section_name) %addSection - add section to end configuration status = obj.insertSection(obj.count_sections+1, section_name); end %------------------------------------------------------------------ function status = insertSection(obj, section_pos, section_name) %insertSection - insert section to given position CheckIsScalarPositiveInteger(section_pos); if (section_pos > obj.count_sections+1) section_pos = obj.count_sections+1; end if ~isempty(section_name) is_unique_sect = obj.isUniqueSectionName(section_name); if ~is_unique_sect status = false; return; end if (section_pos <= obj.count_sections && obj.count_sections > 0) sect_ind = obj.indicies_of_sections(section_pos); elseif (section_pos == 1 && obj.count_sections == 0) sect_ind = 1; obj.config_data_array = {}; elseif (section_pos == obj.count_sections+1) sect_ind = obj.count_strings+1; end new_data = cell(2,3); new_data(1,:) = {section_name, '', ''}; new_data(2,:) = {''}; obj.config_data_array = ... InsertCell(obj.config_data_array, sect_ind, new_data); obj.updateCountStrings(); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); status = true; else status = false; end end %------------------------------------------------------------------ function status = removeSection(obj, section_name) %removeSection - remove given section section_name = obj.validateSectionName(section_name); sect_num = obj.nameToNumSection(section_name); if ~isempty(sect_num) if (sect_num < obj.count_sections) first_ind = obj.indicies_of_sections(sect_num); last_ind = obj.indicies_of_sections(sect_num+1)-1; elseif (sect_num == obj.count_sections) first_ind = obj.indicies_of_sections(sect_num); last_ind = obj.count_strings; end obj.config_data_array(first_ind:last_ind,:) = []; obj.updateCountStrings(); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); obj.updateCountKeysInfo(); status = true; else status = false; end end %------------------------------------------------------------------ function status = renameSection(obj, old_section_name, new_section_name) %renameSection - rename given section old_section_name = obj.validateSectionName(old_section_name); new_section_name = obj.validateSectionName(new_section_name); sect_num = obj.nameToNumSection(old_section_name); if (~isempty(new_section_name) && ~isempty(sect_num)) sect_ind = obj.indicies_of_sections(sect_num); obj.config_data_array(sect_ind, 1) = {new_section_name}; status = true; else status = false; end end %------------------------------------------------------------------ function key_name = validateKeyName(obj, key_name) %validateKeyName - check the name of the key CheckIsString(key_name); key_name = key_name(:)'; key_name = strtrim(key_name); indicies_cell = regexp(key_name, '^\[.*\]$', 'once'); indicies_cell_comment = regexp(key_name, obj.comment_style, 'once'); if (isempty(key_name) || ~isempty(indicies_cell) || ... ~isempty(indicies_cell_comment)) key_name = ''; end end %------------------------------------------------------------------ function status = isKey(obj, section_name, key_name) %isKey - determine whether there is a key in a given section key_name = obj.validateKeyName(key_name); if ~isempty(key_name) status = ~obj.isUniqueKeyName(section_name, key_name); else status = false; end end %------------------------------------------------------------------ function [status, write_value] = ... addKey(obj, section_name, key_name, key_value, value_formats) %addKey - add key in a end given section [inds, count_keys] = obj.getKeysIndexes(section_name); [status, write_value] = obj.insertKey(section_name, ... count_keys+1, key_name, key_value, value_formats); end %------------------------------------------------------------------ function [status, set_status] = ... insertKey(obj, section_name, key_pos, key_name, key_value, value_formats) %insertKey - insert key into the specified position in a given section CheckIsScalarPositiveInteger(key_pos); set_status = false; key_name = obj.validateKeyName(key_name); sect_num = obj.nameToNumSection(section_name); if (~isempty(sect_num) && ~isempty(key_name)) is_unique_key = obj.isUniqueKeyName(section_name, key_name); if ~is_unique_key status = false; return; end [key_indicies, count_keys] = obj.getKeysIndexes(section_name); if (count_keys > 0) if (key_pos <= count_keys) insert_index = key_indicies(key_pos); elseif (key_pos > count_keys) insert_index = key_indicies(end) + 1; end else insert_index = obj.indicies_of_sections(sect_num) + 1; end new_data = {key_name, '', ''}; obj.config_data_array = InsertCell(obj.config_data_array, ... insert_index, new_data); obj.updateCountStrings(); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); obj.updateCountKeysInfo(); if ~isempty(key_value) set_status = obj.setValue(section_name, key_name, ... key_value, value_formats); end status = true; else status = false; end end %------------------------------------------------------------------ function status = removeKey(obj, section_name, key_name) %removeKey - remove the key from a given section key_name = obj.validateKeyName(key_name); sect_num = obj.nameToNumSection(section_name); [keys, count_keys] = obj.getKeys(section_name); if (~isempty(sect_num) && ~isempty(key_name) && count_keys > 0) is_unique_key = obj.isUniqueKeyName(section_name, key_name); if is_unique_key status = false; return; end status = find(strcmp(key_name, keys), 1, 'last'); key_indicies = obj.getKeysIndexes(section_name); key_index = key_indicies(status); obj.config_data_array(key_index, :) = []; obj.updateCountStrings(); obj.updateSectionsInfo(); obj.updateEmptyStringsInfo(); obj.updateCountKeysInfo(); status = true; else status = false; end end %------------------------------------------------------------------ function status = renameKey(obj, section_name, old_key_name, new_key_name) %renameKey - rename the key in a given section old_key_name = obj.validateKeyName(old_key_name); new_key_name = obj.validateKeyName(new_key_name); sect_num = obj.nameToNumSection(section_name); [keys, count_keys] = obj.getKeys(section_name); if (~isempty(sect_num) && ~isempty(old_key_name) && ... ~isempty(new_key_name) && count_keys > 0) is_unique_key = obj.isUniqueKeyName(section_name, old_key_name); if is_unique_key status = false; return; end status = find(strcmp(old_key_name, keys), 1, 'last'); key_indicies = obj.getKeysIndexes(section_name); key_index = key_indicies(status); obj.config_data_array{key_index, 1} = new_key_name; status = true; else status = false; end end %------------------------------------------------------------------ function status = setValue(obj, section_name, key_name, key_value, value_format) %setValue key_name = obj.validateKeyName(key_name); if ~obj.isSection(section_name) status = false; return; end if ~obj.isKey(section_name, key_name) status = false; return; end key_index = obj.getKeyIndex(section_name, key_name); if isempty(value_format) str_value = num2str(key_value); else value_format = ValidateValueFormat(value_format); str_value = num2str(key_value, value_format); end if (isvector(key_value) && isnumeric(key_value)) str_value = CorrectionNumericArrayStrings(str_value); end obj.config_data_array(key_index, 2) = {str_value}; status = true; end %------------------------------------------------------------------ function [key_value, status] = getValue(obj, ... section_name, key_name, default_value) %getValue - get key value status = false; if ~obj.isSection(section_name) key_value = default_value; return; end if ~obj.isKey(section_name, key_name) key_value = default_value; return; end key_index = obj.getKeyIndex(section_name, key_name); str_value = obj.config_data_array{key_index, 2}; key_value = ParseValue(str_value); status = true; end %------------------------------------------------------------------ function [key_names, count_keys] = getKeys(obj, section_name) %getKeys [key_indicies, count_keys] = obj.getKeysIndexes(section_name); if ~isempty(key_indicies) key_names = obj.config_data_array(key_indicies, 1); else key_names = {}; end end end % private methods %---------------------------------------------------------------------- end % classdef IniConfig %-------------------------------------------------------------------------- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Tools Functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %========================================================================== function [file_data, status] = GetDataFromFile(file_name) %GetDataFromFile - Get data from file fid = fopen(file_name, 'r'); if (fid ~= -1) file_data = textscan(fid, ... '%s', ... 'delimiter', '\n', ... 'endOfLine', '\r\n'); fclose(fid); status = true; file_data = file_data{1}; else status = false; file_data = {}; end end %-------------------------------------------------------------------------- %========================================================================== function config_data = ParseConfigData(file_data, comment_style) %ParseConfigData - parse data from the INI file % Select the comment in a separate array pat = sprintf('^[^%s]+', comment_style); comment_data = regexprep(file_data, pat, ''); % Deleting comments pat = sprintf('%s.*+$', comment_style); file_data = regexprep(file_data, pat, ''); % Select the key value in a separate array values_data = regexprep(file_data, '^.[^=]*.', ''); % Select the names of the sections and keys in a separate array keys_data = regexprep(file_data, '=.*$', ''); config_data = cell(size(file_data, 1), 3); config_data(:,1) = keys_data; config_data(:,2) = values_data; config_data(:,3) = comment_data; config_data = strtrim(config_data); end %-------------------------------------------------------------------------- %========================================================================== function value = ParseValue(value) %ParseValue - classify the data types and convert them % ����������, �������� �� ������ value �� �������� ������� start_idx = regexp(value, '[^\.\s-+,0-9ij]', 'once'); if ~isempty(start_idx) return; end num = StringToNumeric(value); if ~isnan(num) value = num; end end %-------------------------------------------------------------------------- %========================================================================== function num = StringToNumeric(str) %StringToNumeric - convert string to numeric data if isempty(str) num = NaN; return; end delimiter = ','; str = regexprep(str, '\s*,*\s*', delimiter); cells = textscan(str, '%s', 'delimiter', delimiter); cells = cells{:}'; num_cell = cellfun(@(x) str2double(x), cells, 'UniformOutput', false); is_nans = cellfun(@(x) isnan(x), num_cell, 'UniformOutput', true); if any(is_nans) num = NaN; else num = cell2mat(num_cell); end end %-------------------------------------------------------------------------- %========================================================================== function values = CorrectionNumericArrayStrings(values) %CorrectionNumericArrayStrings - correction strings of numeric arrays values = regexprep(values, '\s+', ', '); end %-------------------------------------------------------------------------- %========================================================================== function comment_style = ValidateCommentStyle(comment_style) %ValidateCommentStyle - validate style of comments if ~ischar(comment_style) error('Requires char input for comment style.') end end %-------------------------------------------------------------------------- %========================================================================== function key_values = ValidateValues(key_values) %ValidateValues - validate data of key values is_valid = cellfun(@(x) ... (isempty(x) | ischar(x) | (isnumeric(x) & isvector(x))), ... key_values, 'UniformOutput', true); if ~all(is_valid) error('Invalid type of one or more <%s>.', inputname(key_values)); end % transform key_values to vector-rows key_values = cellfun(@(x) x(:).', key_values, 'UniformOutput', 0); end %-------------------------------------------------------------------------- %========================================================================== function value_format = ValidateValueFormat(value_format) %ValidateValueFormat - CheckIsString(value_format); value_format = strtrim(value_format); valid_formats = 'd|i|u|f|e|g|E|G'; start_ind = regexp(value_format, ... ['^%\d*\.?\d*(', valid_formats, ')$'], 'once'); if isempty(start_ind) error('Invalid value format "%s".', value_format) end value_format = strrep(value_format, '%', '% '); end %-------------------------------------------------------------------------- %========================================================================== function CheckEqualNumberElems(input1, input2) %CheckEqualNumberElems - checking equal numbers of elements if (numel(input1) ~= numel(input2)) error(['Number of elements in the <%s> and ', ... '<%s> must be equal.'], inputname(1), inputname(2)) end end %-------------------------------------------------------------------------- %========================================================================== function CheckIsString(input_var) %CheckIsString if ~(ischar(input_var) && isvector(input_var)) error('<%s> must be a string.', inputname(1)) end end %-------------------------------------------------------------------------- %========================================================================== function CheckIsScalarPositiveInteger(input_var) %CheckIsScalarPositiveInteger if ~(isscalar(input_var) && isnumeric(input_var)) error('<%s> must be a scalar.', inputname(1)) end if (input_var < 1) error('<%s> must be a positive integer > 0.', inputname(1)) end end %-------------------------------------------------------------------------- %========================================================================== function cell_data = PadDataToCell(data, number_elems) %PadDataToCell - pad data to cell array cell_data = {data}; cell_data = cell_data(ones(1, number_elems), :); end %-------------------------------------------------------------------------- %========================================================================== function data_var = DataToCell(data_var) %DataToCell - convert data to cell array if ~iscell(data_var) data_var = {data_var}; else data_var = data_var(:); end end %-------------------------------------------------------------------------- %========================================================================== function B = InsertCell(C, i, D) %InsertCell - insert a new cell or several cells in a two-dimensional % array of cells on the index B = [C(1:i-1, :); D; C(i:end, :)]; end %--------------------------------------------------------------------------
github
RoboticsLabURJC/2017-tfm-alexandre-rodriguez-master
visualization.m
.m
2017-tfm-alexandre-rodriguez-master/2016-tfg-david-pascual-replicado/Net/visualization.m
5,298
utf_8
c0d9be2c88eb5d80e89618c3cf3e583a
# # Created on Mar 28, 2017 # # @author: dpascualhe # function benchmark(results_path) # This function reads and plots a variety of measures, which evaluate the neural # network performance, that have been saved like a structure (a Python # dictionary) into a .mat file. more off; results_path = file_in_loadpath(results_path); results_dict = load(results_path).metrics; if results_dict.("training") == "y" # Loss. figure('Units','normalized','Position',[0 0 1 1]); subplot(2,1,1) train_loss = results_dict.("training loss"); val_loss = results_dict.("validation loss"); new_val_loss = NaN(size(train_loss)); val_index = length(train_loss)/length(val_loss); for i = [val_index:val_index:length(train_loss); 1:length(val_loss)] if i(1) != 0 new_val_loss(i(1)) = val_loss(i(2)); endif endfor x = 1:length(train_loss); plot(x, train_loss, x, new_val_loss, "r.") set(gca,"ytick", 0:0.2:max(train_loss), "ygrid", "on"); title("Loss after each batch during training", "fontweight",... "bold", "fontsize", 15); h = legend("Training", "Validation", "location", "northeastoutside"); set (h, "fontsize", 15); xlabel("Batch number", "fontsize", 15); ylabel("Categorical crossentropy", "fontsize", 15); # Accuracy. subplot(2,1,2) train_acc = results_dict.("training accuracy"); val_acc = results_dict.("validation accuracy"); new_val_acc = NaN(size(train_acc)); for i = [val_index:val_index:length(train_acc); 1:length(val_acc)] if i(1) != 0 new_val_acc(i(1)) = val_acc(i(2)); endif endfor x = 1:length(train_acc); plot(x, train_acc, x, new_val_acc, "r.") set(gca,"ytick", 0:0.2:max(train_acc), "ygrid", "on"); title("Accuracy after each batch during training", "fontweight",... "bold", "fontsize", 15); h = legend("Training", "Validation", "location", "northeastoutside"); set (h, "fontsize", 15); xlabel("Batch number", "fontsize", 15); ylabel("Accuracy", "fontsize", 15); printf("=======================VALIDATION RESULTS=======================\n") printf("\nValidation loss (after each epoch):\n") for i = 1:length(val_loss) printf(" Epoch %2i: %1.5f\n", i, val_loss(i)) endfor printf("\nValidation accuracy (after each epoch):\n") for i = 1:length(val_acc) printf(" Epoch %2i: %1.5f\n", i, val_acc(i)) endfor endif # Precision. figure; subplot(2,1,1) precision = results_dict.("precision"); bar(precision) nb_classes = length(precision); set(gca,"ytick", 0:1/nb_classes:1, "ygrid", "on"); title("Test precision", "fontweight", "bold", "fontsize", 15); xlabel("Class", "fontsize", 15); ylabel("Precision", "fontsize", 15); # Recall. subplot(2,1,2) recall = results_dict.("recall"); bar(recall) set(gca,"ytick", 0:1/nb_classes:1, "ygrid", "on"); title("Test recall", "fontweight", "bold", "fontsize", 15); xlabel("Class", "fontsize", 15); ylabel("Recall", "fontsize", 15); # Confusion matrix. figure; conf_mat = results_dict.("confusion matrix"); new_conf_mat = NaN(size(conf_mat)+1); for i = 1:length(conf_mat) new_conf_mat(i, length(new_conf_mat)) = sum(conf_mat(i, :)); new_conf_mat(length(new_conf_mat), i) = sum(conf_mat(:, i)); endfor pred_samples = sum(new_conf_mat(1:length(conf_mat), length(new_conf_mat))); real_samples = sum(new_conf_mat(length(new_conf_mat), 1:length(conf_mat))); if pred_samples != real_samples printf("Number of predicted and real samples is not equal") endif new_conf_mat(1:size(conf_mat)(1), 1:size(conf_mat)(2)) = conf_mat; imagesc(double(new_conf_mat)); colormap(gray); thresh = max(new_conf_mat(:))/2; for i = 1:length(new_conf_mat) for j = 1:length(new_conf_mat) h = text(i, j, num2str(new_conf_mat(i, j)), "horizontalalignment",... "center", "verticalalignment", "middle"); if new_conf_mat(i, j) < thresh set(h, "Color", "white"); endif endfor j = 1; endfor title(strcat("Confusion matrix -> Samples = ", num2str(real_samples)),... "fontweight", "bold", "fontsize", 15); xlabel("Predicted", "fontsize", 15); ylabel("Real", "fontsize", 15); set(gca,"XTick", 1:1:(length(conf_mat)+1), "XTickLabel",{"0","1","2","3",... "4","5","6","7",... "8", "9", "TOTAL"}); set(gca,"YTick", 1:1:(length(conf_mat)+1), "YTickLabel",{"0","1","2","3",... "4","5","6","7",... "8", "9", "TOTAL"}); # We print the results. printf("\n==========================TEST RESULTS==========================\n") printf("\nPrecision:\n") for i = 1:length(precision) printf(" %2i: %1.5f\n", i, precision(i)) endfor printf("\nRecall:\n") for i = 1:length(recall) printf(" %2i: %1.5f\n", i, recall(i)) endfor printf("\nConfusion Matrix:\n") disp(conf_mat) printf(["\nTest loss:\n " num2str(results_dict.("loss"))]) printf(["\nTest accuracy:\n " num2str(results_dict.("accuracy")) "\n"]) endfunction
github
RoboticsLabURJC/2017-tfm-alexandre-rodriguez-master
comparison.m
.m
2017-tfm-alexandre-rodriguez-master/2016-tfg-david-pascual-replicado/Net/comparison.m
1,598
utf_8
890b5ddb42c5031d86793ea899acca87
# # Created on May 15, 2017 # # @author: dpascualhe # function comparison(path1, path2) more off; metrics_path1 = file_in_loadpath(path1); metrics_dict1 = load(metrics_path1).metrics; metrics_path2 = file_in_loadpath(path2); metrics_dict2 = load(metrics_path2).metrics; # Loss. figure('Units','normalized','Position',[0 0 1 1]); subplot(2,1,1) val_loss1 = metrics_dict1.("validation loss"); val_loss2 = metrics_dict2.("validation loss"); x1 = 1:0.001:length(val_loss1); x2 = 1:0.001:length(val_loss2); val_loss1 = interp1(val_loss1, x1); val_loss2 = interp1(val_loss2, x2); plot(x1, val_loss1, '.', x2, val_loss2, '.') set(gca,"ytick", 0:0.1:1, "ygrid", "on"); title("Validation loss", "fontweight", "bold", "fontsize", 15); h = legend("Patience=2", "Patience=5", "location", "northeastoutside"); set (h, "fontsize", 15); xlabel("Epoch number", "fontsize", 15); ylabel("Categorical crossentropy", "fontsize", 15); # Accuracy. subplot(2,1,2) val_acc1 = metrics_dict1.("validation accuracy"); val_acc2 = metrics_dict2.("validation accuracy"); x1 = 1:0.001:length(val_acc1); x2 = 1:0.001:length(val_acc2); val_acc1 = interp1(val_acc1, x1); val_acc2 = interp1(val_acc2, x2); plot(x1, val_acc1, ".", x2, val_acc2, ".") set(gca,"ytick", 0:0.1:1, "ygrid", "on"); title("Validation accuracy", "fontweight", "bold", "fontsize", 15); h = legend("Patience=2", "Patience=5", "location", "northeastoutside"); set (h, "fontsize", 15); xlabel("Epoch number", "fontsize", 15); ylabel("Accuracy", "fontsize", 15); endfunction
github
johnybang/AdaptiveFilter-LMS-master
AdaptiveFirTest.m
.m
AdaptiveFilter-LMS-master/Matlab/AdaptiveFirTest.m
2,335
utf_8
699c8f7afeffc369173cd9ce9b5e038e
classdef AdaptiveFirTest properties (Constant) Iterations = 5000; Weights = rand(30,1)*2 - 1; % random weights on interval [-1,1] StepSize = 0.3; DbEpsilon = 1e-40; end methods (Static) function Run() % generate uniform random noise on the interval [-1,1] noise = (2 * rand(AdaptiveFirTest.Iterations,1) - 1); % filter noise with test filter desired = filter(AdaptiveFirTest.Weights,1,noise); % Instantiate and run adaptive filter af = AdaptiveFir(zeros(size(AdaptiveFirTest.Weights)),... AdaptiveFirTest.StepSize); adaptiveOut = zeros(size(noise)); weightError = zeros(size(noise)); for j = 1:AdaptiveFirTest.Iterations adaptiveOut(j) = af.Run(noise(j),desired(j)); weightError(j) = norm(AdaptiveFirTest.Weights-af.Weights)^2; end misalignment = weightError/(norm(AdaptiveFirTest.Weights)^2); squaredError = (desired - adaptiveOut).^2; dbEps = AdaptiveFirTest.DbEpsilon; disp(['Final Misalignment = ', ... num2str(db(dbEps + misalignment(end),'power')) 'dB']) disp(['Final Squared Error = ', ... num2str(db(dbEps + squaredError(end),'power')) 'dB']) PlotResults(af.Weights,misalignment,squaredError); end end end % plotting function just for use by this file function PlotResults(adaptiveWeights,misalignment,squaredError) figure subplot(3,1,1) stem(AdaptiveFirTest.Weights,'xb','MarkerSize',8) hold on stem(adaptiveWeights,'or','MarkerSize',8) ylabel('Weight Value'),xlabel('Weight #') % legend('desired','adaptive','Location','Best') title(['Desired and Adaptive Weights after ' ... num2str(AdaptiveFirTest.Iterations) ' Iterations, StepSize = ' ... num2str(AdaptiveFirTest.StepSize)]) subplot(3,1,2) plot(db(misalignment,'power')) ylabel('dB'),xlabel('Iteration #') title('E[ || W_{desired} - W ||^2 / || W_{desired} ||^2 ] vs Iteration #') subplot(3,1,3) plot(db(squaredError,'power')) ylabel('dB'),xlabel('Iteration #') title('E[ ( desired - y )^2 ] vs Iteration #') end
github
nipunperera/seizureDetection-master
trainingWaveletFeatures.m
.m
seizureDetection-master/trainingWaveletFeatures.m
3,619
utf_8
bf89240c92578637b08cd4a75b843f07
%%---------------------Seizure detection in continuous EEG----------------- % In this method, seizure events are detected and classified using discrete % wavelet packet transform. % Seizure events of the ECG are identified by considering 4 second % intervals in the EEG signal. Prominent channels and the wavelet packet % are extracted by significance.m based on a one way ANOVA test % Prominent channels for the first patient % Channels 14, 15, 21, 22 % Corresponding wavelet packets 2, 2, 2, 2 clear %% Indices corresponding to seizure events seizureInd = [900*2+(749:759) 900*3+(367:373) 900*14+(433:443)... 900*15+(254:266) 900*17+(430:452)]; %% Preparing feature vector and targets featMatrix1 = generateFeatMat(0); featMatrix2 = generateFeatMat(10); featMatrix = cat(3, featMatrix1, featMatrix2); featMatrix2D = reshape(featMatrix, size(featMatrix, 1), ... size(featMatrix, 2)*size(featMatrix, 3)); % Preparing the training dataset and target vectors targetVectorNonSeiz = zeros(1, size(featMatrix2D, 2) - length(seizureInd))'; targetVectorSeiz = ones(1, length(seizureInd))'; featureVectorSeiz = featMatrix2D(:,seizureInd); featureVectorSeiz = featureVectorSeiz'; featureVectorNonSeiz = featMatrix2D; featureVectorNonSeiz(:,seizureInd) = []; featureVectorNonSeiz = featureVectorNonSeiz'; % Create and train SVM model % Randomly select 1000 samples from non-seizure data randSampleInd = randi(size(featureVectorNonSeiz, 1), 1, 1000); finalFeatureVector = [featureVectorSeiz;featureVectorNonSeiz(randSampleInd,:)]; finalTargetVector = [targetVectorSeiz;targetVectorNonSeiz(randSampleInd,:)]; SVMmodel = fitcsvm(finalFeatureVector, finalTargetVector, 'Standardize',... true,'KernelFunction','RBF','KernelScale','auto'); %% Read EEG Data for patient 01 (In blocks of 10 records) function featMatrix = generateFeatMat(index) parfor i = 1:10 fileName = sprintf('chb01/chb01_%d.edf', i+index); [~,records(:,:,i)] = edfread(fileName); end % Channels being used for detection chansOfInterest = [14 15 21 22]; waveletPkts = [2 2 2 2]; % Each channel is represented by a column for filtering data = permute(records(chansOfInterest,:,:), [2, 1, 3]); % Create low pass filter Fs = 256; % Sampling Frequency N = 50; % Order Fc = 25; % Cutoff Frequency DpassU = 0.01; % Upper Passband Ripple DpassL = 0.01; % Lower Passband Ripple DstopU = 0.0001; % Upper Stopband Attenuation DstopL = 0.0001; % Lower Stopband Attenuation % Calculate the coefficients using the FIRCLS function. b = fircls(N, [0 Fc Fs/2]/(Fs/2), [1 0], [1+DpassU DstopU], [1-DpassL ... -DstopL]); Hd = dfilt.dffir(b); LPFiltered = filter(Hd, data); records = permute(LPFiltered,[2 1 3]); wdSize = 1024; level = 5; wName = 'db4'; % featMatrix = ones(numFeat*size(records, 1), size(records, 2)/wdSize,... % size(records, 1)); % Matrix to store the features % % First dimension - WP Coeffs of each window % % Last dimension - Record Number % Extraction of features (Wavelet Packet Coefficients) for i = 1:size(records, 3) for j = 1:size(records, 2) / wdSize for k = 1:size(records, 1) signal = records(k,1 + (wdSize * (j - 1)):wdSize * j, i); wpt = wpdec(signal,level,wName); wpCoef = wpcoef(wpt, [level, waveletPkts(k) - 1]); featMatrix(k, j, i) = log(sqrt(mean(wpCoef.*wpCoef))); % featMatrix((2*k), j, i) = var(wpCoef); end end end end
github
nipunperera/seizureDetection-master
featExtractionWaveletOverlapping1.m
.m
seizureDetection-master/featExtractionWaveletOverlapping1.m
4,983
utf_8
058cc7f916d2cabfc5feea3428b9d150
%%---------------------Seizure detection in continuous EEG----------------- % In this method, seizure events are detected and classified using discrete % wavelet packet transform. % Seizure events of the ECG are identified by considering 4 second % intervals in the EEG signal. Prominent channels and the wavelet packet % are extracted by significance.m based on a one way ANOVA test % Prominent channels for the first patient % Channels 14, 15, 21, 22 % Corresponding wavelet packets 2, 2, 2, 2 % ----------------------------Seizure occurences--------------------------- % File Name: chb01_03.edf (Record 3) % Seizure Start Time: 2996 seconds - 2993 % Seizure End Time: 3036 seconds - 3033 % File Name: chb01_04.edf (Record 4) % Seizure Start Time: 1467 seconds - 1464 % Seizure End Time: 1494 seconds - 1491 % File Name: chb01_15.edf (Record 15) % Seizure Start Time: 1732 seconds - 1729 % Seizure End Time: 1772 seconds - 1769 % % File Name: chb01_16.edf (Record 16) % Seizure Start Time: 1015 seconds - 1012 % Seizure End Time: 1066 seconds - 1063 % File Name: chb01_18.edf (Record 18) % Seizure Start Time: 1720 seconds - 1717 % Seizure End Time: 1810 seconds - 1807 % File Name: chb01_21.edf (Record 21) % Seizure Start Time: 327 seconds - 324 % Seizure End Time: 420 seconds - 417 % File Name: chb01_26.edf (Record 26) % Seizure Start Time: 1862 seconds % Seizure End Time: 1963 seconds clear %% Indices corresponding to seizure events seizureInd = [3597*2+(2993:3033) 3597*3+(1464:1491) 3597*14+(1729:1769)... 3597*15+(1012:1063) 3597*17+(1717:1807)]; seizureInd = []; %% Preparing feature vector and targets featMatrix1 = generateFeatMat(19); %featMatrix2 = generateFeatMat(5); %featMatrix3 = generateFeatMat(10); %featMatrix4 = generateFeatMat(15); featMatrix = featMatrix1; %featMatrix = cat(3, featMatrix1, featMatrix2, featMatrix3, featMatrix4); featMatrix2D = reshape(featMatrix, size(featMatrix, 1), ... size(featMatrix, 2)*size(featMatrix, 3)); % Preparing the training dataset and target vectors targetVectorNonSeiz = zeros(1, size(featMatrix2D, 2) - length(seizureInd))'; targetVectorSeiz = ones(1, length(seizureInd))'; featureVectorSeiz = featMatrix2D(:,seizureInd); featureVectorSeiz = featureVectorSeiz'; featureVectorNonSeiz = featMatrix2D; featureVectorNonSeiz(:,seizureInd) = []; featureVectorNonSeiz = featureVectorNonSeiz'; % Create and train SVM model % Randomly select 3000 samples from non-seizure data randSampleInd = randi(size(featureVectorNonSeiz, 1), 1, 3000); finalFeatureVector = [featureVectorSeiz;featureVectorNonSeiz(randSampleInd,:)]; finalTargetVector = [targetVectorSeiz;targetVectorNonSeiz(randSampleInd,:)]; SVMmodel = fitcsvm(finalFeatureVector, finalTargetVector, 'Standardize',... true,'KernelFunction','RBF','KernelScale','auto'); %% Read EEG Data for patient 01 (In blocks of 10 records) function featMatrix = generateFeatMat(index) parfor i = 1:1 fileName = sprintf('chb01/chb01_%d.edf', i+index); [~,records(:,:,i)] = edfread(fileName); end % Channels being used for detection chansOfInterest = [14 15 21 22]; waveletPkts = [2 2 2 2]; % Each channel is represented by a column for filtering data = permute(records(chansOfInterest,:,:), [2, 1, 3]); % Create low pass filter Fs = 256; % Sampling Frequency N = 50; % Order Fc = 25; % Cutoff Frequency DpassU = 0.01; % Upper Passband Ripple DpassL = 0.01; % Lower Passband Ripple DstopU = 0.0001; % Upper Stopband Attenuation DstopL = 0.0001; % Lower Stopband Attenuation % Calculate the coefficients using the FIRCLS function. b = fircls(N, [0 Fc Fs/2]/(Fs/2), [1 0], [1+DpassU DstopU], [1-DpassL ... -DstopL]); Hd = dfilt.dffir(b); LPFiltered = filter(Hd, data); records = permute(LPFiltered,[2 1 3]); wdSize = 1024; level = 5; wName = 'db4'; % featMatrix = ones(numFeat*size(records, 1), size(records, 2)/wdSize,... % size(records, 1)); % Matrix to store the features % % First dimension - WP Coeffs of each window % % Last dimension - Record Number % Extraction of features (Wavelet Packet Coefficients) disp('Computing wavelet features...') for i = 1:size(records, 3) for j = 4:size(records, 2) / Fs if mod(j, 100) == 0 fprintf('%d seconds processed....\n', j); end for k = 1:size(records, 1) signal = records(k,1 + (Fs * (j - 4)):Fs * j, i); wpt = wpdec(signal,level,wName); wpCoef = wpcoef(wpt, [level, waveletPkts(k) - 1]); featMatrix(k, j-3, i) = log(sqrt(mean(wpCoef.*wpCoef))); % featMatrix((2*k), j, i) = var(wpCoef); end end end end
github
nipunperera/seizureDetection-master
patient02TrainingWavelet.m
.m
seizureDetection-master/patient02TrainingWavelet.m
4,893
utf_8
e3dd2d35ddb8408ec50bcdd5e3b9bd1a
%%---------------------Seizure detection in continuous EEG----------------- % In this method, seizure events are detected and classified using discrete % wavelet packet transform. % Seizure events of the ECG are identified by considering 4 second % intervals in the EEG signal. Prominent channels and the wavelet packet % are extracted by significance.m based on a one way ANOVA test % ----------------------------Seizure occurences--------------------------- % File Name: chb03_01.edf % File Start Time: 13:23:36 % File End Time: 14:23:36 % Number of Seizures in File: 1 % Seizure Start Time: 362 seconds - 91 % Seizure End Time: 414 seconds - 104 % File Name: chb03_02.edf % File Start Time: 14:23:39 % File End Time: 15:23:39 % Number of Seizures in File: 1 % Seizure Start Time: 731 seconds - 183 % Seizure End Time: 796 seconds - 199 % File Name: chb03_03.edf % File Start Time: 15:23:47 % File End Time: 16:23:47 % Number of Seizures in File: 1 % Seizure Start Time: 432 seconds - 108 % Seizure End Time: 501 seconds - 125 % File Name: chb03_04.edf % File Start Time: 16:23:54 % File End Time: 17:23:54 % Number of Seizures in File: 1 % Seizure Start Time: 2162 seconds - 541 % Seizure End Time: 2214 seconds - 554 % File Name: chb03_05.edf % File Start Time: 01:51:23 % File End Time: 2:51:23 % Number of Seizures in File: 1 % Seizure Start Time: 1982 seconds - 496 % Seizure End Time: 2029 seconds - 507 % File Name: chb03_06.edf % File Start Time: 04:51:45 % File End Time: 5:51:45 % Number of Seizures in File: 1 % Seizure Start Time: 1725 seconds - 437 % Seizure End Time: 1778 seconds - 445 % Prominent channels for the first patient % Channels 2, 19, 20, 21 % Corresponding wavelet packets 2, 2, 2, 2 clear % Indices corresponding to seizure events seizureInd = [(91:104) 900*1+(183:199) 900*2+(108:125) 900*3+(541:554)... 900*4+(496:507) 900*5+(437:445)]; %% Preparing feature vector and targets featMatrix1 = generateFeatMat(0); featMatrix2 = generateFeatMat(10); featMatrix = cat(3, featMatrix1, featMatrix2); featMatrix2D = reshape(featMatrix, size(featMatrix, 1), ... size(featMatrix, 2)*size(featMatrix, 3)); % Preparing the training dataset and target vectors targetVectorNonSeiz = zeros(1, size(featMatrix2D, 2) - length(seizureInd))'; targetVectorSeiz = ones(1, length(seizureInd))'; featureVectorSeiz = featMatrix2D(:,seizureInd); featureVectorSeiz = featureVectorSeiz'; featureVectorNonSeiz = featMatrix2D; featureVectorNonSeiz(:,seizureInd) = []; featureVectorNonSeiz = featureVectorNonSeiz'; % Create and train SVM model % Randomly select 1000 samples from non-seizure data randSampleInd = randi(size(featureVectorNonSeiz, 1), 1, 1000); finalFeatureVector = [featureVectorSeiz;featureVectorNonSeiz(randSampleInd,:)]; finalTargetVector = [targetVectorSeiz;targetVectorNonSeiz(randSampleInd,:)]; SVMmodel = fitcsvm(finalFeatureVector, finalTargetVector, 'Standardize',... true,'KernelFunction','RBF','KernelScale','auto'); %% Read EEG Data for patient 01 (In blocks of 10 records) function featMatrix = generateFeatMat(index) parfor i = 1:10 fileName = sprintf('chb03/chb03_%d.edf', i+index); [~,records(:,:,i)] = edfread(fileName); end % Channels being used for detection chansOfInterest = [2 19 20 21]; waveletPkts = [2 2 2 2]; % Each channel is represented by a column for filtering data = permute(records(chansOfInterest,:,:), [2, 1, 3]); % Create low pass filter Fs = 256; % Sampling Frequency N = 50; % Order Fc = 25; % Cutoff Frequency DpassU = 0.01; % Upper Passband Ripple DpassL = 0.01; % Lower Passband Ripple DstopU = 0.0001; % Upper Stopband Attenuation DstopL = 0.0001; % Lower Stopband Attenuation % Calculate the coefficients using the FIRCLS function. b = fircls(N, [0 Fc Fs/2]/(Fs/2), [1 0], [1+DpassU DstopU], [1-DpassL ... -DstopL]); Hd = dfilt.dffir(b); LPFiltered = filter(Hd, data); records = permute(LPFiltered,[2 1 3]); wdSize = 1024; level = 5; wName = 'db4'; % featMatrix = ones(numFeat*size(records, 1), size(records, 2)/wdSize,... % size(records, 1)); % Matrix to store the features % % First dimension - WP Coeffs of each window % % Last dimension - Record Number % Extraction of features (Wavelet Packet Coefficients) for i = 1:size(records, 3) for j = 1:size(records, 2) / wdSize for k = 1:size(records, 1) signal = records(k,1 + (wdSize * (j - 1)):wdSize * j, i); wpt = wpdec(signal,level,wName); wpCoef = wpcoef(wpt, [level, waveletPkts(k) - 1]); featMatrix(k, j, i) = log(sqrt(mean(wpCoef.*wpCoef))); % featMatrix((2*k), j, i) = var(wpCoef); end end end end
github
nipunperera/seizureDetection-master
trainingSpectralFeatures.m
.m
seizureDetection-master/trainingSpectralFeatures.m
4,687
utf_8
eb0c83735c5e22e41a50d46d3fb0228b
close all clear % ----------------------------Seizure occurences--------------------------- % File Name: chb01_03.edf (Record 3) % Seizure Start Time: 2996 seconds - 749 % Seizure End Time: 3036 seconds - 759 % File Name: chb01_04.edf (Record 4) % Seizure Start Time: 1467 seconds - 367 % Seizure End Time: 1494 seconds - 373 % File Name: chb01_15.edf (Record 15) % Seizure Start Time: 1732 seconds - 433 % Seizure End Time: 1772 seconds - 443 % % File Name: chb01_16.edf (Record 16) % Seizure Start Time: 1015 seconds - 254 % Seizure End Time: 1066 seconds - 266 % File Name: chb01_18.edf (Record 18) % Seizure Start Time: 1720 seconds - 430 % Seizure End Time: 1810 seconds - 452 % File Name: chb01_21.edf (Record 21) % Seizure Start Time: 327 seconds - 82 % Seizure End Time: 420 seconds - 105 % File Name: chb01_26.edf (Record 26) % Seizure Start Time: 1862 seconds - 465 % Seizure End Time: 1963 seconds - 491 % Extraction of spatial features % Prominent channels are selected % Fp1-F7, Fp1-Fp3, F3-C3, Fp2-F4, F4-C4, C4-P4, P4-O2, Fp2-F8, F8-T8, % T8-P8, P8-O2, Fz-Cz, Cz-Pz, FT9-FT10, FT10-T8, T8-P8 % 1, 5, 6, 9, 10, 1, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23 % Indices corresponding to seizure events seizureInd = [900*2+(749:759) 900*3+(367:373) 900*17+(430:452)]; % 900*3+(367:373) 900*15+(254:266) 900*17+(430:452) % Reading data and generating feature matrices featureVector1 = generateSpectralFeat(0); featureVector2 = generateSpectralFeat(10); featureVector = [featureVector1 featureVector2]; %% Preparing the training dataset and target vectors targetVectorNonSeiz = zeros(1, size(featureVector, 2) - length(seizureInd))'; targetVectorSeiz = ones(1, length(seizureInd))'; featureVectorSeiz = featureVector(:,seizureInd); featureVectorSeiz = featureVectorSeiz'; featureVectorNonSeiz = featureVector; featureVectorNonSeiz(:,seizureInd) = []; featureVectorNonSeiz = featureVectorNonSeiz'; %% Create and train SVM model % Randomly select 1000 samples from non-seizure data randSampleInd = randi(size(featureVectorNonSeiz, 1), 1, 1000); finalFeatureVector = [featureVectorSeiz;featureVectorNonSeiz(randSampleInd,:)]; finalTargetVector = [targetVectorSeiz;targetVectorNonSeiz(randSampleInd,:)]; SVMmodel = fitcsvm(finalFeatureVector, finalTargetVector, 'Standardize',... true,'KernelFunction','RBF','KernelScale','auto'); %% % Testing new data newX = featureVector(:,1:900)'; [label,score] = predict(SVMmodel,newX); % %% Visualization of data points % figure; % plot(featureVector(seizureInd(1:18), 1),featureVector(seizureInd(1:18), 17),'r.','MarkerSize',10) % hold on % plot(featureVector(101:200, 1),featureVector(101:200, 17),'b.','MarkerSize',10) % xlim([0 10000]) % ylim([0 500]) % % xlabel('Energy of 0 - 16Hz Band') % ylabel('Energy of 16 - 25Hz Band') % legend('Seizure', 'Non-Seizure') %% Read EEG Data for patient 01 (In blocks of 10 records) % This functions reads blocks of 10 records and a low pass filtering is % applied and only channels of interest specified by the user is considered function featureVector = generateSpectralFeat(index) parfor i = 1:10 fileName = sprintf('chb01/chb01_%d.edf', i+index); [~,records(:,:,i)] = edfread(fileName); end % Prominent channels for patient 01 promChannels = [1, 5, 6, 9, 10, 1, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23]; % Each channel is represented by a column for filtering data = permute(records, [2, 1, 3]); data = data(:,promChannels,:); % Create low pass filter Fs = 256; % Sampling Frequency N = 50; % Order Fc = 25; % Cutoff Frequency DpassU = 0.01; % Upper Passband Ripple DpassL = 0.01; % Lower Passband Ripple DstopU = 0.0001; % Upper Stopband Attenuation DstopL = 0.0001; % Lower Stopband Attenuation % Calculate the coefficients using the FIRCLS function. b = fircls(N, [0 Fc Fs/2]/(Fs/2), [1 0], [1+DpassU DstopU], [1-DpassL ... -DstopL]); Hd = dfilt.dffir(b); LPFiltered = filter(Hd, data); featureVector = []; % Perform Short Time Fourier Transform for time intervals of 4s for i = 1:size(LPFiltered, 3) for j = 1:size(LPFiltered, 1)/1024 [pxx, f] = periodogram(LPFiltered(1 + (1024*(j - 1)):1024*j,:,i),... [], [], 256); power0_16 = bandpower(pxx(1:65, :), f(1:65), 'psd'); power16_25 = bandpower(pxx(65:101, :), f(65:101), 'psd'); powerVector = [power0_16 power16_25]; featureVector = [featureVector powerVector']; end end end
github
nipunperera/seizureDetection-master
patient02TrainingSpectral.m
.m
seizureDetection-master/patient02TrainingSpectral.m
4,762
utf_8
568a4f5382b9546887b87c36c8eb0e42
close all clear % ----------------------------Seizure occurences--------------------------- % File Name: chb03_01.edf % File Start Time: 13:23:36 % File End Time: 14:23:36 % Number of Seizures in File: 1 % Seizure Start Time: 362 seconds - 91 % Seizure End Time: 414 seconds - 104 % File Name: chb03_02.edf % File Start Time: 14:23:39 % File End Time: 15:23:39 % Number of Seizures in File: 1 % Seizure Start Time: 731 seconds - 183 % Seizure End Time: 796 seconds - 199 % File Name: chb03_03.edf % File Start Time: 15:23:47 % File End Time: 16:23:47 % Number of Seizures in File: 1 % Seizure Start Time: 432 seconds - 108 % Seizure End Time: 501 seconds - 125 % File Name: chb03_04.edf % File Start Time: 16:23:54 % File End Time: 17:23:54 % Number of Seizures in File: 1 % Seizure Start Time: 2162 seconds - 541 % Seizure End Time: 2214 seconds - 554 % File Name: chb03_05.edf % File Start Time: 01:51:23 % File End Time: 2:51:23 % Number of Seizures in File: 1 % Seizure Start Time: 1982 seconds - 496 % Seizure End Time: 2029 seconds - 507 % File Name: chb03_06.edf % File Start Time: 04:51:45 % File End Time: 5:51:45 % Number of Seizures in File: 1 % Seizure Start Time: 1725 seconds - 437 % Seizure End Time: 1778 seconds - 445 % Extraction of spatial features % Prominent channels are selected % 1, 2, 3, 4, 5, 6, 9, 13, 19, 20, 21, 22, 23 % Indices corresponding to seizure events seizureInd = [(91:104) 900*1+(183:199) 900*2+(108:125) 900*3+(541:554)... 900*4+(496:507) 900*5+(437:445)]; % Reading data and generating feature matrices featureVector1 = generateSpectralFeat(0); featureVector2 = generateSpectralFeat(10); featureVector = [featureVector1 featureVector2]; %% Preparing the training dataset and target vectors targetVectorNonSeiz = zeros(1, size(featureVector, 2) - length(seizureInd))'; targetVectorSeiz = ones(1, length(seizureInd))'; featureVectorSeiz = featureVector(:,seizureInd); featureVectorSeiz = featureVectorSeiz'; featureVectorNonSeiz = featureVector; featureVectorNonSeiz(:,seizureInd) = []; featureVectorNonSeiz = featureVectorNonSeiz'; %% Create and train SVM model % Randomly select 1000 samples from non-seizure data randSampleInd = randi(size(featureVectorNonSeiz, 1), 1, 1000); finalFeatureVector = [featureVectorSeiz;featureVectorNonSeiz(randSampleInd,:)]; finalTargetVector = [targetVectorSeiz;targetVectorNonSeiz(randSampleInd,:)]; SVMmodel = fitcsvm(finalFeatureVector, finalTargetVector, 'Standardize',... true,'KernelFunction','RBF','KernelScale','auto'); %% % Testing new data % newX = featureVector(:,1:900)'; % [label,score] = predict(SVMmodel,newX); % %% Visualization of data points % figure; % plot(featureVector(seizureInd(1:18), 1),featureVector(seizureInd(1:18), 17),'r.','MarkerSize',10) % hold on % plot(featureVector(101:200, 1),featureVector(101:200, 17),'b.','MarkerSize',10) % xlim([0 10000]) % ylim([0 500]) % % xlabel('Energy of 0 - 16Hz Band') % ylabel('Energy of 16 - 25Hz Band') % legend('Seizure', 'Non-Seizure') %% Read EEG Data for patient 01 (In blocks of 10 records) % This functions reads blocks of 10 records and a low pass filtering is % applied and only channels of interest specified by the user is considered function featureVector = generateSpectralFeat(index) parfor i = 1:10 fileName = sprintf('chb03/chb03_%d.edf', i+index); [~,records(:,:,i)] = edfread(fileName); end % Prominent channels for patient 01 promChannels = [1, 2, 3, 4, 5, 6, 9, 13, 19, 20, 21, 22, 23]; % Each channel is represented by a column for filtering data = permute(records, [2, 1, 3]); data = data(:,promChannels,:); % Create low pass filter Fs = 256; % Sampling Frequency N = 50; % Order Fc = 25; % Cutoff Frequency DpassU = 0.01; % Upper Passband Ripple DpassL = 0.01; % Lower Passband Ripple DstopU = 0.0001; % Upper Stopband Attenuation DstopL = 0.0001; % Lower Stopband Attenuation % Calculate the coefficients using the FIRCLS function. b = fircls(N, [0 Fc Fs/2]/(Fs/2), [1 0], [1+DpassU DstopU], [1-DpassL ... -DstopL]); Hd = dfilt.dffir(b); LPFiltered = filter(Hd, data); featureVector = []; % Perform Short Time Fourier Transform for time intervals of 4s for i = 1:size(LPFiltered, 3) for j = 1:size(LPFiltered, 1)/1024 [pxx, f] = periodogram(LPFiltered(1 + (1024*(j - 1)):1024*j,:,i),... [], [], 256); power0_16 = bandpower(pxx(1:65, :), f(1:65), 'psd'); power16_25 = bandpower(pxx(65:101, :), f(65:101), 'psd'); powerVector = [power0_16 power16_25]; featureVector = [featureVector powerVector']; end end end
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_ORIG_DIRECT.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_ORIG_DIRECT.m
164
utf_8
43ae70342fc7484716698f445981512b
% NLOPT_GN_ORIG_DIRECT: Original DIRECT version (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ORIG_DIRECT val = 6;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_BOBYQA.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_BOBYQA.m
189
utf_8
15ba6db5057c8907343184908e0ecf06
% NLOPT_LN_BOBYQA: BOBYQA bound-constrained optimization via quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_BOBYQA val = 34;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT.m
137
utf_8
915b9f3f3a223d681a10bfaa80318309
% NLOPT_GN_DIRECT: DIRECT (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT val = 0;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_MMA.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_MMA.m
155
utf_8
7e4519526e6353452086a1cf929b12ad
% NLOPT_LD_MMA: Method of Moving Asymptotes (MMA) (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_MMA val = 24;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT_L.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L.m
143
utf_8
ae13ecf48a1ee6d222444643f59c2993
% NLOPT_GN_DIRECT_L: DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L val = 1;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_VAR1.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_VAR1.m
168
utf_8
45d4388965becdc240350c73a2779757
% NLOPT_LD_VAR1: Limited-memory variable-metric, rank 1 (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_VAR1 val = 13;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT_L_NOSCAL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_NOSCAL.m
166
utf_8
c20477ea33399f3311ea6e533dc347ae
% NLOPT_GN_DIRECT_L_NOSCAL: Unscaled DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_NOSCAL val = 4;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_COBYLA.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_COBYLA.m
189
utf_8
2c95152f70105c8ca20929fba67d12a2
% NLOPT_LN_COBYLA: COBYLA (Constrained Optimization BY Linear Approximations) (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_COBYLA val = 25;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_AUGLAG_EQ.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_AUGLAG_EQ.m
189
utf_8
5432778c9b81b5fdcfb98ca1bbbd6486
% NLOPT_LN_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_AUGLAG_EQ val = 32;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT_L_RAND.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_RAND.m
164
utf_8
2135dc3891b556738f41c2a35009b227
% NLOPT_GN_DIRECT_L_RAND: Randomized DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_RAND val = 2;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_MLSL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_MLSL.m
169
utf_8
93ab4e64e2760c4ca201fada42cb05c3
% NLOPT_GN_MLSL: Multi-level single-linkage (MLSL), random (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_MLSL val = 20;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GD_MLSL_LDS.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GD_MLSL_LDS.m
180
utf_8
7f41fd0094df543c2e45280f86c0b87b
% NLOPT_GD_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, derivative) % % See nlopt_minimize for more information. function val = NLOPT_GD_MLSL_LDS val = 23;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_AUGLAG_EQ.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_AUGLAG_EQ.m
186
utf_8
41b81c30c553388e2ff1b6b1fb681618
% NLOPT_LD_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_AUGLAG_EQ val = 33;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_CCSAQ.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_CCSAQ.m
214
utf_8
33892896fe470090edb583b50b9e7d93
% NLOPT_LD_CCSAQ: CCSA (Conservative Convex Separable Approximations) with simple quadratic approximations (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_CCSAQ val = 41;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_AUGLAG.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_AUGLAG.m
155
utf_8
2d7d515e911b5d0277490940a47f333e
% NLOPT_LD_AUGLAG: Augmented Lagrangian method (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_AUGLAG val = 31;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT_L_RAND_NOSCAL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_RAND_NOSCAL.m
187
utf_8
3287f776b0f2ac5e3495c2a4c95ba4e7
% NLOPT_GN_DIRECT_L_RAND_NOSCAL: Unscaled Randomized DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_RAND_NOSCAL val = 5;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_SBPLX.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_SBPLX.m
196
utf_8
c99ee02eb277898e9c509dd359740680
% NLOPT_LN_SBPLX: Sbplx variant of Nelder-Mead (re-implementation of Rowan's Subplex) (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_SBPLX val = 29;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_ISRES.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_ISRES.m
173
utf_8
2c12964785aed0828a5ac17fc416f5be
% NLOPT_GN_ISRES: ISRES evolutionary constrained optimization (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ISRES val = 35;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_VAR2.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_VAR2.m
168
utf_8
5ba0bd034c240547765a0fd4ce90c825
% NLOPT_LD_VAR2: Limited-memory variable-metric, rank 2 (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_VAR2 val = 14;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_AUGLAG_EQ.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_AUGLAG_EQ.m
182
utf_8
2f8b59b483a4f2621264c7de9df58365
% NLOPT_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_AUGLAG_EQ val = 37;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_NELDERMEAD.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_NELDERMEAD.m
168
utf_8
219928fdd3fc8317d321f9f0535d550f
% NLOPT_LN_NELDERMEAD: Nelder-Mead simplex algorithm (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NELDERMEAD val = 28;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_NEWUOA.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_NEWUOA.m
185
utf_8
b318db6792885a5d23dcfd5b28fdc507
% NLOPT_LN_NEWUOA: NEWUOA unconstrained optimization via quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NEWUOA val = 26;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_CRS2_LM.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_CRS2_LM.m
185
utf_8
9a171159b83c77e07256a24704139d8a
% NLOPT_GN_CRS2_LM: Controlled random search (CRS2) with local mutation (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_CRS2_LM val = 19;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_PRAXIS.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_PRAXIS.m
153
utf_8
c7d354e0602183d0d3a7ff71641ab7b4
% NLOPT_LN_PRAXIS: Principal-axis, praxis (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_PRAXIS val = 12;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_SLSQP.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_SLSQP.m
164
utf_8
e767cc9cde902065e67a31664a571819
% NLOPT_LD_SLSQP: Sequential Quadratic Programming (SQP) (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_SLSQP val = 40;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_G_MLSL_LDS.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_G_MLSL_LDS.m
187
utf_8
dfafcdb44b43c59aa5e4d5b73542dc50
% NLOPT_G_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_G_MLSL_LDS val = 39;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_TNEWTON.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON.m
152
utf_8
5e00532d1e34e85f395f6ace048d7d64
% NLOPT_LD_TNEWTON: Truncated Newton (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON val = 15;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_LBFGS_NOCEDAL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_LBFGS_NOCEDAL.m
184
utf_8
7b1380ab03a2272b6e3f1c0f49e4babf
% NLOPT_LD_LBFGS_NOCEDAL: original NON-FREE L-BFGS code by Nocedal et al. (NOT COMPILED) % % See nlopt_minimize for more information. function val = NLOPT_LD_LBFGS_NOCEDAL val = 10;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GD_STOGO.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GD_STOGO.m
137
utf_8
1b374b07cc8dd1fd43998c8f60f49267
% NLOPT_GD_STOGO: StoGO (global, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_GD_STOGO val = 8;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_AUGLAG.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_AUGLAG.m
151
utf_8
a4a6ef23ad60f4ceab26caae4276c02d
% NLOPT_AUGLAG: Augmented Lagrangian method (needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_AUGLAG val = 36;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GD_MLSL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GD_MLSL.m
166
utf_8
3735615f01a5de64ba710bfa7b7eba3a
% NLOPT_GD_MLSL: Multi-level single-linkage (MLSL), random (global, derivative) % % See nlopt_minimize for more information. function val = NLOPT_GD_MLSL val = 21;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_DIRECT_NOSCAL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_NOSCAL.m
160
utf_8
9f11af031bd7ca9c9348de64f7169482
% NLOPT_GN_DIRECT_NOSCAL: Unscaled DIRECT (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_NOSCAL val = 3;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_AUGLAG.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_AUGLAG.m
158
utf_8
ec49cb21c2b454870a401a1c5afd1058
% NLOPT_LN_AUGLAG: Augmented Lagrangian method (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_AUGLAG val = 30;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_ESCH.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_ESCH.m
130
utf_8
6cad4da90ce4145ad2b1dafcf286286f
% NLOPT_GN_ESCH: ESCH evolutionary strategy % % See nlopt_minimize for more information. function val = NLOPT_GN_ESCH val = 42;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_G_MLSL.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_G_MLSL.m
173
utf_8
fd60012f2c05bdeb027ee6dee44175fb
% NLOPT_G_MLSL: Multi-level single-linkage (MLSL), random (global, needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_G_MLSL val = 38;
github
PECAplus/PECAplus_cmd_line-master
nlopt_minimize_constrained.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/nlopt_minimize_constrained.m
5,174
utf_8
2093a6be53db585559168905f1fc1e4a
% Usage: [xopt, fmin, retcode] = nlopt_minimize_constrained % (algorithm, f, f_data, % fc, fc_data, lb, ub, % xinit, stop) % % Minimizes a nonlinear multivariable function f(x, f_data{:}), subject % to nonlinear constraints described by fc and fc_data (see below), where % x is a row vector, returning the optimal x found (xopt) along with % the minimum function value (fmin = f(xopt)) and a return code (retcode). % A variety of local and global optimization algorithms can be used, % as specified by the algorithm parameter described below. lb and ub % are row vectors giving the upper and lower bounds on x, xinit is % a row vector giving the initial guess for x, and stop is a struct % containing termination conditions (see below). % % This function is a front-end for the external routine % nlopt_minimize_constrained in the free NLopt nonlinear-optimization % library, which is a wrapper around a number of free/open-source % optimization subroutines. More details can be found on the NLopt % web page (ab-initio.mit.edu/nlopt) and also under % 'man nlopt_minimize_constrained' on Unix. % % f should be a handle (@) to a function of the form: % % [val, gradient] = f(x, ...) % % where x is a row vector, val is the function value f(x), and gradient % is a row vector giving the gradient of the function with respect to x. % The gradient is only used for gradient-based optimization algorithms; % some of the algorithms (below) are derivative-free and only require % f to return val (its value). f can take additional arguments (...) % which are passed via the argument f_data: f_data is a cell array % of the additional arguments to pass to f. (Recall that cell arrays % are specified by curly brackets { ... }. For example, pass f_data={} % for functions that require no additional arguments.) % % A few of the algorithms (below) support nonlinear constraints, % in particular NLOPT_LD_MMA and NLOPT_LN_COBYLA. These (if any) % are specified by fc and fc_data. fc is a cell array of % function handles, and fc_data is a cell array of cell arrays of the % corresponding arguments. Both must have the same length m, the % number of nonlinear constraints. That is, fc{i} is a handle % to a function of the form: % % [val, gradient] = fc(x, ...) % % (where the gradient is only used for gradient-based algorithms), % and the ... arguments are given by fc_data{i}{:}. % % If you have no nonlinear constraints, i.e. fc = fc_data = {}, then % it is equivalent to calling the the nlopt_minimize() function, % which omits the fc and fc_data arguments. % % stop describes the termination criteria, and is a struct with a % number of optional fields: % stop.ftol_rel = fractional tolerance on function value % stop.ftol_abs = absolute tolerance on function value % stop.xtol_rel = fractional tolerance on x % stop.xtol_abs = row vector of absolute tolerances on x components % stop.fmin_max = stop when f < fmin_max is found % stop.maxeval = maximum number of function evaluations % stop.maxtime = maximum run time in seconds % stop.verbose = > 0 indicates verbose output % Minimization stops when any one of these conditions is met; any % condition that is omitted from stop will be ignored. WARNING: % not all algorithms interpret the stopping criteria in exactly the % same way, and in any case ftol/xtol specify only a crude estimate % for the accuracy of the minimum function value/x. % % The algorithm should be one of the following constants (name and % interpretation are the same as for the C function). Names with % _G*_ are global optimization, and names with _L*_ are local % optimization. Names with _*N_ are derivative-free, while names % with _*D_ are gradient-based algorithms. Algorithms: % % NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, % NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, % NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, % NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, % NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, % NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, % NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, % NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, % NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, % NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, % NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX % % For more information on individual algorithms, see their individual % help pages (e.g. "help NLOPT_LN_SBPLX"). function [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, fc, fc_data, lb, ub, xinit, stop) opt = stop; if (isfield(stop, 'minf_max')) opt.stopval = stop.minf_max; end opt.algorithm = algorithm; opt.min_objective = @(x) f(x, f_data{:}); opt.lower_bounds = lb; opt.upper_bounds = ub; for i = 1:length(fc) opt.fc{i} = @(x) fc{i}(x, fc_data{i}{:}); end [xopt, fmin, retcode] = nlopt_optimize(opt, xinit);
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LN_NEWUOA_BOUND.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LN_NEWUOA_BOUND.m
207
utf_8
67ca43d03f5347c97069a86e3e73a7e4
% NLOPT_LN_NEWUOA_BOUND: Bound-constrained optimization via NEWUOA-based quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NEWUOA_BOUND val = 27;
github
PECAplus/PECAplus_cmd_line-master
nlopt_minimize.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/nlopt_minimize.m
3,978
utf_8
f71b68688b460e0440ff89bdf086d2a7
% Usage: [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub, % xinit, stop) % % Minimizes a nonlinear multivariable function f(x, f_data{:}), where % x is a row vector, returning the optimal x found (xopt) along with % the minimum function value (fmin = f(xopt)) and a return code (retcode). % A variety of local and global optimization algorithms can be used, % as specified by the algorithm parameter described below. lb and ub % are row vectors giving the upper and lower bounds on x, xinit is % a row vector giving the initial guess for x, and stop is a struct % containing termination conditions (see below). % % This function is a front-end for the external routine nlopt_minimize % in the free NLopt nonlinear-optimization library, which is a wrapper % around a number of free/open-source optimization subroutines. More % details can be found on the NLopt web page (ab-initio.mit.edu/nlopt) % and also under 'man nlopt_minimize' on Unix. % % f should be a handle (@) to a function of the form: % % [val, gradient] = f(x, ...) % % where x is a row vector, val is the function value f(x), and gradient % is a row vector giving the gradient of the function with respect to x. % The gradient is only used for gradient-based optimization algorithms; % some of the algorithms (below) are derivative-free and only require % f to return val (its value). f can take additional arguments (...) % which are passed via the argument f_data: f_data is a cell array % of the additional arguments to pass to f. (Recall that cell arrays % are specified by curly brackets { ... }. For example, pass f_data={} % for functions that require no additional arguments.) % % stop describes the termination criteria, and is a struct with a % number of optional fields: % stop.ftol_rel = fractional tolerance on function value % stop.ftol_abs = absolute tolerance on function value % stop.xtol_rel = fractional tolerance on x % stop.xtol_abs = row vector of absolute tolerances on x components % stop.fmin_max = stop when f < fmin_max is found % stop.maxeval = maximum number of function evaluations % stop.maxtime = maximum run time in seconds % stop.verbose = > 0 indicates verbose output % Minimization stops when any one of these conditions is met; any % condition that is omitted from stop will be ignored. WARNING: % not all algorithms interpret the stopping criteria in exactly the % same way, and in any case ftol/xtol specify only a crude estimate % for the accuracy of the minimum function value/x. % % The algorithm should be one of the following constants (name and % interpretation are the same as for the C function). Names with % _G*_ are global optimization, and names with _L*_ are local % optimization. Names with _*N_ are derivative-free, while names % with _*D_ are gradient-based algorithms. Algorithms: % % NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, % NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, % NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, % NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, % NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, % NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, % NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, % NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, % NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, % NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, % NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX % % For more information on individual algorithms, see their individual % help pages (e.g. "help NLOPT_LN_SBPLX"). function [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub, xinit, stop) [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, {}, {}, lb, ub, xinit, stop);
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_ORIG_DIRECT_L.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_ORIG_DIRECT_L.m
170
utf_8
d61c095f05bf7fd4fbbf2ddbe22c58a4
% NLOPT_GN_ORIG_DIRECT_L: Original DIRECT-L version (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ORIG_DIRECT_L val = 7;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_TNEWTON_RESTART.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_RESTART.m
184
utf_8
a482ddde1f6d6b386a3810fc142829a2
% NLOPT_LD_TNEWTON_RESTART: Truncated Newton with restarting (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_RESTART val = 16;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_TNEWTON_PRECOND_RESTART.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_PRECOND_RESTART.m
215
utf_8
1082f147b249cc1f7e564aa3b2462048
% NLOPT_LD_TNEWTON_PRECOND_RESTART: Preconditioned truncated Newton with restarting (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_PRECOND_RESTART val = 18;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_TNEWTON_PRECOND.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_PRECOND.m
183
utf_8
167e47e5e372152ffba7552308e1193f
% NLOPT_LD_TNEWTON_PRECOND: Preconditioned truncated Newton (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_PRECOND val = 17;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GD_STOGO_RAND.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GD_STOGO_RAND.m
170
utf_8
fea04c6327afd49e02ff536330527f60
% NLOPT_GD_STOGO_RAND: StoGO with randomized search (global, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_GD_STOGO_RAND val = 9;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_LD_LBFGS.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_LD_LBFGS.m
160
utf_8
02936ac48fc420cd73b5a6848808dd68
% NLOPT_LD_LBFGS: Limited-memory BFGS (L-BFGS) (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_LBFGS val = 11;
github
PECAplus/PECAplus_cmd_line-master
NLOPT_GN_MLSL_LDS.m
.m
PECAplus_cmd_line-master/include_dir/nlopt-2.4.2/octave/NLOPT_GN_MLSL_LDS.m
183
utf_8
0fb34e2ebed6204b06925782f5fc2417
% NLOPT_GN_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_MLSL_LDS val = 22;
github
chili-epfl/openpose-master
classification_demo.m
.m
openpose-master/3rdparty/caffe/matlab/demo/classification_demo.m
5,466
utf_8
45745fb7cfe37ef723c307dfa06f1b97
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to the Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % and what versions are installed. % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab code for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to your Matlab search PATH in order to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
Coderx7/Caffe_1.0_Windows-master
classification_demo.m
.m
Caffe_1.0_Windows-master/matlab/demo/classification_demo.m
5,466
utf_8
45745fb7cfe37ef723c307dfa06f1b97
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to the Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % and what versions are installed. % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab code for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to your Matlab search PATH in order to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
ekalkan/P-PHASE-PICKER-master
PphasePicker.m
.m
P-PHASE-PICKER-master/PphasePicker.m
10,196
utf_8
821c0c9d6e38fdaf48b1805ae6430f61
function [loc, snr_db] = PphasePicker(x, dt, type, pflag, Tn, xi, nbins, o) % AN AUTOMATIC P-PHASE ARRIVAL TIME PICKER % % Computes P-phase arrival time in windowed digital single-component % acceleration or broadband velocity record without requiring threshold % settings. Returns P-phase arrival time in second, and signal-to-noise % ratio in decibel. Input waveform must be an evenly spaced vector. % PLEASE READ IMPORTANT NOTES BELOW % % Syntax: % [loc, snr_db] = PphasePicker(x, dt, type, pflag, Tn, xi, nbins, o) % % Input (required): % x = raw broadband velocity or acceleration data in % single-column format % dt = sampling interval in second (e.g., 0.005) % type = 'sm' or 'SM' for acceleration waveform (default bandwidth % = 0.1-20 Hz) % 'wm' or 'WM' for velocity waveform (default bandwidth 7-90 % Hz) % 'na' or 'NA' no bandpass filtering % % pflag = 'Y' or 'y' for plotting waveform with P-wave arrival time % marked % 'N' or 'n' for no plot % % Input (optional): % Tn = undamped natural period in second (default is 0.01 for % records sampled with 100 samples-per-second or larger; for % records with lower than 100 samples-per-second default % is 0.1 s) % xi = damping ratio (default is 0.6) % nbins = histogram bin size (default is 2/dt for % strong-motion acceleration and broadband velocity % waveforms; regional or teleseismic records may need % different values of bin size for better picking results) % o = 'to_peak' to take segment of waveform from beginning to % absolute peak value (recommended for fast processing) % 'full' to take full waveform % % Output: % loc = P-phase arrival time in second % snr_db = signal-to-noise ratio in decibel % % Update(s): % 2016/09/09 statelevel command is hard coded % 2016/09/09 no bandpass filter option is added % 2017/01/05 input normalized to prevent numerical instability % as a result of very low amplitude input % 2017/02/17 included signal-to-noise ratio computation % % Example: % Let x be a single component strong-motion acceleration waveform % with 200 sample per second (dt = 0.005). The input for % P-phase picking will be % % [loc, snr_db] = PphasePicker(x, 0.005, 'SM', 'Y'); % % or with optional parameters of plotting waveform (pflag = % 'Y', Tn = 0.01, damping ratio = 0.7, histogram bin size = % 400 and by taking segment of waveform from beginning to its % peak is % % [loc, snr_db] = PphasePicker(x, 0.005, 'SM', 'Y', 0.01, 0.7, 400, 'to_peak') % % IMPORTANT NOTE- 1: User may need to change default corner frequencies of % Butterworth bandpass filter as appropriate to noise level of the input % signal. % % IMPORTANT NOTE- 2: If sampling rate of input signal is lower than 100 % samples-per-second, use Tn = 0.1 s instead of 0.01 s to avoid numerical % errors. If Tn is not specified, default values will be used based on % the sampling rate. % % Comment blocks and equation references in this function correspond to % the following publication: % % Kalkan, E. (2016). "An automatic P-phase arrival time picker", Bull. of % Seismol. Soc. of Am., 106, No. 3, doi: 10.1785/0120150111 % % THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED % WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN % NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY DIRECT, INDIRECT, % INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, % BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS % OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND % ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR % TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE % USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH % DAMAGE. % % Written by Dr. Erol Kalkan, P.E. ([email protected]) % $Revision: 16.0 $ $Date: 2017/02/17 18:14:00 $ if nargin > 2 validateattributes(x,{'double'},{'real','finite','vector'}, ... 'PphasePicker','X'); validateattributes(dt,{'double'},{'real','finite','scalar'}, ... 'PphasePicker','DT'); validatestring(type,{'sm','wm','na','SM','WM','NA'},'PphasePicker','INPUT'); else error('Not enough inputs. See help documentation.'); end if nargin > 3 validatestring(pflag,{'Y','y','N','n'},'PphasePicker','pflag'); else pflag = 'n'; end if nargin > 4 validateattributes(Tn,{'double'},{'real','finite','scalar'}, ... 'PphasePicker','TN'); validateattributes(xi,{'double'},{'real','finite','scalar','<',1}, ... 'PphasePicker','XI'); validateattributes(nbins,{'double'},{'real','finite','scalar','>',1}, ... 'PphasePicker','NBINS'); else if dt <= 0.01; Tn = 0.01; nbins = round(2/dt); else Tn = 0.1; nbins = 200; end xi = 0.6; end if nargin > 7 validatestring(o,{'to_peak','full'},'PphasePicker','O'); else o = 'to_peak'; end % User may modify the filter corner frequencies (flp and fhp) for more % accurate picking switch type % Weak-motion low- and high-pass corner frequencies in Hz case {'wm','WM'} filtflag = 1; %flp = 7; fhp = 90; flp = 0.09; fhp = 5; %flp = 1; fhp = 2; % Strong-motion low- and high-pass corner frequencies in Hz case {'sm','SM'} filtflag = 1; flp = 0.1; fhp = 1.5; % No bandpass filter will be applied case {'na','NA'} filtflag = 0; x_d = detrend(x); % detrend waveform end x_org = x; % Normalize input to prevent numerical instability from very low amplitudes x = x/max(abs(x)); % Bandpass filter and detrend waveform if filtflag ~= 0; x_f = bandpass(x,flp,fhp,dt,4); x_d = detrend(x_f); end switch o case {'to_peak'} ind_peak = find(abs(x_d) == max(abs(x_d))); xnew = x_d(1:ind_peak); otherwise xnew = x_d; end % Construct a fixed-base viscously damped SDF oscillator omegan = 2*pi/Tn; % natural frequency in radian/second C = 2*xi*omegan; % viscous damping term K = omegan^2; % stiffness term y(:,1) = [0;0]; % response vector % Solve second-order ordinary differential equation of motion A = [0 1; -K -C]; Ae = expm(A*dt); AeB = A\(Ae-eye(2))*[0;1]; for k = 2:length(xnew); y(:,k) = Ae*y(:,k-1) + AeB*xnew(k); end veloc = (y(2,:))'; % relative velocity of mass Edi = 2*xi*omegan*veloc.^2; % integrand of viscous damping energy % Apply histogram method R = statelevel(Edi,nbins); locs = find(Edi > R(1)); indx = find(xnew(1:locs(1)-1).*xnew(2:locs(1)) < 0); % get zero crossings TF = isempty(indx); % Update first onset if TF == 0; loc = indx(end)*dt; else R = statelevel(Edi,ceil(nbins/2)); % try nbins/2 locs = find(Edi > R(1)); indx = find(xnew(1:locs(1)-1).*xnew(2:locs(1)) < 0); % get zero crossings TF = isempty(indx); if TF == 0; loc = indx(end)*dt; else loc = -1; end end % Compute SNR if ~loc == -1; snr_db = -1 else snr_db = SNR(x,x(1:loc/dt)); end fprintf('P-phase arrival time in second = %5.2f\n',loc); fprintf('SNR in decibel = %5.2f\n',snr_db); if pflag == 'Y' || pflag == 'y'; fsz = 16; lw = 1; % font size and line width figure set(gcf,'position',[300 283 1000 250]); set(gca,'TickLength',[.0025 .0025]); set(gca,'fontname','times','fontsize',fsz); T = [0:dt:(numel(x)-1)*dt]; plot(T,x_org,'k','LineWidth',lw); grid on; if loc ~= -1; line([loc loc],[ylim],'Color','r','LineWidth',lw); end xlabel('Time, s','FontSize',[fsz+2],'fontname','times','Color','k'); ylabel('Amplitude','FontSize',[fsz+2],'fontname','times','Color','k'); end return function [levels, histogram, bins] = statelevel(y,n) ymax = max(y); ymin = min(y)-eps; % Compute Histogram idx = ceil(n * (y-ymin)/(ymax-ymin)); idx = idx(idx>=1 & idx<=n); histogram = zeros(n, 1); for i=1:numel(idx) histogram(idx(i)) = histogram(idx(i)) + 1; end % Compute Center of Each Bin ymin = min(y); Ry = ymax-ymin; dy = Ry/n; bins = ymin + ((1:n)-0.5)*dy; % Compute State Levels iLowerRegion = find(histogram > 0, 1, 'first'); iUpperRegion = find(histogram > 0, 1, 'last'); iLow = iLowerRegion(1); iHigh = iUpperRegion(1); % Define the lower and upper histogram regions halfway % between the lowest and highest nonzero bins. lLow = iLow; lHigh = iLow + floor((iHigh - iLow)/2); uLow = iLow + floor((iHigh - iLow)/2); uHigh = iHigh; % Upper and lower histograms lHist = histogram(lLow:lHigh, 1); uHist = histogram(uLow:uHigh, 1); levels = zeros(1,2); [~, iMax] = max(lHist(2:end)); [~, iMin] = max(uHist); levels(1) = ymin + dy * (lLow + iMax(1) - 1.5); levels(2) = ymin + dy * (uLow + iMin(1) - 1.5); % Lowest histogram bin numbers for upper and lower histograms lHist_final = (lLow + iMax(1) - 1); uHist_final = (uLow + iMin(1) - 1); return function [x_f] = bandpass(c, flp, fhi, dt, n) % Butterworth Acausal Bandpass Filter % % Syntax: % x_f = bandpass(c, flp, fhi, dt, n) % % Input: % x = input time series % flp = low-pass corner frequency in Hz % fhi = high-pass corner frequency in Hz % dt = sampling interval in second % n = order % % Output: % [x_f] = bandpass filtered signal fnq = 1/(2*dt); % Nyquist frequency Wn = [flp/fnq fhi/fnq]; % Butterworth bandpass non-dimensional frequency [b,a] = butter(n,Wn); x_f = filtfilt(b,a,c); return function [r] = SNR(signal,noise) % Compute signal-to-noise ratio aps = mean(signal.^2); % average power of signal apn = mean(noise.^2); % average power of noise r = 10*log10(aps/apn); % signal-to-noise ratio in decibel return
github
ISET/iset3d-v3-master
autoArrangeFigures.m
.m
iset3d-v3-master/scripts/psf/autoArrangeFigures.m
2,693
utf_8
9ff956614f21a392f0554ec3c62a4984
function autoArrangeFigures(NH, NW, monitor_id) % INPUT : % NH : number of grid of vertical direction % NW : number of grid of horizontal direction % OUTPUT : % % get every figures that are opened now and arrange them. % % autoArrangeFigures selects automatically Monitor1. % If you are dual(or more than that) monitor user, I recommend to set wide % monitor as Monitor1. % % if you want arrange automatically, type 'autoArrangeFigures(0,0)' or 'autoArrangeFigures()'. % But maximum number of figures for automatic mode is 27. % % if you want specify grid for figures, give numbers for parameters. % but if your grid size is smaller than required one for accommodating % all figures, this function changes to automatic mode and if more % figures are opend than maximum number, then it gives error. % % Notes % + 2017.1.20 use monitor id(Adam Danz's idea) % % leejaejun, Koreatech, Korea Republic, 2014.12.13 % [email protected] if nargin < 2 NH = 0; NW = 0; monitor_id = 1; end task_bar_offset = [30 50]; %% N_FIG = NH * NW; if N_FIG == 0 autoArrange = 1; else autoArrange = 0; end figHandle = sortFigureHandles(findobj('Type','figure')); n_fig = size(figHandle,1); if n_fig <= 0 warning('figures are not found'); return end screen_sz = get(0,'MonitorPositions'); screen_sz = screen_sz(monitor_id, :); scn_w = screen_sz(3) - task_bar_offset(1); scn_h = screen_sz(4) - task_bar_offset(2); scn_w_begin = screen_sz(1) + task_bar_offset(1); scn_h_begin = screen_sz(2) + task_bar_offset(2); if autoArrange==0 if n_fig > N_FIG autoArrange = 1; warning('too many figures than you told. change to autoArrange'); else nh = NH; nw = NW; end end if autoArrange == 1 grid = [2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4; 3 3 3 3 3 3 3 3 4 4 4 5 5 5 5 5 5 5 5 6 6 6 7 7 7 7 7]'; if n_fig > length(grid) warning('too many figures(maximum = %d)',length(grid)) return end if scn_w > scn_h nh = grid(n_fig,1); nw = grid(n_fig,2); else nh = grid(n_fig,2); nw = grid(n_fig,1); end end fig_width = scn_w/nw; fig_height = scn_h/nh; fig_cnt = 1; for i=1:1:nh for k=1:1:nw if fig_cnt>n_fig return end fig_pos = [scn_w_begin+fig_width*(k-1) ... scn_h_begin+scn_h-fig_height*i ... fig_width ... fig_height]; set(figHandle(fig_cnt),'OuterPosition',fig_pos); fig_cnt = fig_cnt + 1; end end end function figSorted = sortFigureHandles(figs) [tmp, idx] = sort([figs.Number]); figSorted = figs(idx); end
github
ISET/iset3d-v3-master
s_piReadRenderLF.m
.m
iset3d-v3-master/scripts/pbrtV2/s_piReadRenderLF.m
4,285
utf_8
da68d5c9ccbb68e19f3fa1cc518e6894
% s_piReadRenderLF % *** DEPRECATED **** % % ****** No longer working ******** % % I think this was based on the original Andy Lin microlens code, not the % newer Michael Mara version. Should be updated. % % % Implements a light field camera system with an array of microlenses over a % sensor. Converts the OI into a sensor, the sensor into a rendered image, and % then uses D. Dansereau's toolbox to produce a small video of the images seen % through the different sub-images. % % Time N Rays NMicroLens Nsubpixels % 64 64 7,7 % 30 s 64 128 7,7 % 150 s 128 128 7,7 % 103 s 16 128 7,7 % % TL/BW SCIEN, 2017 %% Initialize ISET and Docker ieInit; if ~piDockerExists, piDockerConfig; end %% Specify the pbrt scene file and its dependencies % We organize the pbrt files with its includes (textures, brdfs, spds, geometry) % in a single directory. %{ fname = fullfile(piRootPath,'data','teapot-area','teapot-area-light.pbrt'); if ~exist(fname,'file'), error('File not found'); end % Read the main scene pbrt file. Return it as a recipe thisR = piRead(fname); %} thisR = piRecipeDefault('scene name','teapot'); %% Modify the recipe, thisR, to adjust the rendering % Configure the light field camera thisR.set('camera','light field'); thisR.set('n microlens',[128 128]); thisR.set('n subpixels',[7, 7]); thisR.set('microlens',1); % Not sure what on or off means. Investigate. thisR.set('aperture',50); % LF cameras need a big aperture thisR.set('rays per pixel',16); % Governs quality of rendering thisR.set('light field film resolution',true); % Sets film resolution % Move the camera far enough away to get a decent focus. thisR.set('object distance',35); % In mm thisR.set('autofocus',true); % thisR.get('film resolution') %% Write out modified PBRT file [p,n,e] = fileparts(fname); thisR.set('outputFile',fullfile(piRootPath,'local','teapot',[n,e])); piWrite(thisR); %% Render with the Docker container [oi,results] = piRender(thisR,'mean illuminance',10); % Show it in ISET ieAddObject(oi); oiWindow; oiSet(oi,'gamma',0.5); %% Create a sensor % Make a sensor so that each pixel is aligned with a single sample % in the OI. Then produce the sensor data. The sensor has a standard % Bayer color filter array. sensor = sensorCreate('light field',oi); sensor = sensorSet(sensor,'exp time',0.01); % 10 ms. % Compute the sensor responses and show sensor = sensorCompute(sensor,oi); % ieAddObject(sensor); sensorWindow('scale',1); %% Use the image processor to demosaic (bilinear) the sensor data ip = ipCreate; ip = ipCompute(ip,sensor); ieAddObject(ip); ipWindow; %% Pack the sensor rgb image into the lightfield structure % This is the format used by Don Dansereau's light field toolbox nPinholes = thisR.get('n microlens'); % Or pinholes lightfield = ip2lightfield(ip,'pinholes',nPinholes,'colorspace','srgb'); %% Show little video if you like %{ % Click on window and press ESC to end LFDispVidCirc(lightfield.^(1/2.2)); %} %% Display the center pixel image %{ r = ceil(size(lightfield,1)/2); c = ceil(size(lightfield,2)/2); img = squeeze(lightfield(r,c,:,:,:).^(1/2.2)); vcNewGraphWin; imagesc(img); truesize; axis off %} %% White balance %{ % We should pull this out into a separate script, experiment, % and run it on saved values to speed up debugging. % This should get us how to scale each pixel so white is white [cMatrix,sensorW,oiW] = piWhiteField(thisR); % ieAddObject(oiW); oiWindow; % ieAddObject(sensorW); sensorImageWindow; % vcNewGraphWin; imagesc(cMatrix); truesize % This function should be added to ISET, I think, to correct function sensorW = sensorScale(sensor,varargin); % % Syntax (typical?) might be: % sensor = sensorScale(sensor,'volts',cMatrix); % This is what it would do v = sensorGet(sensor,'volts'); lst = (cMatrix > 1/10); % Don't want to scale by more than this v(lst) = v(lst) ./ cMatrix(lst); % vcNewGraphWin; imagesc(v); truesize; % Then replace the volts sensorW = sensorSet(sensor,'volts',v); sensorW = sensorSet(sensorW,'name','white field'); end ieAddObject(sensorW); sensorWindow('scale',1); % If you want to continue along ... sensor = sensorW; % %}
github
ISET/iset3d-v3-master
piRecipeRectify.m
.m
iset3d-v3-master/utilities/piRecipeRectify.m
6,556
utf_8
c633e5dc10b6bf17c426d55927a872a9
function thisR = piRecipeRectify(thisR,varargin) % Move the camera and objects so that the origin is 0 and the view % direction is the z-axis % % Description % % Inputs % thisR % % Optional key/val pairs % rotate - Logical to supress rotation. Default is true % % Return % thisR % % See piRotate for the rotation matrices for the three axes % See also % % Examples %{ thisR = piRecipeDefault('scene name','simple scene'); thisR.set('fov',60); thisR.set('film resolution',[160 160]); piAssetGeometry(thisR); piWRS(thisR); thisR = piRecipeRectify(thisR); piAssetGeometry(thisR); piWRS(thisR); %} %% Parser p = inputParser; p.addRequired('thisR',@(x)(isa(x,'recipe'))); p.addParameter('rotate',true,@islogical); p.parse(thisR,varargin{:}); %% Check if we need to insert a rectify node % Identify all the children of root idChildren = thisR.get('asset','root','children'); if numel(idChildren) == 1 % If there is only one node, and it is called rectify just get it tmp = split(thisR.get('asset',idChildren,'name'),'_'); if isequal(tmp{end},'rectify') % No need to insert a rectify node. It is there already. idRectify = thisR.get('asset','rectify','id'); else % Insert a rectify node below the root and before all other nodes rectNode = piAssetCreate('type','branch'); rectNode.name = 'rectify'; thisR.set('asset','root','add',rectNode); idRectify = thisR.get('asset','rectify','id'); % Place all the previous children under rectify for ii=1:numel(idChildren) thisR.set('asset',idChildren(ii),'parent',idRectify); end end else % There was more than one node. % Insert a rectify node below the root and before all other nodes rectNode = piAssetCreate('type','branch'); rectNode.name = 'rectify'; thisR.set('asset','root','add',rectNode); idRectify = thisR.get('asset','rectify','id'); % Place all the previous children under rectify for ii=1:numel(idChildren) thisR.set('asset',idChildren(ii),'parent',idRectify); end end % thisR.show(); thisR.show('objects') %% Translation % The camera is handled separately from the objects from = thisR.get('from'); if ~isequal(from,[0,0,0]) % Move the camera. Maybe there is already a set for this? thisR.set('from',[0,0,0]); to = thisR.get('to'); thisR.set('to',to - from); % I think this may be doing something more complicated than what I % want. % piCameraTranslate(thisR,'xshift',-from(1), ... % 'yshift',-from(2), ... % 'zshift',-from(3)); % Set the translation of the rectify node piAssetSet(thisR,idRectify,'translation',-from); % thisR.get('asset','rectify','translate') % piAssetGeometry(thisR); % piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); end %% Rotation around the new camera position at 0,0,0 % See if rotation was turned off if ~p.Results.rotate, return; end % Test whether we need to rotate the camera % or the direction is already aligned with z axis. [xAngle, yAngle] = direction2zaxis(thisR); if xAngle == 0 && yAngle == 0, return; end % Rotate to point the lookat direction along the z axis rMatrix = piRotate([xAngle,yAngle,0]); to = thisR.get('to'); thisR.set('to',(rMatrix*to(:))); % Set to a row vector % piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); % Reset the position of every object, rotating by the same amount objects = thisR.get('objects'); for ii=1:numel(objects) curPos = thisR.get('asset',objects(ii),'world position'); newPos = rMatrix*curPos(:); thisR.set('asset',objects(ii),'world position',newPos); thisR.set('asset',objects(ii),'world rotate',[xAngle, yAngle, 0]); end % thisR.set('asset','rectify', 'world rotate', [-xAngle,-yAngle,0]); % thisR.get('asset','rectify','rotation') % piWrite(thisR); [scene,results] = piRender(thisR,'render type','radiance'); sceneWindow(scene); end function [xAngle, yAngle] = direction2zaxis(thisR) %% Angles needed to align lookat with zaxis % % 0 = [0 cos(a) -sin(a)]*direction(:) % 0 = cos(a)*direction(2) - sin(a)*direction(3) % sin(a)*direction(3) = cos(a)*direction(2) % sin(a)/cos(a) = (direction(2)/direction(3)) % tan(a) = (direction(2)/direction(3)) % a = atan(direction(2)/direction(3)) % % Rotate again, this time to be perpendicular to the x-axis (x=0). % % 0 = cos(b)*d2(1) + 0*d2(2) + sin(b)*d2(3) % sin(b)/cos(b) = -d2(1)/d2(3) % b = atan(-d2(1)/d2(3)) % xAngle = 0; yAngle = 0; % Assume aligned % Angle to the z axis direction = thisR.get('lookat direction'); % Unit vector zaxis = [0 0 1]; CosTheta = max(min(dot(direction,zaxis),1),-1); ztheta = real(acosd(CosTheta)); % If the direction is different from down the z-axis, do the rest. % Otherwise, return. We consider 'different' to be within a tenth of a % degree, I guess. % if ztheta < 0.1, return; end % Find the rotations in deg around the x and y axes so that the new % direction vector aligns with the zaxis. % % First find a rotation angle around the x-axis into the x-z plane. % The angle must satisfy y = 0. So, we take out the row of the x-rotation % matrix % % Test with different direction vectors % % direction = [1 2 0]; % direction = [-1 0 2]; xAngle = atan2d(direction(2),direction(3)); % Radians xRotationMatrix = piRotate([rad2deg(xAngle),0,0]); direction2 = xRotationMatrix*direction(:); %{ % y entry of this vector should be 0 direction2 %} % Now solve for y rotation yAngle = atan2d(-direction2(1),direction2(3)); %{ % Should be aligned with z-axis cos(yAngle)*direction2(1) + sin(yAngle)*direction2(3) yRotationMatrix = piRotate([0,rad2deg(yAngle),0]); direction3 = yRotationMatrix*direction2(:) %} end %{ rMatrix = piRotate([xAngle,yAngle,0]); % We have the angles. Rotate every object's position and its orientation for ii=1:numel(objects) pos = thisR.get('asset',objects(ii),'world coordinate'); pos = rMatrix*pos(:); thisR.set('asset',objects(ii),'world coordinate',pos); piAssetRotate('asset',objects(ii),[xAngle,yAngle,0]); end end %} %{ % NOTES u = zaxis; v = direction; CosTheta = max(min(dot(u,v)/(norm(u)*norm(v)),1),-1); ztheta = real(acosd(CosTheta)); xaxis = R = [cosd(theta) -sind(theta); sind(theta) cosd(theta)]; vR = v*R; %} % Find the 3D rotation matrix that brings direction to the zaxis. % Call piDCM2angle to get the x,y,z rotations % Call piAssetRotate with those three rotations %}
github
ISET/iset3d-v3-master
piWrite.m
.m
iset3d-v3-master/utilities/piWrite.m
23,855
utf_8
74996513235188090a85988c93a0337a
function workingDir = piWrite(thisR,varargin) % Write a PBRT scene file based on its renderRecipe % % Syntax % workingDir = piWrite(thisR,varargin) % % The pbrt scene file and all the relevant resource files (geometry, % materials, spds, others) are written out in a working directory. These % are the files that will be mounted by the docker container and used by % PBRT to create the radiance, depth, mesh metadata outputs. % % There are multiple options as to whether or not to overwrite files that % are already present in the output directory. The logic and conditions % about these overwrites is quite complex right now, and we need to % simplify. % % In some cases, multiple PBRT scenes use the same resources files. If you % know the resources files are already there, you can set % overwriteresources to false. Similarly if you do not want to overwrite % the pbrt scene file, set overwritepbrtfile to false. % % Input % thisR: a recipe object describing the rendering parameters. % % Optional key/value parameters % There are too many of these options. We hope to simplify % % overwrite pbrtfile - If scene PBRT file exists, overwrite (default true) % overwrite resources - If the resources files exist, overwrite (default true) % overwrite lensfile - Logical. Default true % Deprecated overwrite materials - Logical. Default true % Deprecated overwrite geometry - Logical. Default true % overwrite json - Logical. Default true % lightsFlag % thistrafficflow % % verbose -- how chatty we are % % Return % workingDir - path to the output directory mounted by the Docker % container. This is not necessary, however, because we % can find it from thisR.get('output dir') % % TL Scien Stanford 2017 % JNM -- Add Windows support 01/25/2019 % % See also % piRead, piRender % Examples: %{ thisR = piRecipeDefault('scene name','MacBethChecker'); % thisR = piRecipeDefault('scene name','SimpleScene'); % thisR = piRecipeDefault('scene name','teapot'); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %} %{ thisR = piRecipeDefault('scene name','chessSet'); lensfile = 'fisheye.87deg.6.0mm.json'; thisR.camera = piCameraCreate('omni','lensFile',lensfile); thisR.set('film resolution',round([300 200])); thisR.set('pixel samples',32); % Number of rays set the quality. thisR.set('focus distance',0.45); thisR.set('film diagonal',10); thisR.integrator.subtype = 'path'; thisR.sampler.subtype = 'sobol'; thisR.set('aperture diameter',3); piWrite(thisR); oi = piRender(thisR,'render type','radiance'); oiWindow(oi); %} %{ piWrite(thisR,'overwrite resources',false,'overwrite pbrt file',true); piWrite(thisR); %} %% Parse inputs varargin = ieParamFormat(varargin); p = inputParser; % When varargin contains a number, the ieParamFormat() method fails. % It takes only a string or cell. We should look into that. % varargin = ieParamFormat(varargin); p.addRequired('thisR',@(x)isequal(class(x),'recipe')); % Copy over the whole directory p.addParameter('overwriteresources', true,@islogical); % Overwrite the specific scene file p.addParameter('overwritepbrtfile',true,@islogical); % Force overwrite of the lens file p.addParameter('overwritelensfile',true,@islogical); % Overwrite materials.pbrt p.addParameter('overwritematerials',true,@islogical); % Overwrite geometry.pbrt p.addParameter('overwritegeometry',true,@islogical); % Create a new materials.pbrt % p.addParameter('creatematerials',false,@islogical); % % control lighting in geomtery.pbrt % p.addParameter('lightsflag',false,@islogical); % % % Read trafficflow variable % p.addParameter('thistrafficflow',[]); % Store JSON recipe for the traffic scenes p.addParameter('overwritejson',true,@islogical); p.addParameter('verbose', 0, @isnumeric); p.parse(thisR,varargin{:}); overwriteresources = p.Results.overwriteresources; overwritepbrtfile = p.Results.overwritepbrtfile; overwritelensfile = p.Results.overwritelensfile; overwritematerials = p.Results.overwritematerials; overwritegeometry = p.Results.overwritegeometry; % creatematerials = p.Results.creatematerials; % lightsFlag = p.Results.lightsflag; % thistrafficflow = p.Results.thistrafficflow; overwritejson = p.Results.overwritejson; verbosity = p.Results.verbose; %% Check the input and output directories % Input must exist inputDir = thisR.get('input dir'); if ~exist(inputDir,'dir'), warning('Could not find inputDir: %s\n',inputDir); end % Make working dir if it does not already exist workingDir = thisR.get('output dir'); if ~exist(workingDir,'dir'), mkdir(workingDir); end % Make a geometry directory geometryDir = thisR.get('geometry dir'); if ~exist(geometryDir, 'dir'), mkdir(geometryDir); end renderDir = thisR.get('rendered dir'); if ~exist(renderDir,'dir'), mkdir(renderDir); end %% Selectively copy data from the input to the output directory. piWriteCopy(thisR,overwriteresources,overwritepbrtfile, verbosity) %% If the optics type is lens, copy the lens file to a lens sub-directory if isequal(thisR.get('optics type'),'lens') % realisticEye has a lens file slot but it is empty. So we check % whether there is a lens file or not. if ~isempty(thisR.get('lensfile')) piWriteLens(thisR,overwritelensfile); end end %% Open up the main PBRT scene file. outFile = thisR.get('output file'); fileID = fopen(outFile,'w'); %% Write header piWriteHeader(thisR,fileID) %% Write Scale and LookAt commands first piWriteLookAtScale(thisR,fileID); %% Write transform start and end time piWriteTransformTimes(thisR, fileID); %% Write all other blocks that we have field names for piWriteBlocks(thisR,fileID); %% Add 'Include' lines for materials, geometry and lights into the scene PBRT file piIncludeLines(thisR,fileID); %% Write out the lights piLightWrite(thisR); %% Close the main PBRT scene file fclose(fileID); %% Write scene_materials.pbrt % Even when copying, we extract the materials and textures piWriteMaterials(thisR,overwritematerials); %% If the exporter is copy, we do not write out the geometry if isequal(thisR.exporter, 'Copy') return; end %% Overwrite geometry.pbrt piWriteGeometry(thisR,overwritegeometry); %% Overwrite xxx.json - For traffic scenes if overwritejson [~,scene_fname,~] = fileparts(thisR.outputFile); jsonFile = fullfile(workingDir,sprintf('%s.json',scene_fname)); jsonwrite(jsonFile,thisR); end end % End of piWrite %% Helper functions %% Copy the input resources to the output directory function piWriteCopy(thisR,overwriteresources,overwritepbrtfile, verbosity) % Copy files from the input to output dir % % In some cases we are looping over many renderings. In that case we may % turn off the repeated copies by setting overwriteresources to false. inputDir = thisR.get('input dir'); outputDir = thisR.get('output dir'); % We check for the overwrite here and we make sure there is also an input % directory to copy from. if overwriteresources && ~isempty(inputDir) sources = dir(inputDir); status = true; for i = 1:length(sources) if startsWith(sources(i).name(1),'.') % Skip dot-files continue; elseif sources(i).isdir && (strcmpi(sources(i).name,'spds') || strcmpi(sources(i).name,'textures')) % Copy the spds and textures directory files. status = status && copyfile(fullfile(sources(i).folder, sources(i).name), fullfile(outputDir,sources(i).name)); else % Selectively copy the files in the scene root folder [~, ~, extension] = fileparts(sources(i).name); % ChessSet needs input geometry because we can not parse it % yet. --zhenyi if ~(piContains(extension,'zip') || piContains(extension,'json')) thisFile = fullfile(sources(i).folder, sources(i).name); if verbosity > 1 fprintf('Copying %s\n',thisFile) end status = status && copyfile(thisFile, fullfile(outputDir,sources(i).name)); end end end if(~status) error('Failed to copy input directory to docker working directory.'); else if verbosity > 1 fprintf('Copied resources from:\n'); fprintf('%s \n',inputDir); fprintf('to \n'); fprintf('%s \n \n',outputDir); end end end %% Potentially overwrite the scene PBRT file outFile = thisR.get('output file'); % Check if the outFile exists. If it does, decide what to do. if(exist(outFile,'file')) if overwritepbrtfile % A pbrt scene file exists. We delete here and write later. fprintf('Overwriting PBRT file %s\n',outFile) delete(outFile); else % Do not overwrite is set, and yet it exists. We don't like this % condition, so we throw an error. error('PBRT file %s exists.',outFile); end end end %% Put the header into the scene PBRT file function piWriteHeader(thisR,fileID) % Write the header % fprintf(fileID,'# PBRT file created with piWrite on %i/%i/%i %i:%i:%0.2f \n',clock); fprintf(fileID,'# PBRT version = %i \n',thisR.version); fprintf(fileID,'\n'); % If a crop window exists, write out a warning if(isfield(thisR.film,'cropwindow')) fprintf(fileID,'# Warning: Crop window exists! \n'); end end %% Write lens information function piWriteLens(thisR,overwritelensfile) % Write out the lens file. Manage cases of overwrite or not % % We also manage special human eye model cases Some of these require % auxiliary files like Index of Refraction files that are specified using % Include statements in the World block. % % See also % navarroWrite, navarroLensCreate, setNavarroAccommodation % Make sure the we have the full path to the input lens file inputLensFile = thisR.get('lens file'); outputDir = thisR.get('output dir'); outputLensFile = thisR.get('lens file output'); outputLensDir = fullfile(outputDir,'lens'); if ~exist(outputLensDir,'dir'), mkdir(outputLensDir); end if isequal(thisR.get('realistic eye model'),'navarro') % Write lens file and the ior files into the output directory. navarroWrite(thisR); elseif isequal(thisR.get('realistic eye model'),'legrand') % Write lens file and the ior files into the output directory. legrandWrite(thisR); elseif isequal(thisR.get('realistic eye model'),'arizona') % Write lens file into the output directory. % Still tracking down why no IOR files are associated with this model. arizonaWrite(thisR); else % If the working copy doesn't exist, copy it. % If it exists but there is a force overwrite, delete and copy. % % We need to check that this will work for the RTF json file as well. % I think so. (BW). if ~exist(outputLensFile,'file') copyfile(inputLensFile,outputLensFile); elseif overwritelensfile % It must exist. So if we are supposed overwrite delete(outputLensFile); copyfile(inputLensFile,outputLensFile); end end end %% LookAt and Scale fields function piWriteLookAtScale(thisR,fileID) % Optional Scale % This was here for a long time. But I don't think it matters unless it is % inside the 'WorldBegin' loop. So I deleted it and started writing the % Scale inside the WorldBegin' write section % %{ theScale = thisR.get('scale'); if(~isempty(theScale)) fprintf(fileID,'Scale %0.2f %0.2f %0.2f \n', [theScale(1) theScale(2) theScale(3)]); fprintf(fileID,'\n'); end %} % Optional Motion Blur % default StartTime and EndTime is 0 to 1; if isfield(thisR.camera,'motion') motionTranslate = thisR.get('camera motion translate'); motionStart = thisR.get('camera motion rotation start'); motionEnd = thisR.get('camera motion rotation end'); fprintf(fileID,'ActiveTransform StartTime \n'); fprintf(fileID,'Translate 0 0 0 \n'); fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,1)); % Z fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,2)); % Y fprintf(fileID,'Rotate %f %f %f %f \n',motionStart(:,3)); % X fprintf(fileID,'ActiveTransform EndTime \n'); fprintf(fileID,'Translate %0.2f %0.2f %0.2f \n',... [motionTranslate(1),... motionTranslate(2),... motionTranslate(3)]); fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,1)); % Z fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,2)); % Y fprintf(fileID,'Rotate %f %f %f %f \n',motionEnd(:,3)); % X fprintf(fileID,'ActiveTransform All \n'); end % Required LookAt from = thisR.get('from'); to = thisR.get('to'); up = thisR.get('up'); fprintf(fileID,'LookAt %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f %0.6f \n', ... [from(:); to(:); up(:)]); fprintf(fileID,'\n'); end %% Transform times function piWriteTransformTimes(thisR, fileID) % Get transform times startTime = thisR.get('transform times start'); endTime = thisR.get('transform times end'); if ~isempty(startTime) && ~isempty(endTime) fprintf(fileID,'TransformTimes %0.6f %0.6f \n', ... startTime, endTime); end end %% function piWriteBlocks(thisR,fileID) % Loop through the thisR fields, writing them out as required % % The blocks that are written out include % % Camera, lens % workingDir = thisR.get('output dir'); % These are the main fields in the recipe. We call them the outer fields. % Within each outer field, there will be inner fields. The outer fields % include film, filter, camera and such. outerFields = fieldnames(thisR); for ofns = outerFields' ofn = ofns{1}; % If empty, we skip this field. if(~isfield(thisR.(ofn),'type') || ... ~isfield(thisR.(ofn),'subtype')) continue; end % Skip, we don't want to write these out here. So if any one of these, % we skip to the next for-loop step if(strcmp(ofn,'world') || ... strcmp(ofn,'lookAt') || ... strcmp(ofn,'inputFile') || ... strcmp(ofn,'outputFile')|| ... strcmp(ofn,'version')) || ... strcmp(ofn,'materials')|| ... strcmp(ofn,'recipeVer')|| ... strcmp(ofn,'exporter') || ... strcmp(ofn,'metadata') || ... strcmp(ofn,'renderedFile') || ... strcmp(ofn,'world') continue; end % Deal with camera and medium if strcmp(ofn,'camera') && isfield(thisR.(ofn),'medium') if ~isempty(thisR.(ofn).medium) currentMedium = []; for j=1:length(thisR.media.list) if strcmp(thisR.media.list(j).name,thisR.(ofn).medium) currentMedium = thisR.media.list; end end fprintf(fileID,'MakeNamedMedium "%s" "string type" "water" "string absFile" "spds/%s_abs.spd" "string vsfFile" "spds/%s_vsf.spd"\n', ... currentMedium.name,... currentMedium.name,currentMedium.name); fprintf(fileID,'MediumInterface "" "%s"\n',currentMedium.name); end end % Write header that identifies which block this is fprintf(fileID,'# %s \n',ofn); % Write out the main type and subtypes fprintf(fileID,'%s "%s" \n',thisR.(ofn).type,... thisR.(ofn).subtype); % Find and then loop through inner field names innerFields = fieldnames(thisR.(ofn)); if(~isempty(innerFields)) for ifns = innerFields' ifn = ifns{1}; % Skip these since we've written these out earlier. if(strcmp(ifn,'type') || ... strcmp(ifn,'subtype') || ... strcmp(ifn,'subpixels_h') || ... strcmp(ifn,'subpixels_w') || ... strcmp(ifn,'motion') || ... strcmp(ifn,'subpixels_w') || ... strcmp(ifn,'medium')) continue; end %{ Many fields are written out in here. Some examples are type, subtype, lensfile retinaDistance retinaRadius pupilDiameter retinaSemiDiam ior1 ior2 ior3 ior4 type subtype pixelsamples type subtype xresolution yresolution type subtype maxdepth %} currValue = thisR.(ofn).(ifn).value; currType = thisR.(ofn).(ifn).type; if(strcmp(currType,'string') || ischar(currValue)) % We have a string with some value lineFormat = ' "%s %s" "%s" \n'; % The currValue might be a full path to a file with an % extension. We find the base file name and copy the file % to the working directory. Then, we transform the string % to be printed in the pbrt scene file to be its new % relative path. There is a minor exception for the lens % file. Perhaps we should have a better test here, say an % exist() test. (BW). [~,name,ext] = fileparts(currValue); % only if the file is in lens folder if ~isempty(which(currValue)) if(~isempty(ext)) % This looks like a file with an extension. If it % is a lens file or an iorX.spd file, indicate that % it is in the lens/ directory. Otherwise, copy the % file to the working directory. fileName = strcat(name,ext); if strcmp(ifn,'specfile') || strcmp(ifn,'lensfile') % It is a lens, so just update the name. It % was already copied % This should work. % currValue = strcat('lens',[filesep, strcat(name,ext)]); if ispc() currValue = strcat('lens/',strcat(name,ext)); else currValue = fullfile('lens',strcat(name,ext)); end elseif piContains(ifn,'ior') % The the innerfield name contains the ior string, % then we change it to this currValue = strcat('lens',[filesep, strcat(name,ext)]); else [success,~,id] = copyfile(currValue,workingDir); if ~success && ~strcmp(id,'MATLAB:COPYFILE:SourceAndDestinationSame') warning('Problem copying %s\n',currValue); end % Update the file for the relative path currValue = fileName; end end end elseif(strcmp(currType,'spectrum') && ~ischar(currValue)) % A spectrum of type [wave1 wave2 value1 value2]. TODO: % There are probably more variations of this... lineFormat = ' "%s %s" [%f %f %f %f] \n'; elseif(strcmp(currType,'rgb')) lineFormat = ' "%s %s" [%f %f %f] \n'; elseif(strcmp(currType,'float')) if(length(currValue) > 1) lineFormat = ' "%s %s" [%f %f %f %f] \n'; else lineFormat = ' "%s %s" [%f] \n'; end elseif(strcmp(currType,'integer')) lineFormat = ' "%s %s" [%i] \n'; end fprintf(fileID,lineFormat,... currType,ifn,currValue); end end % Blank line. fprintf(fileID,'\n'); end end %% function piIncludeLines(thisR,fileID) % Insert the 'Include scene_materials.pbrt' and similarly for geometry and % lights into the main scene file % % We must add the materials before the geometry. % We add the lights at the end. % basename = thisR.get('output basename'); % For the Copy case, we just copy the world and Include the lights. if isequal(thisR.exporter, 'Copy') for ii = 1:numel(thisR.world) if ii == numel(thisR.world) % Lights at the end fprintf(fileID,'Include "%s_lights.pbrt" \n', basename); end fprintf(fileID,'%s \n',thisR.world{ii}); if ii == 1 % Materials at the beginning fprintf(fileID,'Include "%s_materials.pbrt" \n', basename); end end return; end %% Find the World lines with _geometry, _materials, _lights % We are being aggressive about the Include files. We want to name them % ourselves. First we see whether we have Includes for these at all lineMaterials = find(contains(thisR.world, {'_materials.pbrt'})); lineGeometry = find(contains(thisR.world, {'_geometry.pbrt'})); lineLights = find(contains(thisR.world, {'_lights.pbrt'})); % If we have geometry Include, we overwrite it with the name we want. if ~isempty(lineGeometry) thisR.world{lineGeometry} = sprintf('Include "%s_geometry.pbrt"\n', basename); end % If we have materials Include, we overwrite it. % end. if ~isempty(lineMaterials) thisR.world{lineMaterials} = sprintf('Include "%s_materials.pbrt"\n',basename); end % We think nobody except us has these lights files. So this will never get % executed. if ~isempty(lineLights) thisR.world(lineLights) = sprintf('Include "%s_lights.pbrt"\n', basename); end %% Write out the World information. % Insert the Include lines as the last three before WorldEnd. % Also, as of December 2021, placed the 'Scale' line in here. % Maybe we should not have an overall Scale in the recipe, however. % for ii = 1:length(thisR.world) currLine = thisR.world{ii}; % ii = 1 is 'WorldBegin' if piContains(currLine, 'WorldEnd') && isempty(lineLights) % Insert the lights file. fprintf(fileID, sprintf('Include "%s_lights.pbrt" \n', basename)); end fprintf(fileID,'%s \n',currLine); if piContains(currLine,'WorldBegin') % Start with the Scale value from the recipe. This scales the whole scene, % but it might be a bad idea because it does not preserve the geometric % relationships between the objects. They all get bigger. theScale = thisR.get('scale'); if(~isempty(theScale)) fprintf(fileID,'Scale %0.2f %0.2f %0.2f \n', [theScale(1) theScale(2) theScale(3)]); fprintf(fileID,'\n'); end end if piContains(currLine,'WorldBegin') && isempty(lineMaterials) % Insert the materials file fprintf(fileID,'%s \n',sprintf('Include "%s_materials.pbrt" \n', basename)); end end end %% function piWriteMaterials(thisR,overwritematerials) % Write both materials and textures files into the output directory % We create the materials file. Its name is the same as the output pbrt % file, but it has an _materials inserted. if overwritematerials outputDir = thisR.get('output dir'); basename = thisR.get('output basename'); % [~,n] = fileparts(thisR.inputFile); fname_materials = sprintf('%s_materials.pbrt',basename); thisR.set('materials output file',fullfile(outputDir,fname_materials)); piMaterialWrite(thisR); end end %% function piWriteGeometry(thisR,overwritegeometry) % Write the geometry file into the output dir % if overwritegeometry piGeometryWrite(thisR); end end
github
ISET/iset3d-v3-master
piRecipRectify.m
.m
iset3d-v3-master/utilities/piRecipRectify.m
5,470
utf_8
31f356831c4e47d979027ec8af3443f8
function thisR = piRecipRectify(thisR,origin) % Move the camera and objects so that the camera is at origin pointed along % the z-axis % % Description % % See piRotate for the rotation matrices for the three axes % See also % % Examples %{ thisR = piRecipeDefault('scene name','simple scene'); piAssetGeometry(thisR,'inplane','xz'); piCameraRotate(thisR,'y rot',10); thisR.get('lookat direction') piAssetGeometry(thisR,'inplane','xz'); origin = [0 0 0]; thisR = piRecipRectify(thisR,origin); thisR.get('lookat direction') piAssetGeometry(thisR); piAssetGeometry(thisR,'inplane','xy'); thisR.set('fov',60); piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %} %% Find the camera position from = thisR.get('camera position'); %% Move the camera to the specified origin % Identify all the children of root idChildren = thisR.get('asset','root','children'); if numel(idChildren) == 1 tmp = split(thisR.get('asset',idChildren,'name'),'_'); if isequal(tmp{end},'rectify') % No need to insert a rectify node. It is there already. else % Create the rectify node below the root and before all other nodes rectNode = piAssetCreate('type','branch'); rectNode.name = 'rectify'; thisR.set('asset','root','add',rectNode); end else % Create the rectify node below the root and before all other nodes rectNode = piAssetCreate('type','branch'); rectNode.name = 'rectify'; thisR.set('asset','root','add',rectNode); end % Get the rectify node under the root idRectify = thisR.get('asset','rectify','id'); % Place all the previous children under rectify for ii=1:numel(idChildren) thisR.set('asset',idChildren(ii),'parent',idRectify); end % thisR.show %% Translation % The camera is handled separately from the objects d = origin - from; piCameraTranslate(thisR,'xshift',d(1), ... 'yshift',d(2), ... 'zshift',d(3)); % Set the translation of the rectify node piAssetSet(thisR,idRectify,'translation',d); % thisR.get('asset','rectify','translate') % piAssetGeometry(thisR); % piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); %% Rotation % Rotate the camera [xAngle, yAngle] = direction2zaxis(thisR); % No rotation needed. Direction is already aligned with z axis. if xAngle == 0 && yAngle == 0, return; end % Rotate the to point onto the z axis rMatrix = piRotate([xAngle,yAngle,0]); to = thisR.get('to'); thisR.set('to',(rMatrix*to(:))'); % Row vector. Should be forced in set. % piWrite(thisR); scene = piRender(thisR,'render type','radiance'); sceneWindow(scene); % Set a rotation in the rectify nodes to change all the objects r = piRotationMatrix('zrot',0,'yrot',-yAngle,'xrot',-xAngle); piAssetSet(thisR,idRectify,'rotation',r); % thisR.get('asset','rectify','rotation') % piWrite(thisR); [scene,results] = piRender(thisR,'render type','radiance'); sceneWindow(scene); end function [xAngle, yAngle] = direction2zaxis(thisR) %% Angles needed to align lookat with zaxis % % 0 = [0 cos(a) -sin(a)]*direction(:) % 0 = cos(a)*direction(2) - sin(a)*direction(3) % sin(a)*direction(3) = cos(a)*direction(2) % sin(a)/cos(a) = (direction(2)/direction(3)) % tan(a) = (direction(2)/direction(3)) % a = atan(direction(2)/direction(3)) % % Rotate again, this time to be perpendicular to the x-axis (x=0). % % 0 = cos(b)*d2(1) + 0*d2(2) + sin(b)*d2(3) % sin(b)/cos(b) = -d2(1)/d2(3) % b = atan(-d2(1)/d2(3)) % xAngle = 0; yAngle = 0; % Assume aligned % Angle to the z axis direction = thisR.get('lookat direction'); % Unit vector zaxis = [0 0 1]; CosTheta = max(min(dot(direction,zaxis),1),-1); ztheta = real(acosd(CosTheta)); % If the direction is different from down the z-axis, do the rest. % Otherwise, return. We consider 'different' to be within a tenth of a % degree, I guess. % if ztheta < 0.1, return; end % Find the rotations in deg around the x and y axes so that the new % direction vector aligns with the zaxis. % % First find a rotation angle around the x-axis into the x-z plane. % The angle must satisfy y = 0. So, we take out the row of the x-rotation % matrix % % Test with different direction vectors % % direction = [1 2 0]; % direction = [-1 0 2]; xAngle = atan2d(direction(2),direction(3)); % Radians xRotationMatrix = piRotate([rad2deg(xAngle),0,0]); direction2 = xRotationMatrix*direction(:); %{ % y entry of this vector should be 0 direction2 %} % Now solve for y rotation yAngle = atan2d(-direction2(1),direction2(3)); %{ % Should be aligned with z-axis cos(yAngle)*direction2(1) + sin(yAngle)*direction2(3) yRotationMatrix = piRotate([0,rad2deg(yAngle),0]); direction3 = yRotationMatrix*direction2(:) %} end %{ rMatrix = piRotate([xAngle,yAngle,0]); % We have the angles. Rotate every object's position and its orientation for ii=1:numel(objects) pos = thisR.get('asset',objects(ii),'world coordinate'); pos = rMatrix*pos(:); thisR.set('asset',objects(ii),'world coordinate',pos); piAssetRotate('asset',objects(ii),[xAngle,yAngle,0]); end end %} %{ % NOTES u = zaxis; v = direction; CosTheta = max(min(dot(u,v)/(norm(u)*norm(v)),1),-1); ztheta = real(acosd(CosTheta)); xaxis = R = [cosd(theta) -sind(theta); sind(theta) cosd(theta)]; vR = v*R; %} % Find the 3D rotation matrix that brings direction to the zaxis. % Call piDCM2angle to get the x,y,z rotations % Call piAssetRotate with those three rotations %}
github
ISET/iset3d-v3-master
piWebGet.m
.m
iset3d-v3-master/utilities/piWebGet.m
11,212
utf_8
881910654e170229a04f37bcc7676b17
function localFile = ieWebGet2(varargin) %% Download a resource from the Stanford web site % % Synopsis % localFile = ieWebGet2(varargin) % % Brief description % Download an ISET zip or mat-file file from the web. The type of file % and the remote file name define how to get the file. % % Inputs % varargin{1} - If the first argument is ,'list','url', you will be % 'browse' - sent to the website % 'list' - be returned a list of resources or . The second argument % 'url' - shown the type of resource at the url ('pbrt', % 'hyperspectral', 'multispectral', 'hdr'). The default resource is % 'pbrt'. % % Key/val pairs % op: The operation to perform {'fetch','read'} % (default: 'fetch') % resource type: 'pbrt', 'hyperspectral', 'multispectral', 'hdr' % (default: 'pbrt') % resource name : File name of the remote file % remove temp files: Remove local temp file (zip) % unzip: : Unzip the file % verbose : Print a report to the command window % % Output % localFile: Name of the local download file % % Description % We store various data sets (resources) as zip- and mat-files on the % Stanford resource, cardinal.stanford.edu/~SOMEONE. This routine is a % gateway that allows us to download the files (using fetch). % % The types of resources are listed above. To see the remote web site or % the names of the resources, use the 'list' or 'browse' operations. % % pbrt resources default to being stored under % % iset3d/data/v3/web. % % other resources ('hdr','hyperspectral','multispectral') default to % being stored under % % isetcam/local/scenes/<resourcetype>/. % See also: % webImageBrowser_mlapp % % Examples %{ % Browse the remote site ieWebGet('browse'); %} %{ ieWebGet('list') %} %{ localFile = ieWebGet('resource name','veach-ajar'); %} %{ localFile = ieWebGet2('resourcename', 'ChessSet', 'resourcetype', 'pbrt') data = ieWebGet2('op', 'read', 'resourcetype', 'hyperspectral', 'resourcename', 'FruitMCC') localFile = ieWebGet2('op', 'fetch', 'resourcetype', 'hdr', 'resourcename', 'BBQsite1') ~ = ieWebGet2('resourcetype', 'pbrt', 'op', 'browse') %} %{ % Use it to create a list of resources and then select one: arrayOfResourceFiles = ieWebGet('op', 'list', 'resourcetype', 'hyperspectral') data = ieWebGet2('op', 'read', 'resource type', 'hyperspectral', 'resource name', arrayOfResourceFiles{ii}); %} %% Set up base URL urlList = ... {'http://stanford.edu/~wandell/data/pbrt/', ... 'http://stanford.edu/~david81/ISETData/Hyperspectral/', ... 'http://stanford.edu/~david81/ISETData/Multispectral/', ... 'http://stanford.edu/~david81/ISETData/HDR/'}; baseURL = urlList{1}; %% Check for the special input arguments % ieWebGet2('browse','pbrt'), % ieWebGet2('browse','hyperspectral') if ismember(ieParamFormat(varargin{1}),{'browse','list','url'}) if numel(varargin) < 2, src = 'pbrt'; else, src = ieParamFormat(varargin{2}); end switch src case 'pbrt' baseURL = urlList{1}; case 'hyperspectral' baseURL = urlList{2}; case 'multispectral' baseURL = urlList{3}; case 'hdr' baseURL = urlList{4}; otherwise error('Unknown resource type %s\n',src); end if isequal(ieParamFormat(varargin{1}),'browse') % assume for now that means we are looking on the web web(baseURL); localFile = ''; return; elseif isequal(ieParamFormat(varargin{1}),'list') % simply read the pre-loaded list of resources try localFile = webread(strcat(baseURL, 'resourcelist.json')); catch % We should find a better way to do this warning("Unable to load resource list from remote site. Returning webread data"); localFile = webread(baseURL); end % we need to filter here as sometimes we only want .MAT files localFile = localFile(contains(localFile, ".mat", 'IgnoreCase', true)); return; elseif isequal(ieParamFormat(varargin{1}),'url') fprintf('\nResource URLs\n=================\n\n'); for ii=1:numel(urlList) fprintf('%s\n',urlList{ii}); end fprintf('\n'); return; end end %% Decode key/val args varargin = ieParamFormat(varargin); p = inputParser; vFunc = @(x)(ismember(x,{'fetch','read','list'})); p.addParameter('op','fetch',vFunc); p.addParameter('resourcename', '', @ischar); vFunc = @(x)(ismember(x,{'pbrt', 'hyperspectral', 'multispectral', 'hdr','pbrt','v3'})); p.addParameter('resourcetype', 'pbrt',vFunc); p.addParameter('askfirst', true, @islogical); p.addParameter('unzip', true, @islogical); % assume the user wants the resource unzipped, if applicable p.addParameter('localname','',@ischar); % Defaults to remote name p.addParameter('removetempfiles', true, @islogical); p.addParameter('verbose',true,@islogical); % Tell the user what happened p.parse(varargin{:}); resourceName = p.Results.resourcename; resourceType = p.Results.resourcetype; localName = p.Results.localname; unZip = p.Results.unzip; removeTempFiles = p.Results.removetempfiles; if isempty(localName) localName = resourceName; end verbose = p.Results.verbose; op = p.Results.op; askFirst = p.Results.askfirst; localFile = ''; % Default local file name switch resourceType case {'pbrt', 'v3'} if exist('piRootPath','file') && isfolder(piRootPath) downloadRoot = piRootPath; elseif exist('isetRootPath', 'file') && isfolder(isetRootPath) downloadRoot = isetRootPath; else error("Need to have either iset3D or isetCam Root set"); end switch op case 'fetch' % for now we only support v3 pbrt files downloadDir = fullfile(downloadRoot,'data','v3','web'); if ~isfolder(downloadDir) mkdir(downloadDir); end remoteFileName = strcat(resourceName, '.zip'); resourceURL = strcat(baseURL, remoteFileName); localURL = fullfile(downloadDir, remoteFileName); if askFirst proceed = confirmDownload(resourceName, resourceURL, localURL); if proceed == false, return, end end try websave(localURL, resourceURL); if unZip unzip(localURL, downloadDir); if removeTempFiles delete(localURL); end % not sure how we "know" what the unzip path is? localFile = fullfile(downloadDir, resourceName); else localFile = localURL; end catch %not much in the way of error handling yet:) warning("Unable to retrieve: %s", resourceURL); localFile = ''; end otherwise error('Unknown operation for PBRT %s\n',op); end case {'hyperspectral', 'multispectral', 'hdr'} % We need to adjust the baseurl for these non-pbrt cases parentURL = 'http://stanford.edu/~david81/ISETData/'; % do we want to switch based on browse op or % split by type first? switch resourceType case 'hyperspectral' baseURL = strcat(parentURL, "Hyperspectral", '/'); case 'multispectral' baseURL = strcat(parentURL, "Multispectral", '/'); case 'hdr' baseURL = strcat(parentURL, "HDR", '/'); end switch op case {'read', 'fetch'} options = weboptions('Timeout', 60); if ~endsWith(resourceName, "." + lettersPattern) remoteFileName = strcat(resourceName, '.mat'); else remoteFileName = resourceName; end resourceURL = strcat(baseURL, remoteFileName); switch op case {'fetch','read'} if exist('isetRootPath','file') && isfolder(isetRootPath) downloadRoot = isetRootPath; downloadDir = fullfile(downloadRoot, 'local', 'scenes', resourceType); if ~isfolder(downloadDir) mkdir(downloadDir) end else error("Need to have root path set for isetcam or isetbio."); end localFile = fullfile(downloadDir, remoteFileName); if askFirst proceed = confirmDownload(resourceName, resourceURL, localFile); if proceed == false, return, end end try websave(localFile, resourceURL, options); catch warning("Unable to retrieve %s", resourceURL); end if isequal(op, 'read') % in this case we are actually returning a Matlab % array with scene data! stashFile = localFile; localFile = load(stashFile); if removeTempFiles delete(stashFile); end end end otherwise warning("Not Supported yet"); end otherwise error('sceneType %s not supported.',resourceType); end %% Tell the user what happened if verbose if ischar(localFile) disp(strcat("Retrieved: ", resourceName, " to: ", localFile)); elseif isstruct(localFile) disp(strcat("Retrieved: ", resourceName, " and returned as a struct")); elseif exist('localFile','file') && ~isempty(localFile) disp(strcat("Retrieved: ", resourceName, " and returned it as an array")); elseif ~isequal(op,'list') disp(strcat("Unable to Retrieve: ", resourceName)); end end end %% Query the user to confirm the download % function proceed = confirmDownload(resourceName, resourceURL, localURL) question = sprintf("Okay to download: %s from %s to file %s and if necessary, unzip it?\n This may take some time.", resourceName, resourceURL, localURL); answer = questdlg(question, "Confirm Web Resource Download", 'Yes'); if isequal(answer, 'Yes') proceed = true; else proceed = false; end end
github
ISET/iset3d-v3-master
piDCM2angle.m
.m
iset3d-v3-master/utilities/geometry/piDCM2angle.m
3,290
utf_8
26048adb702b41e7f73876c60114ed82
function [r1,r2,r3] = piDCM2angle( dcm, varargin ) % Simplified version of the Aerospace toolbox angle conversion utility % % Syntax: % [r1,r2,r3] = piDCM2angle( dcm ) % % Brief description: % The case that we compute is this one. There are many others and % various options in the Mathworks dcm2angle.m code % % [ cy*cz, cy*sz, -sy] % [ sy*sx*cz-sz*cx, sy*sx*sz+cz*cx, cy*sx] % [ sy*cx*cz+sz*sx, sy*cx*sz-cz*sx, cy*cx] % % Inputs: % dcm: A 3D array of matrices % % Optional key/value pairs % N/A % % Outputs: % zAngle, yAngle, xAngle: Vectors of rotation angles for the matrices % % See also: % piRotationDefault, piGeometryRead % Examples: %{ % Should be all zeros dcm(:,:,1) = eye(3); dcm(:,:,2) = eye(3); [z,y,x] = piDCM2angle(dcm) %} %{ % Consistency with rotationMatrix3d % Some issues with negative positive rotations and dimensions. Sigh. % We need to multiply z and y by -1, and it seems x,y,z have different % definitions. There is a parameter in piDCM2angle that may handle some of % this. angleList = [25 20 -40]; tmp = deg2rad(angleList) rMatrix = rotationMatrix3d(tmp) [z,x,y] = piDCM2angle(rMatrix); estimatedA = rad2deg([-1*y, x, -1*z]); angleList - estimatedA %} %% Should validate here % TL: Validate seems to fail for certain scenes. Commenting out for now % until we figure out what's going on. % validatedcm(dcm); if isempty(varargin) type = 'ZYX'; else type = varargin{1}; end %% This is the transform switch type case 'ZYX' [r1,r2,r3] = threeaxisrot( dcm(1,2,:), dcm(1,1,:), -dcm(1,3,:), ... dcm(2,3,:), dcm(3,3,:)); case 'ZXY' [r1,r2,r3] = threeaxisrot( -dcm(2,1,:), dcm(2,2,:), dcm(2,3,:), ... -dcm(1,3,:), dcm(3,3,:)); case 'XYZ' [r1,r2,r3] = threeaxisrot( -dcm(3,2,:), dcm(3,3,:), dcm(3,1,:), ... -dcm(2,1,:), dcm(1,1,:)); case 'XZY' [r1,r2,r3] = threeaxisrot( dcm(2,3,:), dcm(2,2,:), -dcm(2,1,:), ... dcm(3,1,:), dcm(1,1,:)); case 'YXZ' [r1,r2,r3] = threeaxisrot( dcm(3,1,:), dcm(3,3,:), -dcm(3,2,:), ... dcm(1,2,:), dcm(2,2,:)); case 'YZX' [r1,r2,r3] = threeaxisrot( -dcm(1,3,:), dcm(1,1,:), dcm(1,2,:), ... -dcm(3,2,:), dcm(2,2,:)); end r1 = r1(:); r2 = r2(:); r3 = r3(:); end function [r1,r2,r3] = threeaxisrot(r11, r12, r21, r31, r32) % find angles for rotations about X, Y, and Z axes r1 = atan2( r11, r12 ); r2 = asin( r21 ); r3 = atan2( r31, r32 ); %{ % The original implements this special case of zero rotation on the % 3rd dimension. Does not seem relevant to us if strcmpi( lim, 'zeror3') for i = find(abs( r21 ) >= 1.0) r1(i) = atan2( r11a(i), r12a(i) ); r2(i) = asin( r21(i) ); r3(i) = 0; end end %} end function validatedcm(dcm) %VALIDATEDCM internal function to check that the input dcm is orthogonal %and proper. % The criteria for this check are: % - the transpose of the matrix multiplied by the matrix equals % 1 +/- tolerance % - determinant of matrix == +1 % tolerance = 1e-6; for ii=1:size(dcm,3) x = dcm(:,:,ii)*dcm(:,:,ii)'; d = (x - eye(3)); assert( max(d(:)) < tolerance); assert(det(x) - 1 < tolerance); end end
github
ISET/iset3d-v3-master
piGeometryWrite.m
.m
iset3d-v3-master/utilities/geometry/piGeometryWrite.m
14,203
utf_8
3b095877b9bd5b703e37fbfc0b1af90c
function piGeometryWrite(thisR,varargin) % Write out a geometry file that matches the format and labeling objects % % Synopsis % piGeometryWrite(thisR,varargin) % % Input: % thisR: a render recipe % obj: Returned by piGeometryRead, contains information about objects. % % Optional key/value pairs % % Output: % None for now. % % Description % We need a better description of objects and groups here. Definitions % of 'assets'. % % Zhenyi, 2018 % % See also % piGeometryRead % %% p = inputParser; % varargin =ieParamFormat(varargin); p.addRequired('thisR',@(x)isequal(class(x),'recipe')); % default is flase, will turn on for night scene % p.addParameter('lightsFlag',false,@islogical); % p.addParameter('thistrafficflow',[]); p.parse(thisR,varargin{:}); % These were used but seem to be no longer used % % lightsFlag = p.Results.lightsFlag; % thistrafficflow = p.Results.thistrafficflow; %% Create the default file name [Filepath,scene_fname] = fileparts(thisR.outputFile); fname = fullfile(Filepath,sprintf('%s_geometry.pbrt',scene_fname));[~,n,e]=fileparts(fname); % Get the assets from the recipe obj = thisR.assets; %% Wrote the geometry file. fname_obj = fullfile(Filepath,sprintf('%s%s',n,e)); % Open and write out the objects fid_obj = fopen(fname_obj,'w'); fprintf(fid_obj,'# Exported by piGeometryWrite on %i/%i/%i %i:%i:%f \n \n',clock); % Traverse the tree from root rootID = 1; % Write object and light definition in main geoemtry and children geometry % file if ~isempty(obj) recursiveWriteNode(fid_obj, obj, rootID, Filepath, thisR.outputFile); % Write tree structure in main geometry file lvl = 0; recursiveWriteAttributes(fid_obj, obj, rootID, lvl, thisR.outputFile); else for ii = numel(thisR.world) fprintf(fid_obj, thisR.world{ii}); end end fclose(fid_obj); % Not sure we want this most of the time, can un-comment as needed %fprintf('%s is written out \n', fname_obj); end function recursiveWriteNode(fid, obj, nodeID, rootPath, outFilePath) % Define each object in geometry.pbrt file. This section writes out % (1) Material for every object % (2) path to each children geometry files which store the shape and other % geometry info. % % The process will be: % (1) Get the children of this node % (2) For each child, check if it is an 'object' or 'light' node. If so, % write it out. % (3) If the child is a 'branch' node, put it in a list which will be % recursively checked in next level. %% Get children of thisNode children = obj.getchildren(nodeID); %% Loop through all children at this level % If 'object' node, write out. If 'branch' node, put in the list % Create a list for next level recursion nodeList = []; for ii = 1:numel(children) thisNode = obj.get(children(ii)); % If node, put id in the nodeList if isequal(thisNode.type, 'branch') % do not write object instance repeatedly nodeList = [nodeList children(ii)]; % Define object node elseif isequal(thisNode.type, 'object') while numel(thisNode.name) >= 8 &&... isequal(thisNode.name(5:6), 'ID') thisNode.name = thisNode.name(8:end); end fprintf(fid, 'ObjectBegin "%s"\n', thisNode.name); % Write out mediumInterface if ~isempty(thisNode.mediumInterface) fprintf(fid, strcat("MediumInterface ", '"', thisNode.mediumInterface, '" ','""', '\n')); end % Write out material if ~isempty(thisNode.material) %{ % From dev branch if strcmp(thisNode.material,'none') fprintf(fid, strcat("Material ", '"none"', '\n')); else fprintf(fid, strcat("NamedMaterial ", '"',... thisNode.material.namedmaterial, '"', '\n')); %} try fprintf(fid, strcat("NamedMaterial ", '"',... thisNode.material.namedmaterial, '"', '\n')); catch materialTxt = piMaterialText(thisNode.material); fprintf(fid, strcat(materialTxt, '\n')); end end %{ % I don't know what's this used for, but commenting here. if ~isempty(thisNode.output) % There is an output slot [~,output] = fileparts(thisNode.output); fprintf(fid, 'Include "scene/PBRT/pbrt-geometry/%s.pbrt" \n', output); %} if ~isempty(thisNode.shape) shapeText = piShape2Text(thisNode.shape); if ~isempty(thisNode.shape.filename) % If the shape has ply info, do this % Convert shape struct to text [~, ~, e] = fileparts(thisNode.shape.filename); if isequal(e, '.ply') fprintf(fid, '%s \n',shapeText); else % In this case it is a .pbrt file, we will write it % out. fprintf(fid, 'Include "%s" \n', thisNode.shape.filename); end else % If it does not have plt file, do this % There is a shape slot we also open the % geometry file. name = thisNode.name; geometryFile = fopen(fullfile(rootPath,'scene','PBRT','pbrt-geometry',sprintf('%s.pbrt',name)),'w'); fprintf(geometryFile,'%s',shapeText); fclose(geometryFile); fprintf(fid, 'Include "scene/PBRT/pbrt-geometry/%s.pbrt" \n', name); end end fprintf(fid, 'ObjectEnd\n\n'); elseif isequal(thisNode.type, 'light') || isequal(thisNode.type, 'marker') || isequal(thisNode.type, 'instance') % That's okay but do nothing. else % Something must be wrong if we get here. warning('Unknown node type: %s', thisNode.type) end end for ii = 1:numel(nodeList) recursiveWriteNode(fid, obj, nodeList(ii), rootPath, outFilePath); end end function recursiveWriteAttributes(fid, obj, thisNode, lvl, outFilePath) % Write attribute sections. The logic is: % 1) Get the children of the current node % 2) For each child, write out information accordingly % %% Get children of this node children = obj.getchildren(thisNode); %% Loop through children at this level % Generate spacing to make the tree structure more beautiful spacing = ""; for ii = 1:lvl spacing = strcat(spacing, " "); end % indent spacing indentSpacing = " "; for ii = 1:numel(children) thisNode = obj.get(children(ii)); fprintf(fid, strcat(spacing, 'AttributeBegin\n')); if isequal(thisNode.type, 'branch') % get stripID for this Node while numel(thisNode.name) >= 8 &&... isequal(thisNode.name(5:6), 'ID') thisNode.name = thisNode.name(8:end); end % Write info fprintf(fid, strcat(spacing, indentSpacing,... sprintf('#ObjectName %s:Vector(%.5f, %.5f, %.5f)',thisNode.name,... thisNode.size.l,... thisNode.size.w,... thisNode.size.h), '\n')); % If a motion exists in the current object, prepare to write it out by % having an additional line below. if ~isempty(thisNode.motion) fprintf(fid, strcat(spacing, indentSpacing,... 'ActiveTransform StartTime \n')); end % Transformation section if ~isempty(thisNode.rotation) % Zheng: I think it is always this case, but maybe it is rarely % the case below. Have no clue. % If this way, we would write the translation, rotation and % scale line by line based on the order of thisNode.transorder piGeometryTransformWrite(fid, thisNode, spacing, indentSpacing); else thisNode.concattransform(13:15) = thisNode.translation(:); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('ConcatTransform [%.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f]', thisNode.concattransform(:)), '\n')); % Scale fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Scale %.10f %.10f %.10f', thisNode.scale), '\n')); end %{ % This is the old transformation section % Rotation if ~isempty(thisNode.rotation) fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Translate %.5f %.5f %.5f', thisNode.translation(1),... thisNode.translation(2),... thisNode.translation(3)), '\n')); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation(:, 1)), '\n')); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation(:, 2)), '\n')); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation(:, 3)), '\n')); else thisNode.concattransform(13:15) = thisNode.translation(:); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('ConcatTransform [%.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f %.5f]', thisNode.concattransform(:)), '\n')); end % Scale fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Scale %.10f %.10f %.10f', thisNode.scale), '\n')); %} % Write out motion if ~isempty(thisNode.motion) for jj = 1:size(thisNode.translation, 1) fprintf(fid, strcat(spacing, indentSpacing,... 'ActiveTransform EndTime \n')); % First write out the same translation and rotation piGeometryTransformWrite(fid, thisNode, spacing, indentSpacing); if isfield(thisNode.motion, 'translation') if isempty(thisNode.motion.translation(jj, :)) fprintf(fid, strcat(spacing, indentSpacing,... 'Translate 0 0 0\n')); else pos = thisNode.motion.translation(jj,:); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Translate %f %f %f', pos(1),... pos(2),... pos(3)), '\n')); end end if isfield(thisNode.motion, 'rotation') && ~isempty(thisNode.motion.rotation) rot = thisNode.motion.rotation; % Write out rotation fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %f %f %f %f',rot(:,jj*3-2)), '\n')); % Z fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %f %f %f %f',rot(:,jj*3-1)),'\n')); % Y fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %f %f %f %f',rot(:,jj*3)), '\n')); % X end end end recursiveWriteAttributes(fid, obj, children(ii), lvl + 1, outFilePath); elseif isequal(thisNode.type, 'object') || isequal(thisNode.type, 'instance') while numel(thisNode.name) >= 8 &&... isequal(thisNode.name(5:6), 'ID') % remove instance suffix endIndex = strfind(thisNode.name, '_I_'); if ~isempty(endIndex) endIndex =endIndex-1; else endIndex = numel(thisNode.name); end thisNode.name = thisNode.name(8:endIndex); end fprintf(fid, strcat(spacing, indentSpacing, ... sprintf('ObjectInstance "%s"', thisNode.name), '\n')); elseif isequal(thisNode.type, 'light') % Create a tmp recipe tmpR = recipe; tmpR.outputFile = outFilePath; tmpR.lights = thisNode.lght; lightText = piLightWrite(tmpR, 'writefile', false); for jj = 1:numel(lightText) for kk = 1:numel(lightText{jj}.line) fprintf(fid,sprintf('%s%s%s\n',spacing, indentSpacing,... sprintf('%s',lightText{jj}.line{kk}))); end end else % Hopefully we never get here. warning('Unknown node type %s\n',thisNode.type); end fprintf(fid, strcat(spacing, 'AttributeEnd\n')); end end % Geometry file writing helper function piGeometryTransformWrite(fid, thisNode, spacing, indentSpacing) pointerT = 1; pointerR = 1; pointerS = 1; for tt = 1:numel(thisNode.transorder) switch thisNode.transorder(tt) case 'T' fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Translate %.5f %.5f %.5f', thisNode.translation{pointerT}(1),... thisNode.translation{pointerT}(2),... thisNode.translation{pointerT}(3)), '\n')); pointerT = pointerT + 1; case 'R' fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation{pointerR}(:, 1)), '\n')); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation{pointerR}(:, 2)), '\n')); fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Rotate %.5f %.5f %.5f %.5f', thisNode.rotation{pointerR}(:, 3)), '\n')); pointerR = pointerR + 1; case 'S' fprintf(fid, strcat(spacing, indentSpacing,... sprintf('Scale %.10f %.10f %.10f', thisNode.scale{pointerS}), '\n')); pointerS = pointerS + 1; end end end
github
ISET/iset3d-v3-master
piGeometryRead.m
.m
iset3d-v3-master/utilities/geometry/piGeometryRead.m
11,214
utf_8
4c51e4a64d4970dfbc39bce423936f8c
function thisR = piGeometryRead(thisR) % Read a C4d geometry file and extract object information into a recipe % % Syntax: % renderRecipe = piGeometryRead(renderRecipe) % % Input % renderRecipe: an iset3d recipe object describing the rendering % parameters. This object includes the inputFile and the % outputFile, which are used to find the directories containing % all of the pbrt scene data. % % Return % renderRecipe - Updated by the processing in this function % % Zhenyi, 2018 % Henryk Blasinski 2020 % % Description % This includes a bunch of sub-functions and a logic that needs further % description. % % See also % piGeometryWrite %% p = inputParser; p.addRequired('thisR',@(x)isequal(class(x),'recipe')); %% Check version number if(thisR.version ~= 3) error('Only PBRT version 3 Cinema 4D exporter is supported.'); end %% give a geometry.pbrt % Best practice is to initalize the ouputFile. Sometimes peopleF % don't. So we do this as the default behavior. [inFilepath, scene_fname] = fileparts(thisR.inputFile); inputFile = fullfile(inFilepath,sprintf('%s_geometry.pbrt',scene_fname)); %% Open the geometry file % Read all the text in the file. Read this way the text indents are % ignored. fileID = fopen(inputFile); tmp = textscan(fileID,'%s','Delimiter','\n'); txtLines = tmp{1}; fclose(fileID); %% Check whether the geometry have already been converted from C4D % If it was converted into ISET3d format, we don't need to do much work. % It was not converted, so we go to work. thisR.assets = parseGeometryText(thisR, txtLines,''); % jsonwrite(AssetInfo,renderRecipe); % fprintf('piGeometryRead done.\nSaving render recipe as a JSON file %s.\n',AssetInfo); %{ % The converted flag is true, so AssetInfo is already stored in a % JSON file with the recipe information. We just copy it isnto the % recipe. % Save the JSON file at AssetInfo % outputFile = renderRecipe.outputFile; outFilepath = fileparts(thisR.outputFile); AssetInfo = fullfile(outFilepath,sprintf('%s.json',scene_fname)); renderRecipe_tmp = jsonread(AssetInfo); % There may be a utility that accomplishes this. We should find % it and use it here. fds = fieldnames(renderRecipe_tmp); thisR = recipe; % Assign the each field in the struct to a recipe class for dd = 1:length(fds) thisR.(fds{dd})= renderRecipe_tmp.(fds{dd}); end %} %% Make the node name unique [thisR.assets, ~] = thisR.assets.uniqueNames; end %% % function [trees, parsedUntil] = parseGeometryText(thisR, txt, name) % % Inputs: % % txt - remaining text to parse % name - current object name % % Outputs: % res - struct of results % children - Attributes under the current object % parsedUntil - line number of the parsing end % % Description: % % The geometry text comes from C4D export. We parse the lines of text in % 'txt' cell array and recrursively create a tree structure of geometric objects. % % Logic explanation: % parseGeometryText will recursively parse the geometry text line by % line. If current text is: % a) 'AttributeBegin': this is the beginning of a section. We will % keep looking for node/object/light information until we reach the % 'AttributeEnd'. % b) Node/object/light information: this could contain rotation, % position, scaling, shape, material properties, light spectrum % information. Upon seeing the information, parameters will be % created to store the value. % c) 'AttributeEnd': this is the end of a section. Depending on % parameters in this section, we will create different nodes and make % them as trees. Noted the 'branch' node will have children for sure, % so we assumed that before reaching the end of 'branch' seciton, we % already have some children, so we need to attach them under the % 'branch'. 'Ojbect' and 'Light', on the other hand will have no child % as they will be children leaves. So we simply create leave nodes % for them and return. % res = []; % groupobjs = []; % children = []; subtrees = {}; i = 1; while i <= length(txt) currentLine = txt{i}; % Return if we've reached the end of current attribute if strcmp(currentLine,'AttributeBegin') % This is an Attribute inside an Attribute [subnodes, retLine] = parseGeometryText(thisR, txt(i+1:end), name); subtrees = cat(1, subtrees, subnodes); %{ groupobjs = cat(1, groupobjs, subnodes); % Give an index to the subchildren to make it different from its % parents and brothers (we are not sure if it works for more than % two levels). We name the subchildren based on the line number and % how many subchildren there are already. if ~isempty(subchildren) subchildren.name = sprintf('%d_%d_%s', i, numel(children)+1, subchildren.name); end children = cat(1, children, subchildren); %} % assets = cat(1, assets, subassets); i = i + retLine; elseif piContains(currentLine,'#ObjectName') [name, sz] = piParseObjectName(currentLine); elseif piContains(currentLine,'ConcatTransform') [rot, translation, ctform] = piParseConcatTransform(currentLine); elseif piContains(currentLine,'MediumInterface') % MediumInterface could be water or other scattering media. medium = currentLine; elseif piContains(currentLine,'NamedMaterial') mat = piParseGeometryMaterial(currentLine); elseif piContains(currentLine,'Matieral') % in case there is no NamedMaterial mat = parseBlockMaterial(currentLine); elseif piContains(currentLine,'AreaLightSource') areaLight = currentLine; elseif piContains(currentLine,'LightSource') ||... piContains(currentLine, 'Rotate') ||... piContains(currentLine, 'Scale') % Usually light source contains only one line. Exception is there % are rotations or scalings if ~exist('lght','var') lght{1} = currentLine; else lght{end+1} = currentLine; end elseif piContains(currentLine,'Shape') shape = piParseShape(currentLine); elseif strcmp(currentLine,'AttributeEnd') % Assemble all the read attributes into either a groub object, or a % geometry object. Only group objects can have subnodes (not % children). This can be confusing but is somewhat similar to % previous representation. % More to explain this long if-elseif-else condition: % First check if this is a light/arealight node. If so, parse the % parameters. % If it is not a light node, then we consider if it is a node % node which records some common translation and rotation. % Else, it must be an object node which contains material info % and other things. if exist('areaLight','var') || exist('lght','var') % This is a 'light' node resLight = piAssetCreate('type', 'light'); if exist('lght','var') % Wrap the light text into attribute section lghtWrap = [{'AttributeBegin'}, lght(:)', {'AttributeEnd'}]; resLight.lght = piLightGetFromText(lghtWrap, 'print', false); end if exist('areaLight','var') resLight.lght = piLightGetFromText({areaLight}, 'print', false); if exist('shape', 'var') resLight.lght{1}.shape = shape; end if exist('rot', 'var') resLight.lght{1}.rotate = rot; end if exist('ctform', 'var') resLight.lght{1}.concattransform = ctform; end if exist('translation', 'var') resLight.lght{1}.translation = translation; end end if exist('name', 'var'), resLight.name = sprintf('%s_L', name); end subtrees = cat(1, subtrees, tree(resLight)); trees = subtrees; elseif exist('rot','var') || exist('translation','var') % This is a 'branch' node % resCurrent = createGroupObject(); resCurrent = piAssetCreate('type', 'branch'); % If present populate fields. if exist('name','var'), resCurrent.name = sprintf('%s_B', name); end if exist('sz','var'), resCurrent.size = sz; end if exist('rot','var'), resCurrent.rotation = rot; end if exist('ctform','var'), resCurrent.concattransform = ctform; end if exist('translation','var'), resCurrent.translation = translation; end %{ resCurrent.groupobjs = groupobjs; resCurrent.children = children; children = []; res = cat(1,res,resCurrent); %} trees = tree(resCurrent); for ii = 1:numel(subtrees) trees = trees.graft(1, subtrees(ii)); end elseif exist('shape','var') || exist('mediumInterface','var') || exist('mat','var') % resChildren = createGeometryObject(); resObject = piAssetCreate('type', 'object'); if exist('name','var') % resObject.name = sprintf('%d_%d_%s',i, numel(subtrees)+1, name); resObject.name = sprintf('%s_O', name); end if exist('shape','var'), resObject.shape = shape; end if exist('mat','var') resObject.material = mat; end if exist('medium','var') resObject.medium = medium; end subtrees = cat(1, subtrees, tree(resObject)); trees = subtrees; elseif exist('name','var') % resCurrent = createGroupObject(); resCurrent = piAssetCreate('type', 'branch'); if exist('name','var'), resCurrent.name = sprintf('%s_B', name); end %{ resCurrent.groupobjs = groupobjs; resCurrent.children = children; children = []; res = cat(1,res,resCurrent); %} trees = tree(resCurrent); for ii = 1:numel(subtrees) trees = trees.graft(1, subtrees(ii)); end end parsedUntil = i; return; else % warning('Current line skipped: %s', currentLine); end i = i+1; end %{ res = createGroupObject(); res.name = 'root'; res.groupobjs = groupobjs; res.children = children; %} trees = tree('root'); for ii = 1:numel(subtrees) trees = trees.graft(1, subtrees(ii)); end parsedUntil = i; end
github
ISET/iset3d-v3-master
piParseShape.m
.m
iset3d-v3-master/utilities/parse/piParseShape.m
4,291
utf_8
58163ce1cf2b2cbde45be66a5fe652e4
function shape = piParseShape(txt) % Parse the shape information into struct % Logic: % Normally the shape line has this format: % 'Shape "SHAPE" "integerindices" [] "point P" [] % "float uv" [] "normal N" []' % We split the string based on the '"' and get each component % % Test %{ thisR = piRecipeDefault('scene name', 'MacBethChecker'); %} %% keyWords = strsplit(txt, '"'); shape = shapeCreate; % keyWords if find(piContains(keyWords, 'Shape ')) shape.meshshape = keyWords{find(piContains(keyWords, 'Shape ')) + 1}; switch shape.meshshape case 'disk' shape.height = piParameterGet(txt, 'float height'); shape.radius = piParameterGet(txt, 'float radius'); shape.phimax = piParameterGet(txt, 'float phimax'); shape.innerradius = piParameterGet(txt, 'float innerradius'); case 'shpere' shape.radius = piParameterGet(txt, 'float radius'); shape.zmin = piParameterGet(txt, 'float zmin'); shape.zmax = piParameterGet(txt, 'float zmax'); shape.phimax = piParameterGet(txt, 'float phimax'); case 'cone' shape.height = piParameterGet(txt, 'float height'); shape.radius = piParameterGet(txt, 'float radius'); shape.phimax = piParameterGet(txt, 'float phimax'); case 'cylinder' shape.radius = piParameterGet(txt, 'float radius'); shape.zmin = piParameterGet(txt, 'float zmin'); shape.zmax = piParameterGet(txt, 'float zmax'); shape.phimax = piParameterGet(txt, 'float phimax'); case 'hyperboloid' shape.p1 = piParameterGet(txt, 'point p1'); shape.p2 = piParameterGet(txt, 'point p2'); shape.phimax = piParameterGet(txt, 'float phimax'); case 'paraboloid' shape.radius = piParameterGet(txt, 'float radius'); shape.zmin = piParameterGet(txt, 'float zmin'); shape.zmax = piParameterGet(txt, 'float zmax'); shape.phimax = piParameterGet(txt, 'float phimax'); case 'curve' % todo case {'trianglemesh', 'plymesh'} if find(piContains(keyWords, 'filename')) shape.filename = piParameterGet(txt, 'string filename'); % shape.filename = keyWords{find(piContains(keyWords, 'filename')) + 2}; end if find(piContains(keyWords, 'integer indices')) shape.integerindices = uint64(piParameterGet(txt, 'integer indices')); % Convert it to integer format % shape.integerindices = keyWords{find(piContains(keyWords, 'integer indices')) + 1}; end if find(piContains(keyWords, 'point P')) shape.pointp = piParameterGet(txt, 'point P'); % shape.pointp = keyWords{find(piContains(keyWords, 'point P')) + 1}; end if find(piContains(keyWords, 'float uv')) % If file extension is ply, don't do this. ext = ''; if ~isempty(shape.filename) [~, ~, ext] = fileparts(shape.filename); end if isequal(ext, '.ply') else shape.floatuv = piParameterGet(txt, 'float uv'); % shape.floatuv = keyWords{find(piContains(keyWords, 'float uv')) + 1}; end end if find(piContains(keyWords, 'normal N')) shape.normaln = piParameterGet(txt, 'normal N'); % shape.normaln = keyWords{find(piContains(keyWords, 'normal N')) + 1}; end % to add % float/texture alpha % float/texture shadowalpha case 'heightfield' % todo case 'loopsubdiv' % todo case 'nurbs' % todo end end end function s = shapeCreate s.meshshape = ''; s.filename=''; s.integerindices = ''; s.pointp = ''; s.floatuv = ''; s.normaln = ''; s.height = ''; s.radius = ''; s.zmin = ''; s.zmax = ''; s.p1 = ''; s.p2=''; s.phimax = ''; end